首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell将if else语句转换为Foreach循环

问PowerShell将if else语句转换为Foreach循环
EN

Stack Overflow用户
提问于 2016-07-12 16:37:25
回答 0查看 2.3K关注 0票数 1

我需要摆脱一些不再存在于AD中但仍然安装到应用程序中的用户。

我有一个脚本,它提供一个用户列表,并将他们分配给一个变量。目前,我想要一份做notexist的用户列表。这适用于单个用户:

代码语言:javascript
复制
#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循环。我如何把它放到每个用户的对象中,并输出不存在的对象呢?

代码语言:javascript
复制
#List of all users in Appication

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

Username                                                                                                                                                                        
--------                                                                                                                                                                        

JohnSmith
JohnSmith1
JohnSmith2

尝试过,但不起作用,显示所有用户存在,即使JohnSmith不存在如上:

代码语言:javascript
复制
$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
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38323801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档