簡體   English   中英

使用PowerShell腳本將不屬於另一個組的計算機添加到組中?

[英]PowerShell script to add computers to group that are not part of another group?

我正在嘗試整理一個PS腳本,以將計算機自動添加到不屬於另一個組的安全組中。

在這種情況下,將不屬於group_a的所有計算機添加到group_b。

這就是我嘗試過的

#get list of computers from group_a
$tpmobjects = Get-ADGroupMember -Identity "group_a" | Select name
#add computers to group_b that are not in group_a
Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects} | Foreach-Object { Add-ADPrincipalGroupMembership -Identity $_.SamAccountName -MemberOf "group_b" }

我得到的錯誤是...

Get-ADComputer : Type: 'System.Object[]' is not supported for extended attribute 'SamAccountName'.
At line:2 char:1
+ Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects}...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

有人有辦法嗎?

謝謝。

什么情況是, Get-ADGroupMember返回多個對象和-Filter參數不支持對多個對象進行匹配。

有多種解決方法,但是最簡單的方法是使用Where-Object簡單過濾Get-ADGroupMember的輸出:

$Computers = Get-ADGroupMember group_a |Where-Object {$_.objectClass -eq 'computer'}

您也不需要將Add-ADPrincipalGroupMembership包裝在ForEach-Object ,它接受管道輸入,並且ADComputer對象可以直接綁定到-Identity參數,而不會出現問題:

$Computers |Add-ADPrincipalGroupMembership -MemberOf group_a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM