Last active
October 7, 2019 10:15
-
-
Save h1romas4/4b2e728faf131c345205b4b923c9aa50 to your computer and use it in GitHub Desktop.
PowerShell を使ったリモートサーバー操作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# プレーンな user/password 文字列からの認証情報をつくる | |
# | |
$username = "DOMAIN\username" | |
$secure = ConvertTo-SecureString "xxxxxxxx" -AsPlainText -Force | |
$credential = New-Object System.Management.Automation.PsCredential($username, $secure) | |
# | |
# Enter-PSSession 相手のサーバーに対話式でログインしたい場合 (exit で抜けます) | |
# | |
Enter-PSSession -ComputerName $hostname -Credential $credential | |
# | |
# Invoke-Command 相手のサーバーでコマンドを実行したい場合(返値も取得) | |
# | |
# セッション接続(credential に認証情報を作成しておく) | |
$session = New-PSSession -ComputerName $hostname -Credential $credential | |
# コマンド、引数設定 | |
$command = "Get-ChildItem" # 相手で実行したいコマンド | |
$args1 = "" # 引数1 | |
$args2 = "" # 引数2 | |
$args3 = "" # 引数3 | |
# 相手先でコマンド実行(相手側の標準出力も取得) | |
Invoke-Command -Session $session -ScriptBlock { | |
& $using:command $using:args1 $using:args2 $using:args3 | |
} | %{ | |
[void] (Write-Host $_) | |
} | |
# 相手先の環境変数からリターンコードを取得 | |
$rc = Invoke-Command -Session $session -ScriptBlock { $LASTEXITCODE } | |
# セッション切断 | |
Remove-PSSession -Session $session |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment