user3178250
user3178250

Reputation: 33

Test result of command match with false or true

I'm looking for a function that returns $true or $false according to the result of command.

Little bit like this:

Function Get-ChPwd ([string] $sam) {
    $x = Get-ADUser -Identity $sam -Properties CannotChangePassword |
         Select-Object -ExpandProperty CannotChangePassword

    if( $x -match "False") {
        return $false
    } else {
        return $true
    }
}

Upvotes: 2

Views: 114

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

The property already has a boolean value, so you can simply return that value. I would recommend a different function name, though, so it adheres to the naming conventions.

Function Test-CannotChangePassword([string]$sam) {
    Get-ADUser -Identity $sam -Properties CannotChangePassword |
        Select-Object -ExpandProperty CannotChangePassword
}

Note that this will raise an error if no user with that identity exists. If you want to return $false instead of throwing an error in that case use -Filter instead of -Identity and cast the result to bool:

Function Test-CannotChangePassword([string]$sam) {
    [bool](Get-ADUser -Filter "SamAccountName -eq '$sam'" -Properties CannotChangePassword |
        Select-Object -ExpandProperty CannotChangePassword)
}

Upvotes: 2

Related Questions