尝试使用Powershell以管理员身份在本地运行脚本块

时间:2019-12-09 21:48:50

标签: powershell active-directory admin credentials scriptblock

我正在尝试编写一个Powershell脚本,该脚本以域管理员的身份运行特定的代码块,并将计算机移至特定的OU。

如果我以域管理员身份运行,它可以正常运行,但是问题在于它通常以本地管理员身份运行;显然不会将计算机添加到域中。

因此,我将凭据添加为脚本的一部分,但似乎不起作用。

这是我的代码:

CLS

$command = {
# Specify, or prompt for, NetBIOS name of computer.
$Name = $env:COMPUTERNAME

# Retrieve Distinguished Name of current domain.
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Root = $Domain.GetDirectoryEntry()
$Base = ($Root.distinguishedName)

# Use the NameTranslate object.
$objTrans = New-Object -comObject "NameTranslate"
$objNT = $objTrans.GetType()

# Initialize NameTranslate by locating the Global Catalog.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null))

# Retrieve NetBIOS name of the current domain.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$Base"))
$NetBIOSDomain = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3)

# Retrieve Distinguished Name of specified object.
# sAMAccountName of computer is NetBIOS name with trailing "$" appended.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (3, "$NetBIOSDomain$Name$"))
$ComputerDN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 1)

#Bind to computer object in AD.
$Computer = [ADSI]"LDAP://$ComputerDN"

#Specify target OU.
$TargetOU = "OU=Block-Policies,OU=Windows 10,OU=LAPTOPS,OU=COMPUTERS,OU=COMPUTER-SYSTEMS,DC=domain,DC=com"

#Bind to target OU.
$OU = [ADSI]"LDAP://$TargetOU"

# Move computer to target OU.
$Computer.psbase.MoveTo($OU)
}

#Credentials
$domain = "domain.com"
$password = "2093dhqwoe3212" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\DomainAdmin" 
$credential = New-Object System.Management.Automation.PSCredential($username,$password)

#Run the command with escalation
Invoke-Command -Credential credential -ComputerName localhost -ScriptBlock {$command}

我知道凭据有效,因为如果手动输入凭据并运行脚本,它将起作用。我试过使用invoke-command和

start-job -ScriptBlock {$command} -Credential $credential

似乎都没有为我工作。 开始工作似乎很顺利,但实际上并没有移动计算机。 invoke-command给我一个错误。 “ [[localhost]连接到远程服务器localhost失败,并显示以下错误消息:客户端无法连接到请求中指定的目标...”

0 个答案:

没有答案