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

问题描述 投票:0回答:1

我已经为项目创建了一个脚本,其中包含一些与我自己的代码融合在一起的代码。大部分很棒的命令,但不幸的是,两个命令不起作用。

这些命令是:

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"
powershell active-directory
1个回答
0
投票

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

$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显示脚本中正在发生的事情。您可以通过注释VerbosePreference来禁用/启用此功能。

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

  • Try/Catch,以防万一。

  • 始终使用参数名称。这样可以更清楚地说明您要执行的操作。

© www.soinside.com 2019 - 2024. All rights reserved.