PowerShell Invoke-Command ログファイルの取得

正常および異常のログファイルを確認するために、毎回 エクスプローラ または リモートデスクトップ接続 をするのが面倒なのでローカルPCにログを持ってくる。
FTPは使用したくないので Invoke-Command でリモートPCで Get-Content を行い、その内容をファイルへ出力する。

前提条件

  • Windows 7 Professional
  • $PSVersionTable PSVersion=5.0.10586.117
  • 対象サーバの Windows リモート管理 (WinRM) 機能が有効
  • ファイルを選択し右クリック → PowerShell で実行

get_server_logs.ps1

$user   = "{ユーザ名}"
$pass   = ConvertTo-SecureString "{パスワード}" -AsPlainText -Force
$remote = "{IPアドレス}"

$credential = New-Object System.Management.Automation.PSCredential $user, $pass

$session = New-PSSession $remote -Credential $credential 
$result_info  = Invoke-Command -Session $session -ScriptBlock { Get-Content {正常ログファイルへのPATH} }
$result_error = Invoke-Command -Session $session -ScriptBlock { Get-Content {異常ログファイルへのPATH} }
Remove-PSSession $session

$path = Split-Path $MyInvocation.MyCommand.Path -Parent
$result_info  | Out-File ($path + "\" + $remote + "_{正常ログファイル名}.log")
$result_error | Out-File ($path + "\" + $remote + "_{異常ログファイル名}.log")