引用此posting,在Windows 7 Professional和Server 2008 R2上运行此命令可能有什么区别? Server 2008 R2 IS运行PS版本2.0,而我的Windows 7机器运行1.0。 这是否足以导致以下问题(这可以正常工作,直到最后一次通过目录,然后抛出下面显示的错误 - 一遍又一遍):
以下是该帖子的PS脚本:
$dir_files = "C:\path\to\my\files"
$new = "newFile.xml"
$chkFile = "C:\path\to\my\files\newFile.xml"
$fileExists = Test-Path $chkFile
while($true) {
$xmlFiles = gci $dir_files -include pre_name_*.xml -recurse
if ($xmlFiles.Length -eq 0) {
Write-Host "No files in "$dir_Files". Shutting down."
break
}
foreach ($file in $xmlFiles) {
[string]$strfile = $file
if (Test-Path $chkFile) {
Write-Host $chkFile + " file exists! Sleeping 20 seconds ..."
Start-Sleep -s 20
} else {
if (Test-Path $strfile){
Write-Host $chkFile " doesn't exist, renaming next file in array..."
rename-item -path $file -newname ("$new")
Start-Sleep -s 10
} else{
Write-Host $file " does not exist. Last file processed. Exiting..."
break
}
}
}
}
这样做的要点是遍历目录中的文件列表,一旦找到特定类型,就重命名它。重命名的文件被处理和删除,然后需要重命名下一个文件,直到没有剩下。然后,它将退出/休息。 该脚本在Windows 7计算机上运行正常。在Server 2008 R2机器上没那么多。两者都是64位。
根据请求,更充分地发送请求。取自原始发布: 原始意图在原始帖子中得到了充分的充实。对不起,我试图保持原始请求的简短但引起更多混淆: 任务:将各种.csv文件转储到其中的目录。这些可能类似于file1.csv,file2.csv等。 问题:迭代文件并将其重命名为标准化的'newfilename.csv'。然后,该文件将由外部程序处理,并重命名并移出目录。 这不会全天候运行。它将是一个计划任务并运行,直到目录中没有更多文件。没有子目录。
更新/最终代码:
$dir_files = "C:\path\to\my\files"
$new = "newFile.xml"
$chkFile = "C:\path\to\my\files\newFile.xml"
#https://stackoverflow.com/questions/20922997/powershell-in-windows-7-versus-server-2008-differences
#changed Include to Filter to improve performance
$xmlFiles = gci $dir_files -include pre_name*.xml -recurse
if (@($xmlFiles).Count -eq 0) {
Write-Host "No files in '$dir_Files'. Shutting down."
break
}
foreach ($file in $xmlFiles) {
#wait until last file is removed (processed by external app)
while (Test-Path $chkFile){
Write-Host "$chkFile file exists! Sleeping 20 seconds ..."
Start-Sleep -s 20
}
#continue with the next file
[string]$strfile = $file
if (($strFile) -and (Test-Path $strFile)){
Write-Host "$chkFile doesn't exist, renaming next file in array, sleeping 10 seconds ..."
Rename-Item -Path $file -newname ("$new")
Start-Sleep -s 10
}
}
答案 0 :(得分:1)
这是你追求的吗?我已经清理/重写了代码(未经测试),但由于我不完全理解你要做的事情,这可能是错误的。
$dir_files = "C:\path\to\my\files"
$new = "newFile.xml"
$chkFile = "C:\path\to\my\files\newFile.xml"
$fileExists = Test-Path $chkFile
#Changed Include to Filter to improve performance.
$xmlFiles = Get-ChildItem -Path $dir_files -Filter pre_name_*.xml
if (@($xmlFiles).Count -eq 0) {
Write-Host "No files in '$dir_files'. Shutting down."
break
}
foreach ($file in $xmlFiles) {
#Wait until last file is removed(processed by external app)
while (Test-Path $chkFile) {
Write-Host "$chkFile file exists! Sleeping 20 seconds ..."
Start-Sleep -s 20
}
#Continue with next file
Rename-Item -Path $file -NewName $new
Start-Sleep -s 10
}
要找出原始脚本中导致错误的原因,您应该使用PowerShell ISE运行脚本并在if (Test-Path $strfile){
设置断点,这样您每次都可以看到$strfile
的值并检测到什么发生在它上面,因为正如错误所说,$strfile
突然变为空白(Path属性为空)。