Windows

如何在 powershell 中為每個 Active Directory OU 使用者更正我的 foreach 循環?

  • October 13, 2015

目標:創建一個 for 或 foreach 循環來為 OU 中的每個使用者執行一些程式碼(在本例中,只列印 x)。我使用帶有 ActiveDirectory 模組的 powershell 2.0。

到目前為止:這就是我所擁有的(見下文)。它只是為每個使用者列印出 X。但它並沒有按照我想要的方式工作,而是我認為它可能對每一行都在做。所以我得到 6 個 X 代表“名稱”、“—-”、“test1”、“test2”、SPACE、SPACE。

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=jack,DC=Corp,DC=jill,DC=com" -Properties name | FT name
foreach ($user in $pool )
{ write-host "x"}
$pool

結果,SPACE 將由句點 (.) 表示:

x
x
x
x
x
x


name                        
----                      
test1                  
test2
.
.

我不確定它為什麼這樣做。如果您有更好的方法或方式來處理這個問題,我會很高興聽到它。

$pool將包含 的輸出Format-Table name,即第一行的最後一步。Format-*cmdlet 用於在螢幕上顯示值。您幾乎肯定不想將格式化的表格提供給您的foreach循環。

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=jack,DC=Corp,DC=jill,DC=com"
foreach ($user in $pool) {
 Write-Host "x"
}

# And if you really want to see an `ft $pool`:
$pool | Format-Table name

引用自:https://serverfault.com/questions/725609