Assistance with If Statement

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

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #43723
    Profile photo of Cliff Roy
    Cliff Roy
    Participant

    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
    Profile photo of random commandline
    random commandline
    Participant

    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
    Profile photo of Cliff Roy
    Cliff Roy
    Participant

    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
    Profile photo of Cliff Roy
    Cliff Roy
    Participant

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

    #43887
    Profile photo of random commandline
    random commandline
    Participant

    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]])
        }
    } 
    
Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.