我有這個腳本,我需要使用它從服務器串列中檢索特定用戶“ADTuser”的資料,該腳本運行良好,但我的用戶的輸出檔案還添加了我最終不需要的其他用戶的詳細資訊輸出我怎樣才能將它過濾到我需要的用戶。
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
uj5u.com熱心網友回復:
如果我沒記錯的話,這應該是一種更簡單的方法來做你正在尋找的事情,Get-CimInstance并且自 PowerShell 3 以來就一直存在:Get-CimAssociatedInstance
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
如果這對您不起作用,您的代碼將需要對您的第一個過濾陳述句進行簡單修改:
Where-Object { $_.SchemaClassName -eq 'user' -and $_.Name.Value -eq 'ADTuser' }
將它們放在一起并進行一些小的改進:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/466403.html
標籤:电源外壳
上一篇:Powershell:通過Register-ObjectEvent注冊的事件處理程式不會立即觸發-僅在我的對話框關閉后
