none
Powershell output as boolean RRS feed

  • Question

  • Hello Scripting guys

    Please prompt me. How i can get output as true or false, assume from Get-ADUser "j.maxi" or another cmdlet which outputs string, int, array?

    Thursday, May 8, 2014 11:38 AM

Answers

  • if(Get-ADUser 'j.maxi'){$true}else{$false}

    or even better

    try{Get-ADUser 'j.maxi';$true}catch{$false}

    Thursday, May 8, 2014 11:53 AM

All replies

  • if(Get-ADUser 'j.maxi'){$true}else{$false}

    or even better

    try{Get-ADUser 'j.maxi';$true}catch{$false}

    Thursday, May 8, 2014 11:53 AM
  • As a side bar, null or empty strings coerce to false.

    For example

    $validateU = Get-ADObject -LDAPFilter cn=$($_.UserPrincipalName)
    Instead of...

    IF ($validateU -eq $null) {User Found} ELSE {User not Found}

    or

    IF ($validateU -eq $false) {User not Found} ELSE {User Found}

    You put...
    IF ($validateU) {User Found}
    ELSE {User not Found}



    Thursday, May 8, 2014 12:17 PM
  • This is very eash in PowerShell.

    if(Get-ADUser "j.maxi" -ea 0){
        'user found'
    }else{
        'user ot found'
    }

    The result of a get is always true or false by design.  the same is tru if you want to save the result.

    If($user=ADUser "j.maxi" -ea 0){
         # process user
    }else{
        'user not found'

    No need for any fancy stuff.  This is builtin.  It is a carryover from standard programming practices.  We do this in C and C# all of the time.  The makers of PowerShell liked it so they used it.


    ¯\_(ツ)_/¯

    • Edited by jrv Thursday, May 8, 2014 2:06 PM
    Thursday, May 8, 2014 2:04 PM
  • I tend to use filters when searching for users/objects to prevent the errors that are returned with cmdlets when the object doesn't exist.  (Unless I know 100% that the users/objects exist).

    If($user=Get-ADUser -Filter "SamAccountName -eq '$_.SamAccountName'"){
        # process user
    }else{
        # user not found }


    Thursday, May 8, 2014 5:00 PM
  • I tend to use filters when searching for users/objects to prevent the errors that are returned with cmdlets when the object doesn't exist.  (Unless I know 100% that the users/objects exist).

    If($user=Get-ADUser -Filter "SamAccountName -eq '$_.SamAccountName'"){
        # process user
    }else{
        # user not found }


    Filters reduce the impact on AD and on the network.  We should nearly always use filters.  If you have the SAmName then this works.   If you have the UPN it works.  It may not work with other names and wildcards may return multiple objects. 

    Nothing is ever trivial.


    ¯\_(ツ)_/¯


    • Edited by jrv Thursday, May 8, 2014 5:12 PM
    Thursday, May 8, 2014 5:10 PM