String .Replace

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Jarek C. Jarek C. 1 year, 9 months ago.

  • Author
    Posts
  • #22532
    Profile photo of Jarek C.
    Jarek C.
    Participant

    I'm probably doing something silly but I can't see where I'm failing here. Part of my script is
    foreach($line in (Get-content .\accounts.txt)){
    $LocAdmins = $_.Replace('\','/')
    $LAdmins = [ADSI]("WinNT://$LocAdmins")
    $Group = [ADSI]("WinNT://$env:COMPUTERNAME/administrators")
    $objGroup.PSBase.Invoke("Add",$LAdmins.PSBase.Path)
    }
    In accounts.txt I have a number of accounts in form of domain\accountname. What I need is to add these accounts to local admins.

    I'm getting
    You cannot call a method on a null-valued expression.
    At line:2 char:9
    + $LocAdmins = $_.Replace('\','/')
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

  • #22534
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    You will need to replace $_ with $line. $_ is not valid in this case. Additionally you have a variable naming mismatch with $Group and $objGroup.

    foreach($line in (Get-content .\accounts.txt)){
      $LocAdmins = $line.Replace('\','/') # < << $_ replaced with $line
      $LAdmins = [ADSI]("WinNT://$LocAdmins")
      $objGroup = [ADSI]("WinNT://$env:COMPUTERNAME/administrators") # <<< $Group replaced with $objGroup
      $objGroup.PSBase.Invoke("Add",$LAdmins.PSBase.Path)
    }
    
  • #22537
    Profile photo of Jarek C.
    Jarek C.
    Participant

    Thanks for picking this up. Indeed there should be $line in that line, yet when I run it in debugging my $LocAdmins doesn't get any value even though when I hover over $line.Replace I see the account I want to add to administrators...

  • #22538
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    The quick tip while hovering over a variable sometimes does not work during debugging.

    Save the script, set a breakpoint at the first $objGroup = line, switch to the console in the ISE and enter $LAdmins.PSBase.Path to output the value.

    I hope that helps.

  • #22576
    Profile photo of Jarek C.
    Jarek C.
    Participant

    Exactly as you said. Wasn't aware debugging doesn't always work in ISE 🙂 Thanks again.

You must be logged in to reply to this topic.