Multiple isolated IF statements

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 3 months, 1 week ago.

  • Author
    Posts
  • #51646
    Profile photo of Llamathrust
    Llamathrust
    Participant

    I've done a ton of googling and I can't seem to find the answer I'm looking for, and IF may not even be the right command. Basically, I'm looking for an isolated IF, such as

    IF a user has a mailbox, perform this
    (Then continue down the commands)
    IF a user has a home directory, perform this
    (Then continue down the commands)
    STILL perform this
    (Then continue down the commands)
    STILL perform this

    Right now, it seems like it stops after the first IF is accomplished. I've looked into others like DO, but everything seems to be a IF/ELSE kind of setup, instead of just "If it's this, do this. Next command."

  • #51656
    Profile photo of Alex
    Alex
    Participant

    I think you are talking about nested if statements:

    
    If($this -eq $that){
    
    write some code
    if($something_else -eq $that){do something more, another if statement maybe}else{run something else}
    
    }
    else{
    
    do this
    
    }

    So the first IF statement, if it is true then it will run the code directly after it, if not then it will go to the else statement. You can nest IF statements in these, so should read like if($this -eq true){run me if I am true, you can run another if statement in here too}else{run me if I am not true}
    Its called nesting If statements, you might want to look at case statements too, as sometimes they can be better than loads if nested if statements.

    Hope that helps.

  • #51658
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    You can use If logic like you are talking about, something like:

    $user = "jsmith"
    
    if (Get-MailBox -Identity $user) {
        #Code here
    }
    
    if (Test-Path ("\\server\home\{0}" -f $user)) {
        #Code Here
    }
    
    #executes for everyone
    Get-ADUser -Filter "SamAccountName -eq '$user'"
    

    You can nest if's:

    $user = "jsmith"
    
    if (Get-MailBox -Identity $user) {
        #Code here
    
        if (Test-Path ("\\server\home\{0}" -f $user)) {
            #Only executes if the user has a mailbox AND a homedrive
        }
    }
    
    # ** OR ** #
    
    if ( (Get-MailBox -Identity $user) -or (Test-Path ("\\server\home\{0}" -f $user)) ) {
        #Code here
    }
    
    #executes for everyone
    Get-ADUser -Filter "SamAccountName -eq '$user'"
    

    Are you learning Powershell with a background in batch scripting?

You must be logged in to reply to this topic.