我对 Powershell 非常陌生,我正在尝试创建一个脚本,通过该脚本将文件夹从一台计算机复制到同一网络上的另一台计算机,然后当普通用户在远程计算机上以管理员身份运行批处理文件时已登录。
这就是我所拥有的,问题是,我无法让 Powershell 以管理员权限运行批处理文件。
我想运行批处理文件的原因是批处理文件中的exe需要参数才能运行,而Powershell无法识别它们。
$Session = New-PSSession -ComputerName "computer Name" -Credential "Admin creds"
Copy-Item -Path "\Local computer folder\*" -Destination "\\computer Name\C$\Temp" -Recurse -Force
Invoke-Command -ComputerName "computer Name" -Credential "Admin creds" -ScriptBlock { Start-Process c:\temp\Install.bat -wait }
Remove-Item –path \\computer Name\C$\Temp –recurse
Remove-PSSession $session
我尝试了几种不同的命令,但没有成功。
tl;dr,根据您自己的反馈:
将
{ Start-Process c:\temp\Install.bat -wait }
替换为 -ScriptBlock
参数:
{ c:\temp\Install.bat -wait }
解决您的问题;它确保:
同步(阻塞)执行
&
,但在直接调用 (& c:\temp\Install.bat -wait
) 中,调用运算符是唯一需要的,如果可执行路径被 引用(通常是由于包含空格)和/或以变量表示。
-wait
作为参数传递给
c:\temp\Install.bat
。
您期望
Start-Process c:\temp\Install.bat -wait
-wait
是一个pass-through 参数,即传递给
c:\temp\Install.bat
但是,-wait
被
Start-Process
解释为its-Wait
开关,因此它同步运行批处理文件,但不传递任何参数。
立即修复将是:
引用您的传递参数,这是必须的如果它看起来像参数名称。
Also pass Start-Process
-Wait
switch,这是使用
Invoke-Command
进行远程调用时必须的,由于使用 -ComputerName
参数,创建了 ad hoc远程会话:
Invoke-Command
返回时,会话将关闭,如果此时远程异步
Start-Process
启动的进程尚未完成,它将被killed。
Invoke-Command -ComputerName "computer Name" -Credential "Admin creds" -ScriptBlock {
# Note the use of -Wait for Start-Process and '-wait' as the pass-through argument.
Start-Process -Wait c:\temp\Install.bat '-wait'
}
但是,除了特殊情况没有有很好的理由使用Start-Process
来
同步调用控制台应用程序(例如批处理文件),所以顶部的直接调用解决方案是优选:
之外,还允许您直接捕获它们的输出,并稍后通过自动$LASTEXITCODE
变量
查询其退出代码。
提供了有关何时使用 Start-Process
合适或不合适的指导。
elevation(管理权限)运行的担忧: