Assistance with If Statement

Welcome Forums General PowerShell Q&A Assistance with If Statement

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
2 years, 4 months ago.

  • Author
    Posts
  • #43723

    Participant
    Points: 0
    Rank: Member

    Greetings,
    Below is a script that will set the local administrator to the "Password" field that exists in a separate file. So the separate file may have a field that says Password="password1". However, it is not a mandatory field.

    I want to put a if statement in there that says, if the "Password" field does not exist, do not make any changes to the local admin password so the script does not error. Any thoughts would be greatly appreciated. Also should I change the $computer or leave it?

    This is not the full script, just the portion that needs changing

    $file = "c:\context.sh"
    $admin = [ADSI]"WinNT://$Computer/administrator,user"
    $admin.psbase.invoke("SetPassword", $file["PASSWORD"])

  • #43734

    Participant
    Points: 10
    Rank: Member

    This will change the password to what is captured from context.sh.

    Get-Content .\context.sh | ForEach-Object {
    If ($_ -match 'password="(.*)"'){
        $admin = [ADSI]"WinNT://$Computer/administrator,user"
        $admin.psbase.invoke("SetPassword", $file[$Matches[1]])
        }
    } 
    
  • #43868

    Participant
    Points: 0
    Rank: Member

    Thank you!
    With the script above, if there is no Password value in the context.sh file, what will happen. Ideally, I don't want the script to error our. Sorry I am still a beginner.

  • #43871

    Participant
    Points: 0
    Rank: Member

    As I am learning, could you break down your script for me to understand? If you have the time. Thanks.

  • #43887

    Participant
    Points: 10
    Rank: Member

    Does this help?

    Get-Content .\context.sh | ForEach-Object {
    
    # Check each line of context.sh file for 'password='
    If ($_ -match 'password="(.*)"'){
    # If a line has 'password=' in it, whatever is to right of '=' 
    # is captured in $Matches. Also, if 'password=' is found, 
    # it executes your code and sets password.
        $admin = [ADSI]"WinNT://$Computer/administrator,user"
        $admin.psbase.invoke("SetPassword", $file[$Matches[1]])
        }
    } 
    

The topic ‘Assistance with If Statement’ is closed to new replies.