如何使用Powershell远程以提升的权限启动批处理脚本

时间:2019-01-04 11:04:30

标签: powershell

我正在编写一个脚本,该脚本需要在多台远程计算机上运行批处理。该批处理脚本需要以Domain Admin特权运行。

甚至可以使用Invoke-Command cmdlet来实现这一点吗?

我已经在远程计算机上启用了WinRM,所以我认为这不是问题。

$computername = Read-Host "Enter Hostname"

$user = "mydomain\administrator"
$pwd = Read-Host "Enter Password" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential ("$user", $pwd)

Invoke-Command -ComputerName $computername -Credential $cred -ScriptBlock {
    $remoteuser = "mydomain\administrator"
    $remotepwd = Read-Host "Enter Password" -AsSecureString
    $remotecred = New-Object System.Management.Automation.PSCredential ("$remoteuser", $remotepwd)

    $script = "\\path_to_script\script.bat"

    Start-Process $script -Credential $cred1    
}

我希望脚本在远程计算机上的域管理员凭据下运行。相反,我收到此错误:

  

CategoryInfo:未指定:(:) [Start-Process],UnauthorizedAccessException   FullyQualifiedErrorId:System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.StartProcessCommand   PSComputerName:mycomputername

1 个答案:

答案 0 :(得分:2)

您的$cred1变量不存在,应该为$remotecred

Start-Process $script -Credential $remotecred

变量名$pwd保留给'打印工作目录'。

您可以通过运行新的powershell控制台并对其进行查询来看到此信息,您将获得当前工作目录的值:

PS C:\WINDOWS\system32> $pwd

Path
----
C:\WINDOWS\system32

使用类似$pass之类的东西。

我还会调用CMD并使用/cdocumentation link)传递您的批处理文件:

Start-Process CMD -ArgumentList "/c $script" -Credential $remotecred

将所有这些付诸实践:

$computername = Read-Host "Enter Hostname"

$user = "mydomain\administrator"
$pass = Read-Host "Enter Password" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential ($user, $pass)

Invoke-Command -ComputerName $computername -Credential $cred -ScriptBlock {
    $remoteuser = "mydomain\administrator"
    $remotepwd = Read-Host "Enter Password" -AsSecureString
    $remotecred = New-Object System.Management.Automation.PSCredential ("$remoteuser", $remotepwd)

    $script = "\\path_to_script\script.bat"

    Start-Process CMD -ArgumentList "/c $script" -Credential $remotecred
}

如果您实际上与启动批处理文件使用的远程会话凭据相同,那么您就不需要第二组凭据。

当远程会话以mydomain\administrator的身份运行时,它产生的任何进程也将以该用户身份运行:

$computername = Read-Host "Enter Hostname"

$user = "mydomain\administrator"
$pass = Read-Host "Enter Password" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential ($user, $pass)

Invoke-Command -ComputerName $computername  -ScriptBlock {
    $script = "\\path_to_script\script.bat"

    Start-Process CMD -ArgumentList "/c $script"
}