Last-modified: 2017-07-24 (月) 02:57:37
PowerShell/チートシート

スクリプト

実行権限の変更

Everything is expanded.Everything is shortened.
  1
  2
  3
-
|
!
# 要 管理者権限
# RemoteSignedはローカルスクリプトは許可、それ以外は署名が必要という権限
Set-ExecutionPolicy RemoteSigned

標準出力、標準エラー出力

標準出力、標準エラー出力の一括リダイレクト

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
-
!
-
!
# 新規
<コマンド> > <出力先パス> 2>&1
# 追記
<コマンド> >> <出力先パス> 2>&1

標準出力、標準エラー出力をファイルに記録

Everything is expanded.Everything is shortened.
  1
  2
 
 
start-transcript <出力先パス>
stop-transcript <出力先パス>

ファイル

テンポラリファイル名作成

Everything is expanded.Everything is shortened.
  1
 
[System.IO.Path]::GetTempFileName()

ハッシュ値を取得

Everything is expanded.Everything is shortened.
  1
 
Get-FileHash -Algorithm <アルゴリズム(e.g, MD5, SHA1, SHA256 ...)> <ファイルパス>

オブジェクト

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
-
!
 
-
!
# オブジェクトのメソッド/プロパティを一覧表示
<object> | Get-Member 
 
# 変数一覧
Get-Variable

エイリアス

Everything is expanded.Everything is shortened.
  1
  2
-
!
# エイリアス一覧
Get-Alias

配列

Everything is expanded.Everything is shortened.
  1
  2
-
!
# 配列末尾
$foo[-1]

変数

変数展開

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
-
!
 
-
-
|
!
 
-
!
-
-
|
!
# 単純な場合
${<変数名>}
$($<変数名>)
# 例.
"aaa${foo}"
"aaa$($foo)"
"aaa{0}" -f $foo
 
# プロパティの場合
$($<変数名>.<プロパティ>)
# 例.
"aaa$(${foo}.bar)"
"aaa$($foo.bar)"
"aaa{0}" -f $foo.bar

文字列

SecurityString変換

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
-
!
 
-
!
 
# String→SecurityString
$secureString = ConvertTo-SecureString "<文字列>" -AsPlainText -Force
 
# SecurityString→String
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
$plainString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

その他

バージョンの表示

Everything is expanded.Everything is shortened.
  1
 
$PSVersionTable

パスワード作成

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
 
 
 
-
!
Add-type -AssemblyName System.Web;
[System.Web.Security.Membership]::GeneratePassword(<パスワードの文字数>, <英数字以外の文字の最小数(最小数の保証なので、0と指定しても英数字以外が入る可能性はある)>)
 
# 例. 16文字で最低3文字は英数記号以外の文字
Add-type -AssemblyName System.Web;[System.Web.Security.Membership]::GeneratePassword(16,3)