如何使用 PowerShell 將專案從一個位置複製到另一個位置?


要在 PowerShell 中複製專案,需要使用 **Copy-Item** cmdlet。使用 **Copy-Item** 時,需要提供原始檔名和目標檔名或資料夾名。

在下面的示例中,我們將從 **D:\Temp** 複製單個檔案到 **D:\Temp1** 位置。

示例

Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru

輸出

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands.csv

在上面的示例中,**PowerShellCommands.csv** 檔案將從 **D:\Temp** 複製到 **D:\Temp1** 位置。如果檔案已存在,則它會簡單地覆蓋該檔案,而不會有任何提示、錯誤或警告。

在命令中使用 –**Passthru** 引數時,它會在控制檯中顯示輸出。

您也可以在使用複製命令時重新命名專案。為此,需要在目標引數中提及新的檔名。

示例

Copy-Item -Path D:\Temp\PowerShellcommands.csv 
-Destination D:\Temp1\PowerShel lcommands1.csv -PassThru

輸出

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\PowerShellcommands1.csv -PassThru
    Directory: D:\Temp1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       20-01-2020     12:10        1148809 PowerShellcommands1.csv

在將專案複製到另一個位置時,它們的屬性也會隨之複製。

當您將檔案從原始檔夾複製到目標資料夾時,如果目標資料夾不存在,則檔案將不會被複制,並且會丟擲 **DirectoryNotFoundException** 異常。

示例

例如,我們將上面提到的 **PowerShellcommands1.csv** 檔案複製到未知目標資料夾 **D:\Temp2**,如下所示。

Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShel
lcommands.csv -PassThru

輸出

PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShellcommands.csv -PassThru
Copy-Item : Could not find a part of the path 'D:\Temp2\PowerShellcommands.csv'.
At line:1 char:1
+ Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand

更新於: 2020年3月12日

16K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告