Powershell Script Write-Output

Bryant
Bryant used Ask the Experts™
on
Hello, I want to write-output for the script below. The script is changing local admin passwords and I want it to display the server name and that it was successful after each one is changed. Can you please help or point me in the right direction?

$pass = "password"
$user = "admin"
foreach($_ in (Get-Content C:\script.txt)){
$newpass = [ADSI]"WinNT://$_/$user,user"
$newpass.SetPassword($pass)
$newpass.SetInfo()
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
$pass = "password"
$user = "admin"
foreach ($_ in Get-Content C:\script.txt) {
  $newpass = [ADSI]"WinNT://$_/$user,user"
  $newpass.SetPassword($pass)
  $result = $newpass.SetInfo()
  New-Object PsObject -Property @{Server = $_; Success = $result -eq 0}
}

Open in new window

BryantSystem Administrator

Author

Commented:
@Qlemo,

Thanks, this is the exact output I was looking for with the exception that it tells me that the success rate is false even though it does indeed change the passwords. Any ideas?
"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
Sadly the method call does not return a HRESULT as described in the API. So the only way we can get an error is by using a catch or similar error reporting means.
$pass = "password"
$user = "admin"
foreach ($_ in Get-Content C:\script.txt) {
  $newpass = [ADSI]"WinNT://$_/$user,user"
  try {
    $newpass.SetPassword($pass)
    $newpass.SetInfo()
    $success = $true
  }
  catch {
    Write-Error $_
    $success = $false
  }
  New-Object PsObject -Property @{Server = $_; Success = $success}
}

Open in new window

BryantSystem Administrator

Author

Commented:
Perfect, thanks! I want to do other things with this script later, so I may be back. Thanks again!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial