バッチファイルに複数のパワーシェルスクリプトを埋め込む方法 引数の指定可能 powershell / How to embed multiple PowerShell scripts in a batch file with arguments in PowerShell

2024年9月14日

バッチファイル

自分自身のバッチファイルの中で複数のパワーシェルのスクリプト記述して実行したい時に有効です

表現方法がいろいろあるのでお好きな表現を組み合わせて使ってください

@powershell -Command  "& (Invoke-Expression -Command ('{' + (((Get-Content %~f0 )[4..5]) | Out-String )+ '}'))" %*
@powershell -Command  "& (Invoke-Expression -Command ('{' + (((Get-Content %~f0 )[6..8]) | Out-String )+ '}'))" %*
timeout /t 5&goto:eof

# PowerShellスクリプト
"Time: $([DateTime]::Now)"
# 
Write-Host $Args[0]
Write-Host $Args[1]

別な書き方

@powershell -Command  "& (Invoke-Expression -Command ('{' + (((Get-Content %~f0 )[12..19]) -join \"`n\")+ '}'))" %*

日本語を含むShift-JISのバッチファイルを読むpowershell7

新しいバージョンのパワージェルはUTF 8 として読み込むので普通に読むと文字化けをします

@pwsh -NoProfile -Command  "& (Invoke-Expression -Command ('{' + (Get-Content %~f0 -Encoding Shift-JIS | Where-Object {$_.readcount -gt 9}| Out-String )+ '}'))" %*

先頭の行にパワーシェルを記述し2行目以降にスクリプトを書く

@powershell -Command  "& (Invoke-Expression -Command ('{' + (Get-Content %~f0 | Select-Object -Skip 1 | Out-String )+ '}'))" %*
@powershell -Command  "& (Invoke-Expression -Command ('{#' + (Get-Content %~f0 | Out-String )+ '}'))" %*&goto:eof
@powershell -Command  "& (Invoke-Expression -Command ('{' + (Get-Content %~f0 | Where-Object {$_.readcount -gt 1}| Out-String )+ '}'))" %*&goto:eof
@powershell "$s=[scriptblock]::create((Get-Content %~f0| Where-Object {$_.readcount -gt 1})-join\"`n\");&$s" %*&goto:eof
@powershell -NoProfile -ExecutionPolicy Unrestricted "$s=[scriptblock]::create((gc \"%~f0\"|?{$_.readcount -gt 1})-join\"`n\");&$s  %*&goto:eof

パラメーターが不要な場合

@powershell "Get-Content %~f0  |Where-Object {$_.readcount -gt 8} |Invoke-Expression "  &exit/b
@powershell/c '#'+(Get-Content  \"%~f0\"-raw)^|Invoke-Expression &timeout /t 50&goto:eof

補足

@powershell -Command  "& (Invoke-Expression -Command ('{' + (((Get-Content %~f0 )[4..5]) | Out-String )+ '}'))" %*

@powershell -Command 自分は表示せずパワーシェルのコマンド実行
& (Invoke-Expression -Command 文字列を実行
('{' + スクリプトブロックを開始
(((Get-Content %~f0 )[4..5]) 自分自身のバッチファイルを読み込み5行目6行目を読み込む
| Out-String ) オブジェクト型を文字列型に変更

'}’))" スクリプトブロックを終了
%* パッチファイルの引数

省略

Invoke-Expression iex
Get-Content gc
Where-Object %

bat,PowerShell 

Posted by eightban