【发布时间】:2018-01-09 21:32:33
【问题描述】:
我编写的函数在针对远程计算机运行时返回本地组的成员时遇到问题。我们使用辅助域帐户来获得管理员权限,因此我使用了 Invoke-Command,因此我们可以使用该帐户运行脚本块,但是,当我这样做而不是使用我的管理员凭据运行新的 PowerShell 窗口时,它不能枚举非本地用户的本地组成员。
$computers = "blah"
$creds = Get-Credential
$sb = {
param($c)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype,$c
$idtype = [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName
$lg = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context,$idtype,"administrators")
$members = $lg.Members
return $members
}
foreach ($c in $computers) {
if ($c -eq $env:COMPUTERNAME) { & $sb -c $c }
else {
Invoke-Command -ComputerName $c -Credential $creds -ScriptBlock $sb -ArgumentList $c
}
}
当我在本地登录的机器上运行时,它会返回本地组的所有成员。如果我用我的第二个帐户启动一个新控制台,它也可以工作。但是,如果使用 Invoke-Command 传递凭据,我会收到与缺少网络访问有关的错误,并且它似乎是在首先在计算机上成功列出两个本地帐户后发生的。
失败时为 lg 变量返回的信息:
PSComputerName : blah
RunspaceId : hex...
IsSecurityGroup : True
GroupScope : Local
Members : {local_admin, local_user}
Context : System.DirectoryServices.AccountManagement.PrincipalContext
ContextType : Machine
Description : Administrators have complete and unrestricted access to the computer/domain
DisplayName :
SamAccountName : Administrators
UserPrincipalName :
Sid : SID...
Guid :
DistinguishedName :
StructuralObjectClass :
Name : Administrators
当它成功时,成员部分也包括域组和用户(如果远程使用 shell 作为第二个帐户运行或在本地以第二个帐户登录的服务器上的结果相同):
IsSecurityGroup : True
GroupScope : Local
Members : {local_admin, local_user, domain_group, domain_group, domain_user...}
Context : System.DirectoryServices.AccountManagement.PrincipalContext
ContextType : Machine
Description : Administrators have complete and unrestricted access to the computer/domain
DisplayName :
SamAccountName : Administrators
UserPrincipalName :
Sid : SID...
Guid :
DistinguishedName :
StructuralObjectClass :
Name : Administrators
使用略有不同的方法收到两个不同的错误:
An error occurred while enumerating through a collection: The network path was not found.
.
+ CategoryInfo : InvalidOperation: (System.Director...ctionEnumerator:PrincipalCollectionEnumerator) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
+ PSComputerName : blah
Cannot convert value "System.DirectoryServices.AccountManagement.PrincipalCollection" to type "System.Array". Error: "The network path was not found.
"
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
+ PSComputerName : blah
第一条消息来自试图返回成员变量,第二条消息是当我试图将该变量设为数组时。我认为它们本质上具有相同的根本原因。我尝试将 -EnableNetworkAccess 开关添加到 Invoke-Command,但这不会改变收到的错误。
我很感激我已经知道一种方法来完成这项工作,但我们想看看是否有任何方法可以使用管理员凭据运行 shell,并且只在需要将它们传递给远程服务器时才引入它们。这似乎不是身份验证问题,因为我们可以使用 Invoke-Command 运行更简单的命令,即 ipconfig 或 whoami。
我使用的是 PowerShell 5.1
谢谢。
【问题讨论】: