我是Powershell的新手,我在一个需要帮助的循环中遇到问题。我试图重命名一些在循环中作为进程的一部分创建的文件。 我测试了循环的代码OUTSIDE,它工作正常。但是,当我试图把它放在循环中时,似乎没有任何事情发生。
我需要重命名的文件位于以下位置...... (1)“\ MYSERVER \ MYCOMPANY \ MYFOLDER \ MyPrintouts \ EstimateImport \ ImportPrintout.txt” (2)“\ MYSERVER \ MYCOMPANY \ MYFOLDER \ MyPrintouts \ PostEntries \ ImportPostEntries.txt”
我需要在最后确定日期和时间。这段代码适用于我的循环外部。我把它放在一个名为RenameFiles.ps1
的文件中#File location
$ImportPrintout = “\\MYSERVER\MYCOMPANY\MYFOLDER\MyPrintouts\EstimateImport\ImportPrintout.txt”
$ImportPostEntries = “\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\PostEntries\ImportPostEntries.txt”
#Find and rename the import printouts
Get-ChildItem $ImportPrintout -Filter "ImportPrintout.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
Get-ChildItem $ImportPostEntries -Filter "ImportPostEntires.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
这是我将它添加到循环中的方式,因为我希望在处理下一个文件之前重命名文件...
#Define actions after an Event is Detected
$action = {$files = Get-ChildItem -Path $watcher.Path -Filter $watcher.Filter #-Recurse
foreach ($file in $files)
{
#Define variables for log file
$changeType = $Event.SourceEventArgs.ChangeType #Your event trigger "Created"
$fileDate = $file.LastWriteTime #Date/Time Estimate was created
#logline contains = Date/Time of import, Created, Date/Time Created, filename
$logline = "$(Get-Date), $changeType, $fileDate, $file"
#Actions to take ==============================================================
#Write details to the log
Add-Content "“\\MYSERVER\MYCOMPANY\MYFOLDER\EstimateImportLog.txt" -value $logline
#Copy the estimate to the "ToBeProcessed" folder
Copy-Item $file.FullName -Destination $copyTo
#Move the estimate to the "EstimateHistory" folder
Move-Item $file.FullName -Destination $moveTo -Force
#Run the powershell script that launches the .bat file that launches the macro
Invoke-Expression "& '\\MYSERVER\MYCOMPANY\MYFOLDER\PSscriptToRunBATfile.ps1'"
#Pause the script for 30 seconds to allow the estimate to finish posting
Start-Sleep -Seconds 30
Invoke-Expression "& '“\\MYSERVER\MYCOMPANY\MYFOLDER\RenameFiles.ps1'"
}
}
这似乎“打破”我的循环。但是,我需要在进入下一个文件之前完成此操作。如何在继续之前完成重命名这些文件。任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
如果循环失败,您可能会遇到错误。将$ ErrorActionPreference设置为Continue或将其设置为Stop并将try / catch块包装在copy-item和move-item周围以检测和处理错误。 这可能还解决了copy-item / move-item更改文件名失败的问题,它在尝试执行该操作并失败时遇到错误。