删除一组跨不同订阅的用户的Azure角色分配

时间:2018-07-04 22:28:47

标签: powershell azure

我正在尝试为csv文件中的一组用户删除分配的角色:

$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName

然后,我想检索这些用户的所有对象ID,因此我运行以下命令:

 foreach ($user in $Users)
 {
   $Users = (Get-AzureRmADUser -UserPrincipalName $User).Id
 }

不幸的是,它仅检索1个用户的ID,而不是工作表中的所有用户。 最后,当我尝试使用以下Cmdlet删除生成结果的角色分配时:

Remove-AzureRmRoleAssignment -ObjectId $Users -RoleDefinitionName "*Owner*"

我收到以下错误: Remove-AzureRmRoleAssignment:提供的信息未映射到角色分配 请告知为什么我在循环后只能得到一个用户,以及为什么会得到该错误。

更新 为了确保该脚本将从不同的订阅中删除用户,我对脚本进行了一些更改

$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName
$Subs = (Import-Csv 'C:\Users.csv').SubscriptionId

foreach ($sub in $Subs)
{
    Select-AzureRmSubscription -Subscription $sub
    foreach ($user in $Users)
     {
        $OID = (Get-AzureRmADUser -UserPrincipalName $User).Id
        Remove-AzureRmRoleAssignment -ObjectId $OID.Guid -RoleDefinitionName Owner -Scope /subscriptions/$sub -Verbose
     }
}

不幸的是,我收到以下错误: Remove-AzureRmRoleAssignment:提供的信息未映射到角色分配。

1 个答案:

答案 0 :(得分:0)

编辑:所以从您的编辑中我认为您不会了解ForEach。最后,我将尝试为您解释您的ForEach编辑。但是现在,这应该可以根据您的信息进行操作。

$Users = Import-Csv 'C:\Users.csv'

foreach ($user in $Users){
    Remove-AzureRmRoleAssignment -RoleDefinitionName Owner -SignInName $_.SignInName -Scope /subscriptions/$_.SubscriptionId -Verbose
}

现在,您编辑的代码出现了问题。

# The CSVs can be combined down to one and specific data pulled from them when needed.
$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName
$Subs = (Import-Csv 'C:\Users.csv').SubscriptionId

# This says for each object in variable $subs...
foreach ($sub in $Subs)
{
    # Select the subscription - But do nothing with it cuz herp.
    Select-AzureRmSubscription -Subscription $sub
    foreach ($user in $Users)
     {
        # Searches for the ObjectID of a User based on their SignInName (Email) and assigns to variable
        $OID = (Get-AzureRmADUser -UserPrincipalName $User).Id
        Remove-AzureRmRoleAssignment -ObjectId $OID.Guid -RoleDefinitionName Owner -Scope /subscriptions/$sub -Verbose
     }
}
相关问题