如何根据先前命令的结果生成选择列表并将答案设置为变量

How to generate a selection list from the results of a previous command and set the answer to a variable

我正在尝试创建一个入职脚本来自动执行 AD 帐户创建过程。在脚本中,我想使用命令 Get-ADOrganizationalUnit -Filter 'Name -like "\*"' 获取所有 OU 的列表,然后在 PowerShell 脚本中生成一个选择列表以与每个 OU 的名称一起使用。选择名称后,我想设置一个等于该 OU distinguishedname 的变量。关于完成此操作的最佳方法有什么建议吗?

您可以使用 Out-GridView-PassThru 开关来允许,不确定 是否“最好的方法” 但这是一个简单友好的选择.

$ous = Get-ADOrganizationalUnit -Filter 'Name -like "\*"'
$choice = $ous | Select-Object Name, DistinguishedName | Out-GridView -PassThru
if($choice) { # if the user selected an item from the DGV and pressed `OK`
    $choice.DistinguishedName
}
else { # user clicked `Cancel` or closed the DGV
    exit
}