【PowerShell】PSComputerName プロパティの存在を忘れずに

Windows PowerShell を使用してリモートコンピューターに対して処理を行うには、-ComputerName パラメタを使用するのが一般的です。

例えば、リモートコンピューターのサービス一覧を取得するには、以下のように入力します。

Get-Service –ComputerName Target01

結果は以下の通りです。

Status Name DisplayName
------ ---- -----------
Stopped AeLookupSvc Application Experience
Stopped ALG Application Layer Gateway Service
Running AppHostSvc Application Host Helper Service
Running AppIDSvc Application Identity


出力結果にコンピューター名を含めたい場合には、以下のように書きます。

Get-Service –ComputerName Target01 | Select-Object MachineName,Name,Status

MachineName Name Status
----------- ---- ------
Target01 AeLookupSvc Stopped
Target01 ALG Stopped
Target01 AppHostSvc Running
Target01 AppIDSvc Running

では、リモートコンピューターのサービスを停止したい場合はどうでしょう。

サービスを停止するのは Stop-Service コマンドレットを使用しますが、Stop-Service には –ComputerName パラメタが用意されていません。

じゃ、どうするか。

Invoke-Command コマンドレットを使用して、以下のように書きます。以下は、Windows Update サービスを停止しています。

Invoke-Command –ComputerName TARGET01 { Stop-Service wuauserv }

ただ、これだと戻り値が無いので、本当に止まったのかどうかがわかりません。そこで、Get-Service wuauserv も一緒に実行します。

Invoke-Command -ComputerName TARGET01 {Stop-Service wuauserv; Get-Service wuauser}

Status Name DisplayName PSComputerName
------ ---- ----------- --------------
Stopped wuauserv Windows Update tfdc02        

ここで、PSComputerName に注目してください。

ためしに、以下のコマンドレットで Get-Service の出力結果に PSComputerName が含まれているか確認してみましょう。

Get-Service | Get-Member -Name PSComputerName

何も出力されません。つまり、PSComputerName は Get-Service の出力結果ではないということがわかります。

実は、PSComputerName は Invoke-Command の出力結果に含まれるプロパティの1つです。

Invoke-Command はリモートコンピューターに接続する際に PSセッションを作成しますが、このとき PSComputerName には接続先のコンピューター名が格納されます。

では、MachineName はどうなったのでしょう?

以下のコマンドレットを入力してみてください。

Invoke-Command -ComputerName TARGET01 {Start-Service wuauserv; Get-Service wuauser} | Select-Object MachineName,Name,Status

MachineName Name Status
----------- ---- ------
. wuauserv Stopped

MachineName には「.(ドット)」が格納されています。勘の良い方ならばおわかりのように、これは「Current Computer」を意味しています。

Invoke-Command は、コマンドをリモートコンピューターに投げて、リモートで実行した結果を受け取ります。だから MachineName には Current Computer を意味する「.」が格納されているわけです。

image

一方で、Get-Service –ComputerName Target01 はといえば、Get-Service コマンドレットが実行されるのはローカルです。MachineName プロパティには Get-Service のターゲットコンピューターが格納されるので、-ComputerName パラメタと同じ値を取得することができます。

image

このように、PowerShell リモーティングでは、そのコマンドがどこで実行されるのかを意識しておく必要があります。

PCComputerName は、リモーティングではとても重要なぱらめたです。ぜひ覚えておいてください。