我正在尝试在Invoke会话中验证远程计算机的OU。代码在脚本块之外工作,但是在远程计算机上的脚本块中运行时才是坦克... o_O
这有效:
$rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
$Domain = $rootDse.DefaultNamingContext
$root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain")
$ComputerName = $env:COMPUTERNAME
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
[System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
$dn = $result.Properties["distinguishedName"]
$ouResult = $dn.Substring($ComputerName.Length + 4)
$ouResult
这不会(在标题中返回错误)
#$VMname = Read-Host -Prompt "What server do you want to validate? "
$VMname = "ObsfucatedHostNameHere"
#$Domain = Read-Host -Prompt "What domain is it in (Please specify complete domain)? "
$Domain = "ObsfucatedDomainNameHere.com"
Invoke-Command -ComputerName "$VMname.$Domain" -Credential $Cred -ScriptBlock { param($VMname)
$rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
$Domain = $rootDse.DefaultNamingContext
$root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain")
$ComputerName = $env:COMPUTERNAME
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
[System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
$dn = $result.Properties["distinguishedName"]
$ouResult = $dn.Substring($ComputerName.Length + 4)
$ouResult
}
答案 0 :(得分:0)
在有机会仔细检查之后,这是双跳问题的一个例子。使用Invoke-Command
时,您无法使用Invoke-Command
中的凭据连接到另一台服务器。但是有一些解决方法。最好的是Resourced-Base约束委派,Ashley McGlone has several articles on以及其他解决方法,但如果不起作用,您可以捆绑您想要使用的凭据并将其传递到scriptblock内。
以下是一个适用于您的代码的示例:
#$VMname = Read-Host -Prompt "What server do you want to validate? "
$VMname = "ObsfucatedHostNameHere"
#$Domain = Read-Host -Prompt "What domain is it in (Please specify complete domain)? "
$Domain = "ObsfucatedDomainNameHere.com"
$Cred = (Get-Credential)
$Username = $Cred.UserName
$Password = $Cred.GetNetworkCredential().Password
Invoke-Command -ComputerName "$VMname.$Domain" -Credential $Cred -ScriptBlock {
$rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE",$using:Username,$using:Password)
$Domain = $rootDse.DefaultNamingContext
$root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain",$using:Username,$using:Password)
$ComputerName = $env:COMPUTERNAME
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
[System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
$dn = $result.Properties["distinguishedName"]
$dn.Substring($ComputerName.Length + 4)
}
我也许还有其他一些清理变化。你没有使用VMname,因此我退出了param($VMname)
。 (请注意,如果您使用的是PowerShell 2,则需要使用参数,而不是使用$using
进行范围设定。我还会删除$ouResult
,因为您可以直接输出而无需额外的步骤来定义额外变量。