Powershell命令替换标题字段中AD用户的标题不起作用?



我为一个项目创建了一个脚本,其中一些代码与我自己的代码融合在一起。大多数命令都很棒,但不幸的是,有两个命令不起作用。

这些命令是:

Set-ADUser $UserName -replace @{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"

有什么想法吗?我很感激你的帮助!

以下是完整的脚本:

$UserName = Read-Host "Please enter username to be disabled"
if ($UserName) {
''
} Else {
'User not Found'
}
Disable-ADAccount $UserName
Get-ADUser $UserName -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false }
$title = get-aduser $UserName -properties title           
$title = $title.title
$old=Get-ADuser $UserName -properties Description
$old = $old.description
$new = "DISABLED " + $old
set-aduser $UserName -description $new
set-aduser $UserName -clear "manager"
set-aduser $UserName -clear "telephonenumber"
# these two:
set-aduser $UserName -replace @{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"

我认为最好清理一些代码。看看这个:

$SamAccountName = Read-Host 'Please enter the SamAccountName of the user you want to disable'
$VerbosePreference = 'SilentlyContinue'
$VerbosePreference = 'Continue'
Try {
$ADUser = Get-ADUser -Identity $SamAccountName -Properties MemberOf, Title, Description
Write-Verbose  "User '$($ADUser.Name)' found in AD"
}
Catch {
throw "No user found in AD with SamAccountName '$SamAccountName'"
}
Write-Verbose 'Disable user'
Disable-ADAccount $ADUser
foreach ($Group in $ADUser.MemberOf) {
Write-Verbose "Remove user from group '$Group'"
Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false
}
$NewTitle = "Former Employee {0}" -f $ADUser.Title
Write-Verbose "Set 'Title' to '$NewTitle'"
Set-ADUser -Identity $ADUser -Title $NewTitle
$NewDescription = "DISABLED {0}" -f $ADUser.Description
Write-Verbose "Set 'Description' to '$NewDescription'"
Set-ADUser -Identity $ADUser -Description $NewDescription
foreach ($Property in @('Manager', 'telephonenumber')) {
Write-Verbose "Clear property '$_'"
Set-ADUser -Identity $ADUser -Clear $Property    
}
$NewTargetPath = "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Write-Verbose "Move AD User to '$NewTargetPath'"
Move-ADObject -Identity $ADUser -TargetPath $NewTargetPath

一些提示:

  • 使用Write-Verbose显示脚本中发生的内容。Yuo可以通过注释掉VerbosePreference来禁用/启用此功能。

  • 始终从检索对象开始,而不是使用文本字符串($UserName$ADUser(。将Get-ADUser视为第一个动作。

  • 使用Try/Catch以防出现故障。

  • 始终使用参数名称。它让你更清楚地知道你想做什么

最新更新