2016-07-12 55 views
1

我需要擺脫AD中不存在的某些用戶,但仍將其安裝到應用程序中。PowerShell將if if語句轉換爲Foreach循環

我有一個腳本,它提供了一個用戶列表並將它們分配給一個變量。目前,我想要一個用戶名單notexist。這適用於單個用戶:

#One user in an Application 

$Users = $location.Users.FindAll() | where {$_.username -like "*johnsmith*"} | select username 

Username                                           
--------                                           

JohnSmith 


#See if user exists in AD (Match Username with AD UserPrincipalName) 

$users = $repository.Users.FindAll() |where {$_.username -like "*johnp*"} | select username 

$users2 = Get-ADUser -Filter "UserPrincipalName -eq '$($users.username)'" -Properties LastLogonDate 

if (!$users2) 
{ 
Write-Host "$users doesnt exist" 
} 

else 
{ 
Write-Host "$users does exist" 
} 


> @{Username=JohnSmith} doesnt exist 

問題我得到的是將此餵給變量中的多個用戶的foreach循環。我怎樣才能讓這個通過每個用戶的對象來查看並輸出那些不存在的呢?

#List of all users in Appication 

$Users = $location.Users.FindAll() | select username 

Username                                           
--------                                           

JohnSmith 
JohnSmith1 
JohnSmith2 

試過,但不起作用,表明即使JohnSmith對犯規如上存在的所有用戶存在:

$users = $location.Users.FindAll() |select username 

$users2 = Get-ADUser -Filter "UserPrincipalName -eq '$($users.username)'" 

foreach ($users2 in $users){ 
if (!$users2) 
{ 
write-host "$users2 doesnt exist" 
} 

else 
{ 
write-host "$users2 does exist" 
} 
} 

PS C:\> 
@{Username=JohnSmith} does exist 
@{Username=JohnSmith1} does exist 
@{Username=JohnSmith2} does exist 

回答

-1

沒有測試,但這應該退回沒有在廣告中的所有應用程序的用戶列表:

$applicationUsers = $location.Users.FindAll() | select username 
$adUsers = Get-ADUser -filter * | select -ExpandProperty UserPrincipalName 
$users = $applicationUsers | Where username -NotIn $adUsers 

,並且可以使用超過他們迭代:

$users | Foreach-Object { $_ } 
+0

完美,按需要工作,謝謝 – Ralluhb

+0

'Get-ADUser -filter *'是一個非常糟糕的做法。無法想象這需要多長時間才能在我的AD中用OVER NONG THOUSAND(嚴重)用戶類型的對象完成。您必須指定一些標準,否則檢索所有用戶對象可能需要很長時間。我只是檢查了:2分15秒和〜500MB的RAM。 – n01d

+0

@ n01d這並不是一個壞習慣。這取決於我們不知道的他的環境,所以我不能給他正確的標準來提高整體表現。 –