我有一個小腳本,可以成功復制檔案夾和子檔案夾中的所有檔案并附加創建時間,但是子檔案夾中的檔案沒有將創建時間附加到它們的名稱中。
如何將創建日期附加到檔案夾和子檔案夾中的所有檔案?
我目前的腳本是:
$path = "C:\test1"
$destination = "C:\test2"
Get-ChildItem -path $path | ForEach-Object{
$newname = $_.CreationTime.toString("yyyy-MM-dd") $_.BaseName $_.Extension
(Copy-Item -Recurse -Path $_.FullName -Destination ( Join-Path $destination $newname))
}
uj5u.com熱心網友回復:
你真的很接近,但-Recurse開關應該已經打開Get-ChildItem并且在你需要確保目標子檔案夾路徑存在的回圈內。
嘗試
$source = "C:\test1"
$destination = "C:\test2"
Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
# create the new target folderpath for the copy
$targetPath = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($source.Length)
# make sure the target path exists, if not create it
$null = New-Item -ItemType Directory -Path $targetPath -Force
# create a new filename with CreationDate prefixed
$newName = '{0:yyy-MM-dd}{1}{2}' -f $_.CreationTime, $_.BaseName, $_.Extension
# copy the file
$_ | Copy-Item -Destination (Join-Path -Path $targetPath -ChildPath $newname) -Force
}
uj5u.com熱心網友回復:
雖然您可以創建自己的遞回方法來復制檔案并隨時重命名它們,但Copy-Item遞回使用并在之后重命名檔案和檔案夾會更容易:
$Source = "src"
$Destination = "dst"
Copy-Item -Recurse $Source $Destination
foreach ($Item in (Get-ChildItem -Recurse -File $Destination)) {
Rename-Item $Item ($Item.Name "-" $Item.CreationTime.toString("yyyy-MM-dd"))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366196.html
標籤:电源外壳
