PowerShell で リモートPC に フォルダ または ファイル をコピーする

リモートデスクトップ接続をして日付フォルダを作成して、そこにファイルをコピーする作業を PowerShell で行うようにする。

前提条件

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

copy_item_to_remote.ps1

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

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

$session = New-PSSession $remote -Credential $credential 
Invoke-Command -Session $session -ScriptBlock { New-Item -Path "{リモートPC上のパス}\YYYYMMDD" -ItemType "Directory" -Force }
Copy-Item -Path "{ローカルPC上のパス}" -Destination "{リモートPC上のパス}\YYYYMMDD" -ToSession $session -Recurse
Remove-PSSession $session