2

Given:
PowerShell 5.1
Azure DevOps 2020
Windows Server 2016 Standard

Is there a way I can output message for each computer that successfully updates the LocalUser?

Invoke-Command -ComputerName Computer1,Computer2 -Credential $credential -ScriptBlock {
    $securePassword = ConvertTo-SecureString -String 'P@$$w0rd123' -AsPlainText -Force
    Set-LocalUser -Name User1 -Password $securePassword -Verbose
}
Rod
  • 14,529
  • 31
  • 118
  • 230

1 Answers1

2

Since the cmdlet produces no output you can use a Try Catch statement:

Invoke-Command -ComputerName Computer1,Computer2 -Credential $credential -ScriptBlock {
    $securePassword = ConvertTo-SecureString -String 'P@$$w0rd123' -AsPlainText -Force

    try {
        Set-LocalUser -Name User1 -Password $securePassword -Verbose -ErrorAction Stop
        $status = 'Success'
    }
    catch {
        $status = 'Fail'
        $errmsg = $_.Exception.Message
    }

    [pscustomobject]@{
        Computer = $env:COMPUTERNAME
        Status   = $status
        Error    = $errmsg
    }
} -HideComputerName | Select-Object * -ExcludeProperty RunspaceId
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • I noticed that as soon as one of the computers fail the following computers after that do not get set as well. Is there a way that if one computer fails to update to continue setting password for the rest of the computers remaining? – Rod Feb 27 '23 at 15:01
  • 1
    @Rod are you using the error preference as shown in [previous answer](https://stackoverflow.com/a/75558452/15339544) for `Invoke-Command` ? If the preference is `Stop` then as soon as you cant connect to one of the computers the command will stop, as the name implies. – Santiago Squarzon Feb 27 '23 at 15:03