Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Cannot call a method on a null-valued expression.

$
0
0

Hi

Firstly, apologies if this is a basic one, i am new to Powershell so still learning.

I am trying to change a local admin password across the estate using powershell with the below script, however when running the script, the first computer in the text file list works, but the rest fail with the below error.

You cannot call a method on a null-valued expression.                                                                                                                At E:\Path\Password.ps1:34 char 4                                                                                                                                        $stream.writeline("$computer 't $Isonline 't $Status")                                                                                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                                                             + CategoryInfo:  InvalidOperation: (:) [], RuntimeException                                                                                      + FullyQualifiedErrorId:InvokeMethodOnNull

Script = 

   $Isonline    =    "OFFLINE"
   $Status        =    "SUCCESS"
   $user = "administrator"
   $PlainPassword = Get-Content -path E:\Password.txt
   $SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
    Write-Verbose "Working on $Computer"
foreach ($Computer in Get-Content -path E:\computers.txt)
{
if((Test-Connection -ComputerName $Computer -count 1 -ErrorAction 0)) {
   $Isonline = "ONLINE"
   Write-Verbose "`t$Computer is Online"
} else { Write-Verbose "`t$Computer is OFFLINE" }

try {
 $user = [adsi]"WinNT://$computer/$user,user"
 $user.SetPassword($PlainPassword)
 $user.SetInfo()
   Write-Verbose "`tPassword Change completed successfully"
}
catch {
  $status = "FAILED"
  Write-Verbose "`tFailed to Change the administrator password. Error: $_"
}

$obj = New-Object -TypeName PSObject -Property @{
  ComputerName = $Computer
  IsOnline = $Isonline
  PasswordChangeStatus = $Status
}

$obj | Select ComputerName, IsOnline, PasswordChangeStatus

if($Status -eq "FAILED" -or $Isonline -eq "OFFLINE") {
   $stream.writeline("$Computer `t $Isonline `t $Status")
}

}

     

Viewing all articles
Browse latest Browse all 21975

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>