Is this what you were after? I've cleaned up/rewritten the code(untested), but as I don't completely understand what you're trying to do it may be wrong.
$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
}
To find out what caused the error in your original script, you should run the script using PowerShell ISE and set a breakpoint at if (Test-Path $strfile){
so you can see the value of $strfile
each time and detect what happends to it, because as the error says, $strfile
suddenly becomes blank (Path property is empty).