powershelladsi

ADSI - Local disabled users list from multiple computers in a txt file


I am trying to use a text file for a list of computers to query and get a list of all active and disabled local accounts on each of them.

This part is working fine for a single computer (named glm4453):

([ADSI]('WinNT://glm4453' -f $env:COMPUTERNAME)).Children | Where { $_.SchemaClassName -eq 'user' } | ForEach {
$user = ([ADSI]$_.Path)
$lastLogin = $user.Properties.LastLogin.Value
$enabled = ($user.Properties.UserFlags.Value -band 0x2) -ne 0x2
if ($lastLogin -eq $null) {$lastLogin = 'Never'}

Write-Host
Write-Host Username: ( " " * 5 ) $user.name
Write-Host Last Login: ( " " * 3 ) $lastLogin
Write-Host Enabled: ( " " * 6 )  $enabled
}

By when I try to add a list of computers from a txt file, I get an empty output.

foreach ($name in (get-content C:\temp\computer.txt))
{

([ADSI]('WinNT://$name' -f $env:COMPUTERNAME)).Children | Where { $_.SchemaClassName -eq 'user' } | ForEach {
$user = ([ADSI]$_.Path)
$lastLogin = $user.Properties.LastLogin.Value
$enabled = ($user.Properties.UserFlags.Value -band 0x2) -ne 0x2
if ($lastLogin -eq $null) {$lastLogin = 'Never'}

Write-Host
Write-Host Username: ( " " * 5 ) $user.name
Write-Host Last Login: ( " " * 3 ) $lastLogin
Write-Host Enabled: ( " " * 6 )  $enabled
}}

Note that I am running Server 2008 which limits the PowerShell commands I can run.

Thanks in advance for any assistance provided


Solution

  • The PowerShell -f Format operator is used to replace numbered placeholders in a string. These placeholders take the form of {0}, {1} etc and can be combined with extra formatting.

    In your code 'WinNT://glm4453' -f $env:COMPUTERNAME does nothing, because there is no placeholder to replace, so the string simply remains 'WinNT://glm4453'.

    In the second code, the same thing happens, but in that case, since you are using single-quotes, the $name varable won't be expanded.

    You need to remove -f $env:COMPUTERNAME because it is of no use there and also use double-quotes, so the name gets expanded.

    Let's say the computername in $name is 'PC-01'.

    using single-quotes, 'WinNT://$name' will take the string literally.
    using double-quotes, "WinNT://$name" will result in WinNT://PC-01

    See About Quoting Rules