如何在PowerShell中複製檔案/資料夾到遠端位置?


要將檔案或資料夾複製到遠端位置或從遠端位置複製檔案或資料夾,您需要提供專案的UNC路徑。例如,我們將把一個檔案從本地計算機複製到名為Test-PC的遠端計算機。

Copy-Item D:\Temp\PowerShellcommands.csv -Destination \Test-
PC\Sharedpath\PScommands.ps1 -PassThru

這裡,檔案PowerShellcommands.csv被複制到遠端計算機,並將其重新命名為PSCommands.ps1

您也可以將檔案從一個共享位置複製到另一個共享位置。

例如:

Copy-Item \Test-PC1\D$\PowerShellcommands.csv -Destination \Test-
PC\Sharedpath\PScommands.ps1 -PassThru

另一種將專案複製到遠端位置的方法是使用ToSession引數。要使用ToSession引數,您需要使用PSRemote計算機會話連線遠端計算機,如果目標檔案/資料夾位於不同的域或工作站,則需要在遠端連線時使用不同的憑據。

例如:

$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)
Copy-Item D:\Temp\PowerShellcommands.csv -ToSession $destsession -PassThru

您也可以使用上述相同的方法複製資料夾。

例如:

$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)
Copy-Item D:\Temp\* -ToSession $destsession -Force -PassThru

您還可以使用帶有–FromSession引數的源路徑將檔案從一個會話複製到另一個會話,而目標路徑應使用–ToSession引數。

例如:

$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)
$sourcesession = New-PSSession -ComputerName Test1-PC -Credential (Get-Credential)
Copy-Item -FromSession $sourcesession -ToSession $destsession -PassThru

更新於:2020年3月12日

4K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告