Many PowerShell cmdlets have a common parameter
ErrorAction, that can be set to one of
I’ve never really understood what the different between
SilentlyContinuewas until today. I’d ran the following code:
Get-Service 'NonExistantService' -ErrorAction SilentlyContinue
and then happened to look in the
$Errorautomatic variable and noticed the following:
Get-Service : Cannot find any service with service name 'NonExistantService'. At line:1 char:1 + Get-Service 'NonExistantService' -ErrorAction SilentlyContinue + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (NonExistantService:String) [Get-Service], ServiceCommandException + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Whereas the following does not get added to
Get-Service 'NonExistantService' -ErrorAction Ignore
That’s the difference!
Ignorewas added in PowerShell 3.0, and quoting the documentation page “Unlike SilentlyContinue, Ignore doesn’t add the error message to the
Ignoreis probably a better option for most cases where ignoring the error is fine.
I have some PowerShell scripts that had a dependency on using at least PowerShell 4.0. I’d added
#Require -Version 4.0to the top of the script, but was surprised the other day when this script ran on a machine with only PowerShell 2.0 and it didn’t complain. Well it did complain about other things (related to trying to run on the older version), but it didn’t throw up an error about the wrong version immediately like I’d expected.
Double-checking the documentation for About_Requires, I realised I’d made a minor (but significant) typo.
#Requires -Version 4.0
Yeah - a missing ‘s’. Without that, it’s just a commented line rather than a directive, so it was having no effect.
As it happens, this script also needs to be run as an Administrator, and whilst browsing same the documentation discovered there’s also a Requires prerequisite for that too!
Trying to run the script non-elevated results in the following error:
.\Script.ps1 : The script 'Script.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current PowerShell session is not running as Administrator. Start PowerShell by using the Run as Administrator option, and then try running the script again.
The recording from my presentation ‘Publish or perish - tricks to successfully ship your NET Core 3 app’ that was part of .NET Net Conf is now up on YouTube.
The source for the demos are in this GitHub repository