← Back to Home

Remote PowerShell スクリプトの実行

Views: 880

You can try the commands on our interactive shell.

Remote PowerShell スクリプトの実行

PowerShellは、タスク自動化とシステム管理において非常に強力なツールです。remoteマシンでのPowerShellスクリプト実行という機能がその一例です。このチュートリアルでは、PowerShell Remotingを使用して複数のマシンに対して同時にスクリプトを実行する方法について説明します。

前提条件

始める前に、以下のことを確認してください:

PowerShell Remoting の理解

PowerShell Remotingは、local マシンで実行したようにremote マシンでのPowerShell コマンドやスクリプトを実行できる機能です。これにより、WS-Management(WSMan)プロトコルを使用してremote システムと通信することができます。

remote するには、各マシンで Windows Remote Management サービス(WSMAN)を有効にする必要があります。Windows Server 2012 以降では、このサービスが既に有効になっています 古いバージョンの Windows の場合は、次のコマンドを使用して手動で有効にする必要があります:

Enable-WindowsFeature -Name WS-MAN-PSRemoting-Inbox

remote マシンでの PowerShell スクリプト実行

remote マシンでのPowerShellスクリプト実行には、Invoke-Command コマンドレットを使用します。次の例を見てみてください:

Invoke-Command -ComputerName <remote_machine_name> -ScriptBlock { Get-Process }

この例では、<remote_machine_name> はスクリプトを実行する対象のマシンの名前やIPアドレスです。Get-Process コマンドレットは、remote マシン上の実行中のプロセスの一覧を取得します。

追加のパラメーターを使用してスクリプトの実行を制御することもできます:

次の例を見てみてください:

Invoke-Command -ComputerName <remote_machine_name> -Credential (Get-Credential) -Authentication Kerberos -ScriptBlock {
    Get-Process | Where-Object {$_.ProcessName -eq "chrome"} | Select-Object ProcessName, Id, StartTime
}

この例では、Get-Credential コマンドレットを使用して代替クレデンシャルを提示しています。また、Kerberos 認証機構を指定し、remote マシン上の Chrome プロセスに関する情報を取得するためにscript ブロックを実行しています。

複数の remote マシンに対して同時にスクリプトを実行

複数の remote マシンに対して同時にスクリプトを実行するには、Invoke-Command コマンドレットを使用してcomputer name の配列を指定します:

$computers = @("remote_machine1", "remote_machine2", "remote_machine3")
Invoke-Command -ComputerName $computers -ScriptBlock { Get-Process }

この例では、computer name の配列を作成し、その配列を Invoke-Command コマンドレットに渡しています。スクリプト ブロックは各マシンでの実行を繰り返します。

また、For Each ループを使用して computer name の配列を繰り返すこともできます:

$computers = @("remote_machine1", "remote_machine2", "remote_machine3")
foreach ($computer in $computers) {
    Invoke-Command -ComputerName $computer -ScriptBlock { Get-Process }
}

この例では、For Each ループを使用して computer name の配列を繰り返しています。スクリプト ブロックは各マシンでの実行を繰り返します。

最高の慣習と考慮

remote マシンでのPowerShell スクリプト実行を行う際には、以下の最高の慣習と考慮に注意してください:

結論

remote マシンでのPowerShell スクリプト実行は、タスク自動化とシステム管理において非常に強力な方法です。PowerShell Remoting を使用して複数のマシンに対して同時にスクリプトを実行することで、Automation という新しい世界に踏み込むことができます。慣習と考慮に注意し、練習や努力を積むことで、この機能を完全にマスターすることができます!

Try it Now!