I want to get $null
from the Get-IAMUser
command in case the user does not exist.
I investigated using -ErrorAction SilentlyContinue
but it seems to be ignored.
Line |
3 | if ($null -ne (Get-IAMUser -UserName SomeUserName))
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The user with name SomeUserName cannot be found.
Is there a way to get rid of this error message?
Unfortunately, AWS Powershell modules heavily use terminating errors instead of non-terminating errors.
If they used non-terminating errors, we'd be able to use -ErrorAction SilentlyContinue
to suppress the error message and continue with executing the script. However, passing -ErrorAction SilentlyContinue
to AWS Powershell cmdlets usually has no effect and is 'ignored'.
The error is a terminating error so use try-catch instead.
Recommended approach:
$userName = 'random-string'
try {
$iamUser = Get-IAMUser -UserName $userName
Write-Host "User '$userName' exists."
} catch {
Write-Host "User '$userName' does not exist."
}
Alternatively, if you want to really use if ($null -ne $iamUser)
:
$userName = 'random-string'
try {
$iamUser = Get-IAMUser -UserName $userName
} catch {
# will re-throw the exception if it does not relate to the "user not found" scenario
if ($_.Exception.InnerException.ErrorCode -eq "NoSuchEntity") {
$iamUser = $null
} else {
throw
}
}
if ($null -ne $iamUser) {
Write-Host "User '$userName' exists."
} else {
Write-Host "User '$userName' does not exist."
}
Output:
User 'random-string' does not exist.
Note that most PowerShell Get-*
commands don't throw terminating errors, and so there is currently an open feature request that hopefully is addressed in a future update...