我是PS和AD的新手,我正在编写一个脚本,该脚本通过csv循环并更新我们的AD。我遇到几个问题,如果填充了该字段,则PS AD命令运行正常,如果变量为null或为空,则PS命令将失败。我发现很难相信AD无法处理空值,因此我不知道自己做错了什么。
我尝试为每个命令执行单个命令,以识别是否为导致问题的null,并且可以看到正在发生的情况。
$datetime= get-date -UFormat "%Y-%m-%d_%H-%M-%S"
Import-Csv D:\adupdate.csv | ForEach-Object {
$hdate = $_."hiredate" -as [datetime]
Set-ADUser $_.UserID -DisplayName $_.DisplayName -Initials $_.Middle -Manager $_.Manager -Surname $_.LastName -givenname $_.FirstName -Office $_.Office -Department $_.Department -officeNumber $_.TeleNumber -MobilePhone $_.Mobile -Title $_.JobTitle -Company $_.Company -replace @{employeeType=$_.EmployeeType;employeeID=$_.Badge;employeeNumber=$_.EmployeeNumber;extensionAttribute3=$_.Subdepartment;ipPhone=$_.ipPhone}
Set-ADUser $_.UserID -replace @{hireDate=$hdate}
}
错误:
+ CategoryInfo : InvalidOperation: (XXX:ADUser) [Set-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
所以我改成这个,但是检查csv中的每个变量以检查是否为null或为空似乎无效:
if(-not ([string]::IsNullOrEmpty($_.employeetype))){Set-ADUser $_.userid -Replace @{'employeeType'=$_.employeetype}}
else {Set-ADUser $_.userid - -Replace @{'employeeType'=' '}}
if(-not ([string]::IsNullOrEmpty($_.badgenumber))) {Set-ADUser $_.userid -Replace @{'employeeID'=$_.badgenumber}}
else {Set-ADUser $_.userid -Replace @{'employeeID'= ' '}}
if(-not ([string]::IsNullOrEmpty($_.eecode))) {Set-ADUser $_.userid -Replace @{'employeeNumber'=$_.eecode}}
else {Set-ADUser $_.userid -Replace @{'employeeNumber'= ' '}}
if(-not ([string]::IsNullOrEmpty($_.subdepartment))) {Set-ADUser $_.userid -Replace @{'extensionAttribute3'=$_.subdepartment}}
else{Set-ADUser $_.userid -Replace @{'extensionAttribute3'=' '}}
if(-not ([string]::IsNullOrEmpty($_.ipphone))) {Set-ADUser $_.userid -Replace @{'ipPhone'=$_.ipphone}}
else{Set-ADUser $_.userid -Replace @{'ipPhone'=' '}}
答案 0 :(得分:2)
如果您不想在更新数据之前进行错误/健全性检查,则可以将-Replace
数据存储到哈希表中。然后删除空/空键/值对。清除之后,您可以将哈希表变量传递给-Replace
参数。
$hash = @{employeeType=$_.EmployeeType;employeeID=$_.Badge;employeeNumber=$_.EmployeeNumber;extensionAttribute3=$_.Subdepartment;ipPhone=$_.ipPhone}
$keysToRemove = $hash.keys | Where-Object {
!$hash[$_]
}
$keysToRemove | Foreach-Object {
$hash.remove($_)
}
Set-ADUser $_.UserID -DisplayName $_.DisplayName -Initials $_.Middle -Manager $_.Manager -Surname $_.LastName -givenname $_.FirstName -Office $_.Office -Department $_.Department -officeNumber $_.TeleNumber -MobilePhone $_.Mobile -Title $_.JobTitle -Company $_.Company -Replace $hash
有时候,如果数据变为空值,您实际上可能希望将其清空。过去,我使用Set-ADUser -Clear PropertyName
清除了这些值。在这种情况下,您可以使用Set-ADUser -Clear $keysToRemove
。