●コマンドレットとコマンド
# Get-ChildItemコマンドレットを()で囲い、オブジェクトを返し、そのオブジェクトに対して、GetTypeコマンドを実行している
PS C:\Users\foo\Desktop\PowerShellCookbook_Samples> (Get-ChildItem).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
●オブジェクトのメンバーメソッドならびにプロパティ
# Get-ChildItemコマンドレットによってオブジェクトを出力し、それをパイプしてGet-Memberコマンドレットの入力としている。オブジェクトのメンバーメソッドならびにプロパティが分かる
PS C:\Users\foo\Desktop\PowerShellCookbook_Samples> Get-ChildItem | Get-Member
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
LinkType CodeProperty System.String LinkType{get=GetLinkType;}
Mode CodeProperty System.String Mode{get=Mode;}
Target CodeProperty System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Target{get=GetTarget;}
AppendText Method System.IO.StreamWriter AppendText()
CopyTo Method System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(string destFileName, bool overwrite)
Create Method System.IO.FileStream Create()
:省略
●$() # サブ式
$(some_command), `some_command` # Linuxでいうところのコマンド置換
●スクリプトの実行
$Ret = Invoke-Command -ScriptBlock { C:\Users\foo\Downloads\log\test.ps1 }
$Ret
C:\Users\foo\Downloads\log\test.ps1 : このシステムではスクリプトの実行が無効になっているため、ファイル C:\Users\foo\Downloads\log\test.ps1 を読み込むことができません。詳細については、「about_Ex
ecution_Policies」(http://go.microsoft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:3 文字:38
+ $Ret = Invoke-Command -ScriptBlock { C:\Users\foo\Downloads\log\test.ps1 }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : セキュリティ エラー: (: ) []、PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
PS C:\Users\foo\Downloads\log> Get-ExecutionPolicy
Restricted
# 実行できるように設定
PS C:\Users\foo\Downloads\log> Set-ExecutionPolicy RemoteSigned
PS C:\Users\foo\Downloads\log> Get-ExecutionPolicy
RemoteSigned
●Return値を取りたい
# 呼び出し元コード:
$Ret = Invoke-Command -ScriptBlock { C:\Users\foo\Downloads\log\test.ps1 }
$Ret
$LASTEXITCODE
# test.ps1の中身(1回目)
Write-Host "AAA"
exit 99
=>
AAA # write-hostコマンドレットで出力されるので注意
99 # exitの引数が、$LASTEXITCODE変数の値になる
# test.ps1の中身(2回目)
#Write-Host "AAA" # コメントアウト
get-date
$?
exit 99
=>
2016年12月17日 22:46:07
True # get-dateコマンドレットが成功しているので「真」
99
#test.ps1の中身 (3回目)
#Write-Host "AAA"
get-dates # 故意に、存在しないコマンドレットを記入
$?
exit 99
=>
get-dates : 用語 'get-dates' は、コマンドレット、関数、スクリプト ファイル、または操作可能なプログラムの名前として認識されません。名前が正しく記述されていることを確認し、パスが含まれている場合はそのパスが正しいことを確認してから、再試行してください。
発生場所 C:\Users\foo\Downloads\log\test.ps1:2 文字:1
+ get-dates
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (get-dates:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
False # 実行が失敗しているので「偽」となる
99
参考:
http://syghira.hateblo.jp/entry/2012/04/09/005029
http://win.just4fun.biz/PowerShell/PowerShell%E3%81%A7exit%E3%81%AE%E5%80%A4%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95%E3%83%BB$lastexitcode.html#be6c6e79