我正在尝试编写一个小应用程序脚本,以便复制AD用户的安全组并将其粘贴到另一个人的配置文件中。
我很擅长这个部分,但是我想通过实现一些搜索AD用户的输入框来使它变得更加困难,如果它没有在我的AD中退出则会出错,并再次提示直到找到用户。
ipmo activedirectory
Add-type -assemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
$userref = [Microsoft.VisualBasic.Interaction]::Inputbox("Enter username
", "Prime User")
$usertar = [Microsoft.VisualBasic.Interaction]::Inputbox("Enter username",
"Target")
$userref, $usertar | foreach {
if ([bool](Get-ADUser -Filter {samaccountname -eq $_}) -ne $true) {
[System.Windows.Forms.MessageBox]::Show("This user does not exist!")
}
else {Write-Host "User Ok"}
}
由于您需要在其余代码运行之前验证两个AD用户的存在,因此您基本上使用输入框两次询问相同的内容。在这种情况下,我建议添加一个小的自定义函数来做到这一点。
也许这样的东西:
Import-Module ActiveDirectory
Add-type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
function Get-UserFromInputbox ([string]$Title) {
do {
$account = [Microsoft.VisualBasic.Interaction]::Inputbox("Enter user accountname", $Title)
# On Cancel the InputBox function simply returns an empty string.
# in that case, just return $null so the calling code can handle it
if ([string]::IsNullOrEmpty($account)) { return $null }
# Check if the user can be found
$user = Get-ADUser -Filter "SamAccountName -eq '$account'" –Properties MemberOf -ErrorAction SilentlyContinue
if (!$user) {
# If not found, show the same InputBox again until a valid
# accountname was given or the dialog is cancelled.
[System.Windows.Forms.MessageBox]::Show("User '$account' does not exist!")
}
}
while (!$user)
return $user
}
# Get the AD User object for the source user
$userref = Get-UserFromInputbox -Title "Source User"
if (!$userref) { exit }
# Ditto for the target user
$usertar = Get-UserFromInputbox -Title "Target User"
if (!$usertar) { exit }
# From here on you should have two valid AD user objects with the default properties `DistinguishedName, Enabled,
# GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName`.
# In the function we extended that to also have the `MemberOf` property.
希望这可以帮助