Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, January 18, 2011 4:52 AM
Why I can't catch the following error? How can I catch it?
cls
try {
Rename-Item c:\test\notexist.txt c:\aaaa.txt
} catch{
throw "can't rename the file successfully"
}
Rename-Item : Cannot rename because item at 'c:\test\notexist.txt' does not exist.
At C:\Users\Daniel.Wu\AppData\Local\Temp\412f565d-8cab-4197-823f-1da61f9bb6e1.ps1:3 char:18
+ Rename-Item <<<< c:\test\notexist.txt c:\aaaa.txt
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
All replies (3)
Tuesday, January 18, 2011 5:33 AM ✅Answered | 2 votes
Your code looks fine, however you need to change the ErrorActionPreference for it to work. Powershell treats some errors as "Terminating" and some as "Non-Terminating." Try/Catch only handles Terminating errors, and this cmdlet causes a non-terminating error by default.
You have 2 options:
1. Before this code, set the automation variable $errorActionPreference = 'Stop'. Now all errors are treated as terminating.
2. In the call to Rename-Item, use the parameter -ErrorAction 'Stop' That will set the error behavior for that one call.
Check out Get-Help about_Preference_Variables and Get-Help about_CommonParameters for (lots of) details.
Thanks,
-Lincoln
Wednesday, January 19, 2011 3:09 AM
Very good. Thanks very much.
Wednesday, January 19, 2011 12:49 PM
maybe you are trying to do something else and that was just an example, but why don’t you do this
if(test-path $file){
rename-item $file $new}