假設資料夾 1 為 D:\doc,資料夾 2 為 D:\txt,其內分別儲存 .doc 與 .txt 檔,要將資料夾 1 中,主檔名與資料夾 2 主檔名相同的檔案搬移到另外一個資料夾(D:\newdoc)。
要如何使用 Wondows PowerShell 進行這樣操作呢?
例如:
資料夾 1(D:\doc)內有下列檔案:
- a.doc
- b.doc
- c.doc
- aa.doc
- ab.doc
- ac.doc
資料夾 2(D:\txt)內有下列檔案:
- a.txt
- aa.txt
- bb.txt
- cc.txt
資料夾 1 與資料夾 2 中,相同主檔名的有:
- a
- aa
所以要將 a.doc 與 aa.doc 搬移到新資料夾(D:\newdoc)。Windows PowerShell 程式碼如下:
# 宣告變數
$folderA = "D:\doc\"
$folderB = "D:\txt\"
$folderNew = "D:\newdoc\"
# 找出資料夾中的每個檔案
foreach ($fileA in Get-ChildItem $folderA)
{
# 組出另一資料夾中的檔名
# 方法 1
$fileB = $folderB + $fileA.Name.Remove($fileA.Name.Length - $fileA.Extension.Length) + ".txt"
# 方法 2,此法有缺點,萬一檔名中有數個 .doc 都會被換成 .txt
#$fileB = $folderB + $fileA.Name.ToLower().Replace(".doc", ".txt")
# 檢查檔案是否存在資料夾中
If (Test-Path $fileB) {
"搬移檔案: $fileA"
$fileA.MoveTo($folderNew + $fileA.Name)
}
}