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.
Windows for business | Windows Client for IT Pros | User experience | Remote desktop services and terminal services
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.