vendredi 25 janvier 2019

POWERSHELL: If statement not working showing correct results in Foreach array

I created a foreach loop with a if else statement which should check whether a variable is null/empty or not. Everything seems to work fine, however the results returned all have one outcome despite some variables being empty and some other not.

I tried using different bits within the if else statement such as

If ([string]::IsNullOrWhiteSpace($password))

OR

If ($password -eq $null)

OR

If ($password.length -gt 2)

But I had no luck whatsoever.

I started working on this to find quickly which computers didn't have LAPS working to investigate why, the issue is fixed but this script is still bugging me as I can't understand what I am doing wrong.

This is my code, tried to use both the ms-mcs-admpwd attribute and the LAPS built in get-admpwd, no difference.

$computers = Get-ADComputer -Filter * -SearchBase $OU -properties * | Select-Object Name,ms-mcs-admpwd

Foreach ($computer in $computers){

    $password = Get-ADComputer $computer.name -Properties * | Select ms-mcs-admpwd

    If($password)
    {write-host "LAPS password on $computer present"}

    Else {Write-host "LAPS password on $computer not present"}

    Write-host $password
    write-host " "

}

This is the outcome:

LAPS password on @{Name=Computer1; ms-mcs-admpwd=} present
@{ms-mcs-admpwd=}

LAPS password on @{Name=Computer2; ms-mcs-admpwd=8CG1]8,q.j} present
@{ms-mcs-admpwd=8CG1]8,q.j}

LAPS password on @{Name=Computer3; ms-mcs-admpwd=P2v94d+05q} present
@{ms-mcs-admpwd=P2v94d+05q}

LAPS password on @{Name=Computer4; ms-mcs-admpwd=} present
@{ms-mcs-admpwd=}

As you can see Computer1 and Computer4 have no ms-mcs-admpwd attribute, yet the outcome is the same as Computer2 and Computer3.

Ideas? Going slightly mad :)

Aucun commentaire:

Enregistrer un commentaire