![](/img/trans.png)
[英]Active Directory - a script to find all users that aren't in a set of groups?
[英]Powershell Script for adding Active Directory users to groups
嘿家伙在這里有點泡菜這個腳本。
Import-Module ActiveDirectory
$list = Import-csv "\\ca23fs1\IT\Scripts\Active Directory\New-Hire\Account Setup\Users-Groups.csv"
ForEach ($item in $list) {
$users = $item.Username
$groups = $item.Group
Add-ADPrincipalGroupMembership -Identity $users -MemberOf $groups -Whatif |
Set-ADUser $users -HomeDirectory "Path" -Homedrive H -WhatIf
}
運行$list
,我從 CSV 文件中獲取輸出,但是在運行$users
或$groups
沒有顯示任何內容,所以我想我的語法中缺少一些應該從“用戶名”和“組”中獲取數據的內容" CSV 中的標頭並將其傳遞給循環。
這是我的 CSV 的樣子:
這是錯誤:
任何幫助將不勝感激。
*編輯
以為可能是 CSV,所以我從 txt 文件中制作了一個,如下所示:
Username,Group
User1,group1
,group2
,group3
,group4
,group5
仍然沒有工作:(
我想這可能是因為我使用的是空白列。 將嘗試為用戶和組使用單獨的 CSV 文件。
$item 未填充。 您聲明 $users = $item.username 但此時 $item 為空。
嘗試這個:
$list = Import-csv "PATH"
ForEach ($item in $list) {
$users = $item.Username
$groups = $item.Group
Add-ADPrincipalGroupMembership -Identity $users -MemberOf $groups -Whatif |
Set-ADUser $users -HomeDirectory "Path" -Homedrive H -WhatIf
}
這基本上是說:對於列表中的每個項目,使用 .username 和 .group 語法來填充用戶和組變量。 然后,運行添加和設置命令。 請記住,這是一個對 $list 中的每個 $item 運行一次的循環。
測試代碼:
$list = Import-csv "PATH"
ForEach ($item in $list) {
$user = $item.Username
$group = $item.Group
Write-Host "$user is in $group"
}
該錯誤來自未為用戶指定有效的Identity
值,甚至可能未指定有效的MemberOf
值。
根據docs ,這兩個參數都需要使用DistinguishedName
、 ObjectGUID
、 SID
或SamAccountName
。 默認情況下,此 cmdlet 不會生成任何輸出,除非您使用-PassThru
參數。
在您的情況下,我認為您正在嘗試使用SamAccountName
並且應該可以正常工作。 但是,這里的問題似乎是您使用的 CSV 文件。
將 Excel 保存為 CSV 文件時,人們可能會期望結果將是逗號分隔值文件,正如名稱 CSV 所暗示的那樣。
不幸的是,Excel 使用當前系統區域設置來確定要使用的分隔符。 例如,在我的荷蘭機器上,它將使用分號;
作為分隔符。
如果您不檢查,則不帶-Delimiter
參數的Import-Csv
cmdlet 將假定為逗號。 因此,從 Excel 導出后,使用記事本或任何其他文本編輯器打開 csv 文件以查看創建的內容以及實際使用的分隔符。 您也可以通過在Import-Csv
cmdlet 上使用-UseCulture
開關來解決該問題,但這只有在您從 Excel 導出並在同一台機器上的 PowerShell 中導入時才有意義(或至少一台使用相同文化的機器)
您應該擁有一個有效的 CSV 文件,如下所示:
"UserName","Group"
"user1","group1"
"user2","group1"
"user3","group1"
由於您手動創建的 CSV 的UserName
列具有空值,因此您收到錯誤並不奇怪。
然后,對您的代碼進行更多更改,這應該可以工作:
Import-Module ActiveDirectory
# assuming the CSV uses commas as delimiter character. Otherwise, specify -Delimiter parameter
$list = Import-csv "\\ca23fs1\IT\Scripts\Active Directory\New-Hire\Account Setup\Users-Groups.csv"
foreach ($item in $list) {
# if you are not sure the CSV actually contains valid data to work with, check it here first:
if ([string]::IsNullOrWhiteSpace($item.UserName) -or [string]::IsNullOrWhiteSpace($item.Group)) {
Write-Warning "Empty entry found in the CSV file"
}
else {
Add-ADPrincipalGroupMembership -Identity $item.UserName -MemberOf $item.Group -Whatif
# The DriveLetter must be a single, uppercase letter and the colon is required.
Set-ADUser -Identity $item.UserName -HomeDirectory "Path" -HomeDrive 'H:' -WhatIf
}
}
希望有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.