I have this script that I need to use to retrieve the data of a particular user "ADTuser" from a list of servers the script works well, but the output file with my user add also other users' detail that is not needed for my final output how can I filter it to only the user that I need.
get-content C:\servers.txt | foreach-object {
$Comp = $_
if (test-connection -computername $Comp -count 1 -quiet) {
([ADSI]"WinNT://$comp").Children | ?{$_.SchemaClassName -eq 'user' } | %{
$groups = $_.Groups() | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$_ | Select @{n='Computername';e={$comp}},
@{n='UserName';e={$_.Name}},
@{n='Memberof';e={$groups -join ';'}},
@{n='status'; e={if($groups -like "*Administrators*"){$true} else{$false}}}
}
} Else {Write-Warning "Server '$Comp' is Unreachable hence Could not fetch data"}
} | Out-File -FilePath C:\users.txt
CodePudding user response:
This should be an easier way of doing what you're looking for, Get-CimInstance
and Get-CimAssociatedInstance
have been around since PowerShell 3 if I'm not mistaken:
Get-Content C:\servers.txt | ForEach-Object {
$computer = $_
try {
$query = Get-CimInstance Win32_UserAccount -ComputerName $_ -Filter "Name='ADTuser'" -ErrorAction Stop
if(-not $query) { return }
$membership = Get-CimAssociatedInstance $_ -ResultClassName Win32_Group -ComputerName $_
[pscustomobject]@{
Computername = $_
UserName = $_.Name
Memberof = $membership.Name -join ';'
Status = $membership.Name -contains 'Administrators'
}
catch {
Write-Warning "Server '$computer' is Unreachable hence Could not fetch data"
}
} | Out-File C:\users.txt
If that doesn't work for you, your code would require a simple modification on your first filtering statement:
Where-Object { $_.SchemaClassName -eq 'user' -and $_.Name.Value -eq 'ADTuser' }
Putting it all together with minor improvements:
Get-Content C:\servers.txt | ForEach-Object {
if (-not (Test-Connection -ComputerName $_ -Count 1 -Quiet)) {
Write-Warning "Server '$_' is Unreachable hence Could not fetch data"
return
}
$computer = $_
([adsi]"WinNT://$_").Children.Where{
$_.SchemaClassName -eq 'user' -and $_.Name.Value -eq 'ADTuser'
}.ForEach{
$groups = $_.Groups().ForEach{ $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }
[pscustomobject]@{
Computername = $computer
UserName = $_.Name.Value
Memberof = $groups -join ';'
Status = $groups -contains 'Administrators'
}
}
} | Out-File -FilePath C:\users.txt