【问题标题】:Powershell Check if a User or Role is added to .Net authorization rulesPowershell 检查是否将用户或角色添加到 .Net 授权规则
【发布时间】:2021-02-21 12:37:43
【问题描述】:

我正在尝试自动化将用户或角色添加到 .NET 授权规则的过程。 我可以成功执行此命令添加用户和角色。

.\appcmd set config 'Default Web Site/TestApp' /section:system.webServer/security/authorization /+"[accessType='Allow',roles='Admin,Guest',users='User1,User2,User3']"

但是,我希望能够在运行上述命令之前检查用户或角色是否已添加到“允许”规则中。

当我运行“列表配置”命令时:

.\appcmd list config 'Default Web Site/TestApp' /section:system.webServer/security/authorization

我得到了这个结果:

PS C:\windows\system32\inetsrv> .\appcmd list config 'Default Web Site/TestApp' /section:system.webServer/security/authorization 

<system.webServer>
  <security>
    <authorization>
      <add accessType="Allow" users="User1,User2" roles="Admin,Guest" />
      <add accessType="Allow" users="User3" roles="" />
    </authorization>
  </security>
</system.webServer>

但是如果 $user 已经存在或不存在,我不知道如何返回“真”或“假”。请帮忙。

【问题讨论】:

    标签: xml vb.net powershell iis


    【解决方案1】:

    您可以使用Select-Xml 从xml 中获取添加对象。然后您可以检查您的用户、角色或用户/角色组合。我用以下函数演示了这一点

    Function Check-UserOrRoleExists {
        [cmdletbinding()]
        param(
            $User,
            $Role,
            $AppAuthConfig
            
            )
            $authorizations = Select-Xml -Content $AppAuthConfig -XPath '//authorization//add' | Select-Object -ExpandProperty node
            
            $result = if ($User -and $Role) {
                $authorizations | Where-Object { ($_.users -match $User + '(?:,|$)') -and ($_.roles -match $Role + '(?:,|$)') }
            }
            elseif ($User) {
                $authorizations | Where-Object { ($_.users -match $User + '(?:,|$)') }
            }
            elseif ($Role) {
                $authorizations | Where-Object { $_.roles -match $Role + '(?:,|$)' }
            }
            
            [bool]$result
        }
    

    使用和输出

    # Capture response from appcmd
        $response = .\appcmd list config 'Default Web Site/TestApp' /section:system.webServer/security/authorization
    
    PS > Check-UserOrRoleExists -AppAuthConfig $response -User User1
    
    True
    PS > Check-UserOrRoleExists -AppAuthConfig $response -User User4
    
    False
    PS > Check-UserOrRoleExists -AppAuthConfig $response -User User3 -Role admin
    
    False
    PS > Check-UserOrRoleExists -AppAuthConfig $response -User User1 -Role admin
    
    True
    PS > Check-UserOrRoleExists -AppAuthConfig $response -Role admin            
    
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2013-11-16
      • 2022-11-18
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多