关于 Powershell ForEach MFA 脚本的几个问题

Few questions regarding Powershell ForEach MFA script

我正在编写脚本以通过 Powershell 实施 MFA 部署。我正在连接到 office365 和 运行 Get-MsolUser 命令以从 AD 获取用户列表(我相信)。我将它放入一个数组中,然后通过 ForEach 循环 运行。我不确定这是否有效,但我正在尝试弄清楚如何从这个循环中排除某些用户,因为我不想为域管理员激活 MFA。

Connect-MsolService
$array = @(Get-MsolUser | Select UserPrincipalName)
ForEach ($users in $array)
{ 
$st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$st.RelyingParty = "*"
$st.State = "Enabled"
$sta = @($st)
Set-MsolUser -UserPrincipalName $users -StrongAuthenticationRequirements $sta
}

所以我想我有 3 个问题是:

  1. 如何排除名称与数组中的某个字符串匹配的用户,例如“Admin,Administrator”?

  2. 是否可以获取用户输入并将其应用于 Connect-MsolService 的 username/password 字段?

3)这段代码是否仍然有效,还是我完全偏离了目标?

如评论所述,您的代码中有一些改进。

尝试:

从你的问题 2)
开始 Connect-MsolService 有一个 -Credential 参数,获取该参数的最简单方法是使用 Get-Credential cmdlet:

# ask for credentials to make the connection
$cred = Get-Credential -Message 'Please enter your credentials to connect to Azure Active Directory'
Connect-MsolService -Credential $cred

接下来,您要定义一个用户列表以排除受影响的用户。

$excludeTheseUsers = 'admin', 'user1', 'user2'  # etc.
# for using the regex `-notmatch` operator later, you need to combine the entries with the regex OR sign ('|'),
# but you need to make sure to escape special characters some names may contain
$excludes = ($excludeTheseUsers | ForEach-Object { [regex]::Escape($_) }) -join '|'

# create the StrongAuthenticationRequirement object just once, to use on all users
$st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$st.RelyingParty = "*"
$st.State = "Enabled"
$sta = @($st)

# get an array of UserPrincipalNames
$array = (Get-MsolUser | Where-Object { $_.DisplayName -notmatch $excludes }).UserPrincipalName
foreach ($user in $array) {
    Set-MsolUser -UserPrincipalName $user -StrongAuthenticationRequirements $sta
}