0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Powershell埋め込みバッチファイル(自分用)

Last updated at Posted at 2020-04-18

特徴

・2行目以降にPowershellスクリプトを書ける
・ダブルクリックで実行できる、オプションを渡すこともできる。
・最小化状態で起動する
・$env:SELFPATHでPowershellスクリプト(バッチファイル)本体のパスを取得できる
・外部powershellファイルを呼び出して実行できる

いろんなサイトを参考に組み合わせたものです、参考サイトは参考サイトにリンクを張っておきます。

スクリプト

下記のコードをコピーして1行目に貼り付け、バッチファイルとして保存します。

@if not "%~0"=="%~dp0.\%~nx0" (start /min cmd /c,"%~dp0.\%~nx0" %* & goto :eof)  else  (setlocal enableextensions enabledelayedexpansion & set "SELFPATH=%~dp0" & set "SELF=%~f0" & PowerShell.exe -ExecutionPolicy Bypass -Command "& (Invoke-Expression -Command ('{#' + ((Get-Content '!SELF:'=''!') -join \"`n\") + '}'))" %* & exit /b !errorlevel!)

メモ

コンソールウインドウを最小化から通常状態に戻す

エラーや入力待ちの入力を促す際に使えると思います。最小化するには7行目の61728を61472に変えます。

$title = $Host.UI.RawUI.WindowTitle;
$Host.UI.RawUI.WindowTitle += (new-object random).next();
$process = (ps | where {$_.MainWindowTitle -eq $Host.UI.RawUI.WindowTitle});
$Host.UI.RawUI.WindowTitle = $title;
$hwnd = $process.MainWindowHandle;
[void][Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');
$message = [System.Windows.Forms.Message]::Create($hwnd, 274, 61728, 0);
$nativeWindow = new-object System.Windows.Forms.NativeWindow;
$nativeWindow.DefWndProc([ref]$message)

参考サイト:PowerShellの1行バッチでコンソールウィンドウを最小化/最大化/元に戻す。

引数を解釈する(簡易版)

$arghash = @{}
$arghash["_blank"] = @()
if($args.Count -gt 0){
    $argname = "_blank"
    foreach($argval in $args){
        if($argval.StartsWith("-")){
            $argname = $argval.substring(1, $argval.Length-1)
            if(!($arghash.ContainsKey($argname))){
                $arghash[$argname] = @()
            }
        }else{
            $arghash[$argname] += $argval
        }
    }
}

参考サイト

PowerShell - バッチファイル内に記述したスクリプトを実行する。
コマンドファイルを最小化した状態で実行します

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?