IIIdefconIII
IIIdefconIII

Reputation: 363

PowerShell script - distinguish between 3 command outcomes

Can anyone tell me why I'm always get the same output result?

$syslocal = Get-WmiObject -Class Win32_UserAccount -Filter "localaccount=true" |
            where {$_.Disabled -eq $False}
if ($syslocal -eq "") {
    Write-Host "Syslocal Enabled"
    exit 0
} else {
    Write-Host "No Syslocal"
    exit 0
}

It just needs to see if a account syslocal exist and if it's enabled or not with 3 outcomes:

But all outcomes are the same.

Upvotes: 2

Views: 147

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

If your Get-WmiObject | Where-Object statement finds a match the variable $syslocal will contain a list of WMI objects. If the statement doesn't find a match (i.e. no local accounts exist or all of them are disabled) the variable will be empty. Neither an empty value nor an array of objects equal the empty string, so your check will always evaluate to $false.

Also, for a 3-way check you need to actually check 3 ways.

Change your code to something like this and it should do what you expect.

$syslocal = Get-WmiObject -Class Win32_UserAccount -Filter 'localaccount=true'

if ($syslocal) {
    if ($syslocal | Where-Object {-not $_.Disabled}) {
        Write-Host 'Enabled local accounts exist.'
        exit 1010
    } else {
        Write-Host 'Local accounts exist, but are disabled.'
    }
} else {
    Write-Host 'No local accounts.'
}
exit 0

Upvotes: 5

Avshalom
Avshalom

Reputation: 8889

this line is wrong:

if ($syslocal -eq "")

If it exist it's still not equal to ""

this should be:

if ($syslocal) 

More details already explained on Ansgar Wiechers Answer...

Upvotes: 1

Drew
Drew

Reputation: 4020

Well there's this as well.

$syslocal = Get-WmiObject -Class win32_useraccount -filter "localaccount=true"
Foreach($account in $syslocal){
    If ($syslocal) {
        if($account.Disabled -eq $true) {
            Write-Host "$($account.name) is currently Disabled"
        } Else {
            Write-Host "$($account.name) is currently Enabled"
        }
    } Else {
        Write-host "Just no..."
    }
}

Upvotes: 0

Related Questions