[求助] 判断账户是否存在出现错误


PowerShell交流中心分类: 变量-函数-脚本-条件-循环-参数[求助] 判断账户是否存在出现错误
0
Alan Chiu asked 7 年 ago

设想通过PowerShell循环,使用查询并获取相应Object的DistinguishedName,因此我写出如下代码,但在实际使用的过程中,问题出现在 if((Get-ADUser $user.name -Server $dc) -ne $null) 这一行,如果AD User在网域内并不存在,它不会跳至否则,只会中断执行脚本,所以还请大神指教,如何写 判断AD User/AD Group的是否存在,谢谢!

$dc = 'dc01.pstips.net'
$users = Import-Csv ".\users.csv"
foreach($user in $users) {
    $UserDN = ''
        if((Get-ADUser $user.name -Server $dc) -ne $null){
            $UserDN = Get-ADUser $user.name -Server $dc -Properties samaccountname,DistinguishedName `
            | select samaccountname,DistinguishedName
             "user,$($UserDN.samaccountname),$($UserDN.DistinguishedName)" | Export-Csv ".\$(Get-Date -Format 'yyyyMMdd').csv" -Noty -Append -Encoding Unicode      
        }
        else{
             if((Get-ADGroup $user.name -Server $dc) -ne $null){
                $UserDN = Get-ADUser $user.name -Server $dc -Properties samaccountname,DistinguishedName `
                | select samaccountname,DistinguishedName
                 "group,$($UserDN.samaccountname),$($UserDN.DistinguishedName)" | Export-Csv ".\$(Get-Date -Format 'yyyyMMdd').csv" -Noty -Append -Encoding Unicode 
        }
    }
}
 <#
.\users.csv 文件内Name栏位下user object与group object混合存在
+-+-+-+-+-+-+-+-+-+-+-+
| Name |      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|user1 |      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|user2 |      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|group1|      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|group2|      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|user3 |      |       |
|+-+-+-+-+-+-+-+-+-+-+|
|group3|      |       |
|+-+-+-+-+-+-+-+-+-+-+|
#>

 

Alan Chiu replied 7 年 ago

最后使用LDAP的筛选方式解决的这个问题:
([adsisearcher]”(&(objectClass=group)(samaccountname=$($user.name)))”).FindOne()
如果$user.name在网域内存在,返回DN,如若不存在则返回空。

还是非常感谢Mooser Lee大神的支持和帮助!!

1 Answers
0
Best Answer
Mooser Lee 管理员 answered 7 年 ago
PS> Get-Item nothisfile
Get-Item : Cannot find path 'D:\nothisfile' because it does not exist.
At line:1 char:1
+ Get-Item nothisfile
+ ~~~~~~~~~~~~~~~~~~~
 + CategoryInfo : ObjectNotFound: (D:\nothisfile:String) [Get-Item], ItemNotFoundException
 + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

PS> $condition = Get-Item nothisfile -ErrorAction SilentlyContinue
PS> $condition -eq $null
Alan Chiu replied 7 年 ago

感謝大神指導!

Alan Chiu replied 7 年 ago

PS D:\> $user = Get-ADUser pstips -ErrorAction SilentlyContinue
Get-ADUser : 無法在 DC=test,DC=com 下找到身分識別為 ‘pstips’ 的物件。
位於 線路:1 字元:9
+ $user = Get-ADUser pstips -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (pstips:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
icrosoft.ActiveDirectory.Management.Commands.GetADUser

Alan Chiu replied 7 年 ago

看起來這個參數不適用於AD模組..