下午好!希望大家都喜欢喝热饮和雪鞋。
我正在为AD创建用户创建脚本,并且遇到了一些奇怪的行为。此处的目标是检查人员的SAMID是否已经存在,如果存在,则在SAMID后面附加“ 1”。
例如,让我们使用“ 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”。
答案 0 :(得分:0)
感谢Jacob,在我的代码中发现错误:
$samidcheck = get-aduser $samid
if ($samid -ne $null) {
$samid = $samid + 1
}
应该是
$samidcheck = get-aduser $samid
if ($samidcheck -ne $null) {
$samid = $samid + 1
}
也感谢iRon作为在Powershell中检查$ null的参考: How to test for $null array in PowerShell。读者谨防:关于Powershell行为的首次通读使我头疼。
TLDR:最终用户新手编码器错误!我不好,但谢谢大家的帮助。祝你有个美好的一周!