使用 Powershell 添加基于位置的 AD 组,Powershell 将提示输入要放置的位置

Adding location based AD groups with Powershell that will prompt for input on what location to put

我目前有一个 powershell 脚本,用于将用户添加到某些 AD 组,它会提示我输入用户名,然后将这些组添加到该用户的 AD 帐户。我想要做的是在此脚本中添加另一个提示以提示输入区域特定的 AD 组。例如,我想添加组 (Region) - Admissions,但对于 Region,我希望系统提示我输入实际区域。以下是我目前拥有的脚本:

"Group - 1","Group - 2" |
Add-ADGroupMember -Members `
    (Read-Host -Prompt "Enter User Name")

理想情况下,我希望它的功能和外观完全相同,但只需在顶部添加更多组,然后提示脚本就会在其下方。关于如何做到这一点的任何想法?我不太擅长这种东西哈哈

群组的示例如下:

"Group - 1","Group - 2", "(Region) Admissions", "(Facility) Admissions" |
Add-ADGroupMember -Members `
    (Read-Host -Prompt "Enter User Name")

(Region)(Facility) 是我希望它提示我输入的地方,输入将替换这些词

可以 Read-Host 从用户那里读取值,然后使用可扩展字符串或 -f 运算符将它们添加到模板字符串:

# Ask for variable input form user
$regionName = Read-Host 'Give me a region!'
$facilityName = Read-Host 'Give me a facility!'

# Construct group names based on input
$regionGroupName = "${regionName} Admissions"
$facilityGroupName = "${facilityName} Admissions"

# Define the static group names
$staticGroups = "Group 1", "Group 2"

# Add the group memberships
@(
    $staticGroups
    $regionGroupName
    $facilityGroup
) |Add-ADGroupMember -Members (Read-Host "Input user name")

但更好的解决方案可能是参数化这些变量:

param(
  [Parameter(Mandatory)]
  [string]$RegionName,
  [Parameter(Mandatory)]
  [string]$FacilityName,
  [Parameter(Mandatory)]
  [string]$UserName
)

# Construct group names based on input
$regionGroupName = "${regionName} Admissions"
$facilityGroupName = "${facilityName} Admissions"

# Define the static group names
$staticGroups = "Group 1", "Group 2"

# Add the group memberships
@(
    $staticGroups
    $regionGroupName
    $facilityGroup
) |Add-ADGroupMember -Members $UserName

此时我们可以开始让 PowerShell 对输入值施加约束

param(
  [Parameter(Mandatory)]
  [ValidateSet("North", "East", "South", "West", "Center")]
  [string]$RegionName,

  [Parameter(Mandatory)]
  [ValidateSet("HQ", "Satelite", "Mobile")]
  [string]$FacilityName,

  [Parameter(Mandatory)]
  [string]$UserName
)

# ...

现在用户不会意外输入存在的区域或设施名称:)