String .Replace

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
$Group = ADSI
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: (:slight_smile: [], RuntimeException
    • FullyQualifiedErrorId : InvokeMethodOnNull

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

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…

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.

Exactly as you said. Wasn’t aware debugging doesn’t always work in ISE :slight_smile: Thanks again.