兩周前我開始學習 powershell。我有以下檔案夾結構
C:\not prepared\Not ready
ABCD_EFGH-whatever\work
IJK-whatever\work
LMN-whatever\work
OPRSTU_WXYZ-whatever\work
C:\Already ready
ABCD_EFGH
IJK
LMN
OPRWXY
該腳本將從C:\Already ready. 我想每個移動work檔案夾從"Not ready\*\"以"Already ready\*"獲得
C:\not prepared\Not ready
ABCD_EFGH-whatever
IJK-whatever
LMN-whatever
OPRSTU_WXYZ-whatever
C:\Already ready
ABCD_EFGH\work
IJK\work
LMN\work
OPRWXY\work
我不想指定確切的檔案夾名稱,因為這些名稱可能會改變。只有來自Not ready和Already ready子檔案夾的前 3 個字符匹配。我想我應該從兩個位置讀取所有子檔案夾的名稱,然后將它們放在一個陣列中并一一比較名稱。此外,并非所有檔案夾都可能始終存在于C:\not prepared\Not ready.
有沒有更聰明的方法來做到這一點?請給我一個提示或例子。
uj5u.com熱心網友回復:
Get-Item 'C:\not prepared\Not ready\*\work' | ForEach-Object {
# Derive the destination dir's name from the parent directory name,
# by taking the string before "-". To also split by "_", use:
# $destDir = ($_.Parent.Name -split '[-_]')[0]
# To take just the first 3 characters, use:
# $destDir = $_.Parent.Name.Substring(0, 3)
$destDir = ($_.Parent.Name -split '-')[0]
# Handle the lone exception to the name mapping.
if ($_.Parent.Name -like 'OPRSTU_WXYZ-*') { $destDir = 'OPRWXY' }
# Make sure that the destination dir. exists.
$null = New-Item -ErrorAction Stop -Force -Type Directory $destDir
# Perform the move.
$_ | Move-Item -Destination $destDir -WhatIf
# If desired, remove the parent dir. of the source dir.
Remove-Item -LiteralPath $_.Parent.FullName -Recurse -Force -WhatIf
}
注意:上面命令中的-WhatIfcommon引數可以預覽操作。-WhatIf 一旦您確定操作會執行您想要的操作,請洗掉。
注意:上述解決方案假設兩件事:
每個源
work檔案夾唯一地映射到目標檔案夾。如果目標檔案夾恰好已經存在,則假定沒有
work子檔案夾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320783.html
下一篇:計算機基礎知識(自我的理解)
