测试用户已存在Powershell输入框

时间:2018-09-07 13:03:52

标签: windows powershell scripting

我正在尝试编写一个小应用程序脚本,该应用程序可以复制AD用户的安全组并将其粘贴到另一个人的个人资料中。

我对这部分很满意,但我想通过实现一些搜索AD用户的输入框来使其更加困难,万一它没有退出我的AD时出错并再次提示直到用户已找到。

{
    macid:"mac1234",
    attri:
        {
            data:{

                ch1:12,
                ch2:123
            },
            settings:
                {
                    log_time:1min

                }


        }

}

1 个答案:

答案 0 :(得分:0)

由于您需要先验证两个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.

希望这会有所帮助