Reputation: 53263
I try to catch the error message in Powershell for Net use command like this:
Invoke-Command -ScriptBlock {net use "jkjkj" /delete /y } -ErrorVariable err
which works fine, meaning I can print the $err.
I run it in the console window of PS ISE.
But when I call the same line from a .ps1 file from a command line, the $err variable is empty.
Do I do something wrong or I should handle it differently when I run it in the main block of a ps1 script??
Upvotes: 0
Views: 92
Reputation: 13483
When you run your .ps1 file, are you dot sourcing it?
If you execute your .ps1 file from the console with the execute command (&) like this:
& .\Script.ps1
It will run in its own PowerShell environment, and you won't have access to any of the variables.
If you want it to run in your current PowerShell environment, i.e. run it as if you copied and pasted the code direct from the .ps1 file, then you dot source it (.) like this:
. .\Script.ps1
After you have run the script with a dot source, then you will have access to all the variables, because it was as if you ran it inside the current PowerShell console.
For more information you can look at: Running Windows PowerShell Scripts
Upvotes: 1