Search code examples
windowspowershellwmi

Modifying local accounts with powershell


I'm trying to set the properties of a local account on a bunch of servers to "password never expires". This is the best I could figure out. I keep getting:

Get-WmiObject : Invalid parameter 
At C:\Users\xxxxxx\AppData\Local\Temp\4f06fa1c-61da-4c65-ac0b-a4167d83d51c.ps1:4 char:14
+ Get-WmiObject <<<<  -class Win32_UserAccount -Filter "name = 'localaccount'" -       ComputerName $server | Set-WmiInstance -Argument @{PasswordExpires = 0}
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

--------- Here's what I am trying ------------

$servers = Get-Item c:\list.txt
foreach ($server in $servers)
{
    Get-WmiObject -class Win32_UserAccount -Filter "name = 'localaccount'" -ComputerName $server | Set-WmiInstance -Argument @{PasswordExpires = 0}
}

Thank you!


Solution

  • Your mistake is in this line:

    $servers = Get-Item c:\list.txt
    

    The Get-Item cmdlet returns a FileInfo object, not the content of the file. For reading the content into a variable you need the Get-Content cmdlet.

    This should work:

    Get-Content 'c:\list.txt' | % {
      gwmi Win32_UserAccount -Computer $_ -Filter "name='localaccount'" |
         Set-WmiInstance -Argument @{PasswordExpires = $false}
    }
    

    You could also do the property change like this (source):

    Get-Content 'c:\list.txt' | % {
      $account = gwmi Win32_UserAccount -Computer $_ -Filter "name='localaccount'"
      $account.PasswordExpires = $false
      $account.Put()
    }