【问题标题】:Passing Alternate Credential to ADSI Commands in Powershell在 Powershell 中将备用凭据传递给 ADSI 命令
【发布时间】:2020-05-06 10:12:48
【问题描述】:

我正在尝试使用 powershell 脚本为 AD OU 分配权限,该脚本应该创建一个类型为 System.Security.Principal.NTAccountSystem.DirectoryServices.ActiveDirectoryAccessRule 的新对象,我现在拥有的代码在没有备用凭据的情况下工作,但现在我需要使用具有备用凭据的相同代码。

没有备用凭据的工作代码:

$ADSI = [ADSI]"LDAP://$OUPath"

$NTAccount = New-Object System.Security.Principal.NTAccount($ClientGroupED)

$IdentityReference = $NTAccount.Translate([System.Security.Principal.SecurityIdentifier])

$ActiveDirectoryRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"

$AccessControlType = [System.Security.AccessControl.AccessControlType] "Deny"

$Inherit = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"  #All, Children, Descendents, None, SelfAndChildren

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($IdentityReference,$ActiveDirectoryRights,$AccessControlType,$Inherit)

$ADSI.psbase.ObjectSecurity.SetAccessRule($ACE)

$ADSI.psbase.commitchanges()

我尝试使用 -Credential $Cred 传递备用凭据,并且在调用 New-Object 时也传递了 -ArgumentList $Cred 都不起作用。在这个问题上需要一些帮助。

【问题讨论】:

    标签: powershell active-directory adsi


    【解决方案1】:

    您真正与 AD 交谈的唯一地点是$ADSI.psbase.commitchanges()。因此,您需要设置凭据的唯一位置是创建 $ADSI 时。

    [ADSI] 类型加速器只是创建DirectoryEntry 对象的快捷方式。 DirectoryEntry 确实有一个 constructor that accepts credentials,但是要使用它,你不能再使用类型加速器了。你需要用户New-Object,像这样:

    $ADSI = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$OUPath", "username", "password")
    

    只需将usernamepassword 替换为有权执行您正在执行的操作的凭据即可。

    如果您希望脚本调用 Get-Credential 并使用用户输入的任何凭据,那么您可以使用解决方案 here

    附注:您不需要在最后两行中使用psbase。如果你愿意,你可以,但它没有功能上的区别。你可以不用:

    $ADSI.ObjectSecurity.SetAccessRule($ACE)
    
    $ADSI.CommitChanges()
    

    【讨论】:

    • 这对我有用,完成了我的任务。非常感谢。
    • Gabriel Luci ----- 知道如何将 -credential $Cred 传递给“New-GPLink”命令吗? ------ New-GPLink -Name "Security_Policy" -Target "OUPath"
    • 这只是一个普通的 PowerShell cmdlet,所以如果它没有 -Credential 参数,那么你就不能。不过this question的评论有一些想法。
    【解决方案2】:

    您也可以直接在ADSI 对象上设置凭据。我已经对此进行了测试,以便为用户设置终端服务属性。

    $ADSI = [ADSI]("LDAP://" + $userdn)
    $ADSI.psbase.Username = $credential.username
    $ADSI.psbase.Password = $credential.GetNetworkCredential().Password 
    
    //get the value of a property
    $output["property"] = $ADSI.psbase.InvokeGet("Property")
    
    //set the value of a property
    $ADSI.psbase.InvokeSet("Property", "your value")
    $ADSI.CommitChanges()
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多