如何解析多个输入?

How do I parse through multiple inputs?

早上好!所以我有一个 PowerShell 服务器构建脚本,它执行以下操作:

询问您是否要将 AD 组添加到您正在构建的服务器上的管理员,或者您是否要在不同的服务器上搜索管理员中的组和用户并使用其中之一。

  1. 如果你想添加一个AD组到Administrators,它会问你什么 AD 组并将其保存在变量中($OSAdministrators)
  2. 如果你想在服务器上搜索组和用户,你输入 服务器,它搜索并显示所有组的结果和 管理员中的用户。然后它会要求您输入哪个组 你想使用,并将其保存在同一个变量中 ($OSAdministrators).

#2 的示例代码:

$OSAdministratorsSearchHost = Read-Host "Enter the hostname of the server to search for Administrators groups"

function Get-LocalAdmin {
    $admins = Gwmi win32_groupuser –Computer $OSAdministratorsSearchHost
    $admins = $admins |? {$_.GroupComponent –like '*"Administrators"'}
    $admins |% {
        $_.partcomponent –match “.+Domain\=(.+)\,Name\=(.+)$” > $nul
        $matches[1].trim('"') + “\” + $matches[2].trim('"')
        }
    }
Get-LocalAdmin

$OSAdministrators = Read-Host "Enter the name of the AD group from the list above to add to Administrators on the new server; press Enter to skip"

如果您只想添加 1 个组,这非常有用。问题是有时您可能有几个群组想添加到服务器,但我不确定如何处理。例如,对于上面的#2,我喜欢这样:

$OSAdministrators = Read-Host "Enter the name(s) of the AD group(s) from the list above to add to Administrators on the new server. If entering multiple, separate them with a comma (e.g. "Server Group 1,Server Group 2")"

但我不确定如何拆分 "Server Group 1" 和 "Server Group 2" 并稍后在我的代码中使用它,它实际上将组添加到您正在构建的服务器上的管理员:

$DomainName = "[where the domain FQDN would be]"
$AdminGroup = [ADSI]"WinNT://$HostName/Administrators,group"
$Group = [ADSI]"WinNT://$DomainName/$OSAdministrators,group"
$AdminGroup.Add($Group.Path)

我尝试过在线搜索,但我的搜索方式并未针对此特定用例找到任何内容,或者解决方案对于我尝试做的事情来说似乎过于复杂(我正在说 30 行代码只是为了解析输入)。我认为我只是缺少一种更简单的方法。

任何方向将不胜感激。谢谢!

如果您可以添加一些关于如何输入的控件,则可以按 , 拆分输入。然后循环处理拆分的项目。

$OSAdministrators = Read-Host "Enter the name(s) of the AD group(s) from the list above to add to Administrators on the new server. If entering multiple, separate them with a comma (e.g. "Server Group 1,Server Group 2")"

$OSAdmins = ($OSAdministrators -split ",").Trim()
foreach ($OSAdministrator in $OSAdmins) {

  $DomainName = "[where the domain FQDN would be]"
  $AdminGroup = [ADSI]"WinNT://$HostName/Administrators,group"
  $Group = [ADSI]"WinNT://$DomainName/$OSAdministrator,group"
  $AdminGroup.Add($Group.Path)
}

在您当前的循环迭代中,您可以在任何需要的地方重复使用 $OSAdministrator。在循环外,您可以访问 $OSAdmins 数组中的元素。

如果那时您可以使用 GUI,这可能会满足您的需要...

function Get-LocalAdminList ($ComputerName) {
    (Get-CimInstance -ClassName Win32_GroupUser –Computer $ComputerName |
        Where-Object {
            $_.GroupComponent -match 'administrators'
            }).PartComponent.Name
    }

$ChosenItemList = Get-LocalAdminList -ComputerName $env:COMPUTERNAME |
    Out-GridView -OutputMode Multiple -Title 'Please select the desired Local Admin members & click OK'

$ChosenItemList

当我 select 一项时,我在列表中找到了一项。有两个......我得到两个字符串。 [咧嘴一笑]