【发布时间】:2019-03-02 17:39:09
【问题描述】:
下午好!希望每个人都能在热饮和雪鞋中安顿下来。
我正在为 AD 编写用户创建脚本,并遇到了一些奇怪的行为。此处的目标是检查此人的 SAMID 是否已存在,如果存在,则将“1”附加到 SAMID。
例如,让我们使用“Jaina Proudmoore”作为我们的用户。
import-csv $inputCSV | foreach {
$FullName = $_.FullName
$company = $_.Company
$Givenname = $fullname.Split(" ")[0]
$Surname = $fullname.split(" ")[1]
$firstInitial = ($fullname.substring(0,1)).ToLower()
$surnameLower = $surname.ToLower()
$GivennameLower = $Givenname.ToLower()
$samid = $firstInitial + $surnameLower
$samidcheck = get-aduser $samid
if ($samid -ne $null) {
$samid = $samid + 1
}
$Description = "Created By NewUserCreation Script $DateFormat"
$global:Department = $_.Department
$Title = $_.Title
$Office = $_.Office
$StreetAddress = $_.StreetAddress
$PostalCode = $_.PostalCode
$ManagerFullName = $_.Manager
$ManagerDN = (get-aduser -filter 'Name -like $ManagerFullName').DistinguishedName
$Country = "CA"
$co = "Canada"
$OfficePhone = $_.OfficePhone
$MobilePhone = $_.MobilePhone
$countryCode = "124"
$City = $_.Location
$GroupSourceUser = $_.GroupSourceUser
$GroupSourceUserDN = (get-aduser -filter "Name -like '$GroupSourceUser'").DistinguishedName
$ADUserCheck = get-aduser -Filter 'Name -like $FullName' -ErrorAction SilentlyContinue
在这种情况下,SAMID 检查应该给我:
$samidcheck = get-aduser jproudmoore
如果我要手动执行:
get-aduser : Cannot find an object with identity: 'jproudmoore' under: 'DC=home,DC=local'.
At line:1 char:1
+ get-aduser jproudmoore
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (jproudmoore:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
如果我理解正确,则表示“未找到用户”。因此,我的 SAMID 应该创建为“jproudmoore”。但是,该脚本会创建“jproudmoore1”,就好像它检测到输出为 NOT null。
if ($samid -ne $null) {
由于存在未找到对象错误,我会假设输出确实不等于null,因此:
$samid = $samid + 1
}
我在这里缺少什么?我觉得这很明显。
提前感谢您的宝贵时间,祝您度过愉快的一周!
- 编辑-
我也手动尝试过:
$test = get-aduser jproudmoore
if (!$test) {write-host "variable is null"}
PS > variable is null
如果我在这里是正确的,那么这意味着 SAMID 检查不应该附加“1”。
【问题讨论】:
-
我认为你应该像这样检查
$samidcheck:if ($samidcheck -ne $null)。如果Jsmith和Jsmith1已经存在,还会发生什么? -
人工检查的结果不是$null。 Try
$x = 3; $x = Get-AdUser 'nonexistentuser'; $x -eq $null; $x可能需要 try/catch 异常处理。 -
感谢 Jacob 提供 samidcheck -ne $null 位。完全错过了!将在上午重新测试。点亮:明天也将尝试您的代码;感谢您的评论。
-
在 PowerShell 中检查
$Null的一般规则是遵循 PSScriptAnalizer 规则,并且$Null始终位于左侧:if ($Null -ne $samidcheck) {...}。原因之一是针对空数组的条件检查,如:If (@() -eq $Null)' andIf (@() -ne $Null)'(使用-eq或-ne)都被认为是错误的。见:github.com/PowerShell/PSScriptAnalyzer/issues/1021
标签: powershell automation active-directory