PowerShell 複製檔案並重新命名
Salman Mehmood
2025年2月25日
PowerShell
PowerShell File

本文的主要目的是展示最基本的輸入輸出操作,複製一個文件然後將其粘貼到另一個目錄或位置並改名。
PowerShell 複製文件和重命名
在處理 CSV 文件時,可能需要複製特定的 CSV 文件並將其粘貼到其他地方,並從 CSV 中提取文件名。
考慮以下 CSV:
iid firstname lastname profession oldfilepath newfilename
-- --------- -------- ---------- ----------- -----------
100 Annecorinne Fitzsimmons doctor D:\\old.csv new2.csv
101 Mallory Dunkin firefighter D:\\old.csv new3.csv
102 Carlie Torray firefighter D:\\old.csv new4.csv
103 Marleah Boycey worker D:\\old.csv new5.csv
104 Lusa Corabella worker D:\\old.csv new6.csv
105 Shandie Chesna worker D:\\old.csv new7.csv
106 Melisent Ochs doctor D:\\old.csv new8.csv
107 Cathie Hurley firefighter D:\\old.csv new9.csv
108 Kerrin Regan doctor D:\\old.csv new10.csv
109 Alie Lewes police officer D:\\old.csv new11.csv
110 Jsandye Gemini police officer D:\\old.csv new12.csv
111 Marguerite Myrilla police officer D:\\old.csv new13.csv
112 Florie Dichy developer D:\\old.csv new14.csv
113 Krystle Gaulin doctor D:\\old.csv new15.csv
114 Odessa Nerita developer D:\\old.csv new16.csv
現在我們需要複製這個 CSV,並將其粘貼到另一個目錄中,並使用來自 CSV 文件中的一列的自定義名稱。在這種情況下,該列名為 newfilename
。
考慮以下代碼:
$csv = "D:\\old.csv"
Import-Csv $csv | % { Write-Host "Copying $($_.oldfilepath) to D:\TEST\$($_.newfilename)..." | Copy-Item $_.oldfilepath -Destination "D:\TEST\$($_.newfilename)" }
然後,我們可以使用以下方法驗證文件是否已被複製:
> .\script.ps1
> ls D://TEST
Directory: D:\TEST
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 11/1/2022 10:27 PM 861 new10.csv
-a--- 11/1/2022 10:27 PM 861 new11.csv
-a--- 11/1/2022 10:27 PM 861 new12.csv
-a--- 11/1/2022 10:27 PM 861 new13.csv
-a--- 11/1/2022 10:27 PM 861 new14.csv
-a--- 11/1/2022 10:27 PM 861 new15.csv
-a--- 11/1/2022 10:27 PM 861 new16.csv
-a--- 11/1/2022 10:27 PM 861 new2.csv
-a--- 11/1/2022 10:27 PM 861 new3.csv
-a--- 11/1/2022 10:27 PM 861 new4.csv
-a--- 11/1/2022 10:27 PM 861 new5.csv
-a--- 11/1/2022 10:27 PM 861 new6.csv
-a--- 11/1/2022 10:27 PM 861 new7.csv
-a--- 11/1/2022 10:27 PM 861 new8.csv
-a--- 11/1/2022 10:27 PM 861 new9.csv
使用上述代碼,我們可以從其中一列中提取要複製的文件,以及要保存的新文件的名稱。
程序的整體流程如下:
- 要從中提取路徑和文件名的 CSV 文件的路徑存儲在名為
csv
的變量中。$
符號主要用於在 PowerShell 中聲明和訪問/設置變量。 Import-csv
命令從 CSV 文件中提取數據。- 在提取了相關數據後,使用
|
運算符將其傳遞到下個命令。 %
運算符(foreach
循環的別名)用於迭代提取oldfilepath
和newfilename
列的數據,然後將其傳遞給Copy-Item
命令,以便將文件從給定的源複製到目的地(在我們的情況下未在 CSV 中指定)。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Salman Mehmood
Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.
LinkedIn