PowerShell Basic

PowerShell Basic

前提知識

スクリプトの実行
  • スクリプトファイルの拡張子:.ps1
  • スクリプトを実行するには、実行ポリシーを設定する必要あり(要管理者権限)
> Set-ExecutionPolicy -RemoteSigned
# RemoteSigned : ローカルスクリプトは実行可、ダウンロードしたものは要署名
> Get-ExecutionPolicy # 設定できているかの確認
ヘルプ
> help <コマンドレット名>
コメント
  • #でコメント(1行)
  • <# ... #>でコメント(複数行)
リダイレクト
  • >でリダイレクト
  • >>でリダイレクト(追記)
変数
  • 変数名の先頭は$で始まる
  • 大文字/小文字は区別されない
  • 型は、.NETのものが使用できる
  • 型を指定するには、変数名の前に型を記載
$tmp = "temp"
[int]$cnt = 123 # 型を指定
[string]$str = "test"
定数
  • 文字列は、シングルorダブルクォーテーションで囲む
    • シングルクォーテーションの場合は、変数展開なし
    • ダブルクォーテーションの場合は、変数展開あり
  • 文字列連結は、「+」記号
  • エスケープシーケンスはバッククォート
    • タブ : `t
    • 改行 : `r`n
演算子
演算子 意味
-eq ==
-ne !=
-gt >
-ge >=
-lt <
-le <=

ファイル関連

フロー制御

for
for($i=0;$i<3:$i++)
{
    # 処理
}

foreach($tmp in array)
{
    # 処理
}
if
if($tmp==1)
{
}
elseif($tmp==2)
{
}
else
{
}

関数

パラメーターなし
function func1{
    Write-Output "func1 call"
}

func1
パラメーターあり
function func2 {
    param (
        $arg1,
        $arg2
    )
    Write-Output "func2 call"
    Write-Output " arg1 : $arg1"
    Write-Output " arg2 : $arg2"
}

func2 "abc" 123
パラメーターあり(型指定あり)
function func3 {
    param (
        [string]$arg1,
        [int]$arg2
    )
    Write-Output "func3 call"
    Write-Output " arg1 : $arg1"
    Write-Output " arg2 : $arg2"
}

func3 -arg2 456 -arg1 "ABC"