powershell PasswordLastSet for all local accounts on remote computers

pstoddler 20 Reputation points
2023-03-04T17:29:32.66+00:00
I am a powershell toddler (baby) who is learning by example.

I have a powershell script which inspects each computer currently communicating on my network and lists all local accounts with account information.

The last piece of information needed is password last set.  Testing out code to grab this information has me stymied.

$TestComp = "remotecomputer"
$User = "localaccount"
$PasswordLastSet = (Invoke-Command -ComputerName $TestComp -ScriptBlock {
   Get-LocalUser localaccount }).PasswordLastSet
write-host $User $PasswordLastSet

outputs the following and is verified correct information
localaccount 2/13/2023 11:09:19 AM

Any fancy powershell magic or mojo to use a variable like in the code below?

$TestComp = "remotecomputer"
$User = "localaccount"
$PasswordLastSet = (Invoke-Command -ComputerName $TestComp -ScriptBlock {
   Get-LocalUser $User }).PasswordLastSet
write-host $User $PasswordLastSet

outputs
localaccount

I really do want to get the password last set for a variable list of local accounts on remote computers.
Remote Desktop
Remote Desktop
A Microsoft app that connects remotely to computers and to virtual apps and desktops.
4,226 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,355 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,037 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 44,696 Reputation points
    2023-03-04T19:47:52.3633333+00:00

    The easiest way is to refer to the variable containing the local account in the scriptblock is to prefix the variable with "$Using:".

    Like this:

    Get-LocalUser $Using:User }).PasswordLastSet
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful