【发布时间】:2016-07-12 08:37:25
【问题描述】:
我需要删除一些不再存在于 AD 中但仍安装到应用程序中的用户。
我有一个脚本,它提供了一个用户列表并将它们分配给一个变量。目前我想要一个不存在的用户列表。这适用于单个用户:
#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
【问题讨论】:
标签: powershell if-statement foreach scripting