Reputation: 23
I have the following simple code and it isn't working (simplified from a much larger function)
What am I missing?
Snippet 1:
$user = "no.one"
$myADUsr = Get-ADObject -Filter { sAMAccountName -like $user }
switch ($myADUsr) {
$null { 'User object variable is null' }
default { 'User object variable has a value' }
}
Snippet 2:
$myADUsr = $null
switch ($myADUsr) {
$null { 'The variable is null' }
default { 'The variable has a value' }
}
Snippet 3:
clear-host
$member = "no.one"
$adobject = Get-ADObject -Filter { sAMAccountName -like $member }
'=== Frist switch ==='
switch ($adobject) {
{$null} { "tests as null"}
{$null -eq $_ } { 'another null test' }
{[string]::IsNullOrEmpty($_)} {'string null test'}
{$_ -eq [string]::Empty} { 'another string null test'}
{$null -ne $_ } { 'not null' }
default { "I don't think this is working ..." }
}
'==== if ====='
If ($null -eq $adobject) { 'null' } else { 'not null' }
'==== second switch ==='
$nullvariable = $null
switch ($nullvariable) {
$adobject { 'null object' }
$null { "null"}
default { "not null" }
}
Upvotes: 2
Views: 1190
Reputation: 23
It think updating my original snippet #1 like this gets me out of trouble, it seems to work so I can continue to use the switch statement I have already written. I'm still testing.
$user = "no.one"
$myADUsr = Get-ADObject -Filter "sAMAccountName -like '$user'"
if ( @($myADUsr).Count -eq 0 ) { $myADUsr = $null }
switch ($myADUsr) {
$null { 'User object variable is null' }
default { 'User object variable has a value' }
}
Upvotes: 0
Reputation: 440142
The switch
statement implicitly operates on collections (enumerable data types), and evaluates its branches for each element of the enumeration.
A function or cmdlet call that yields no output technically outputs the [System.Management.Automation.Internal.AutomationNull]::Value
singleton, which can be conceived of as an array-valued $null
- that is, in enumeration contexts such as switch
it behaves like an empty collection: there's nothing to enumerate.
Therefore, because $myADUsr
in your example contains [System.Management.Automation.Internal.AutomationNull]::Value
due to Get-AdUser
not producing any output, the switch
statement is effectively skipped.
If all you need to know is whether an AD user object was returned, use PowerShell's implicit to-Boolean conversion in an if
statement, because in an expression context [System.Management.Automation.Internal.AutomationNull]::Value
behaves like $null
(and therefore evaluates to $false
):
$myADUsr = Get-ADObject -Filter 'sAMAccountName -like $user'
if ($myAdUsr) {
'User object variable has a value'
}
else {
'User object variable is null'
}
Upvotes: 3