首页 > 解决方案 > Powershell启动进程找不到文件

问题描述

我正在尝试通过 PowerShell 远程从客户端升级具有特定应用程序的服务器:

Invoke-Command -ComputerName $server -Credential $mycreds {Start-Process -FilePath "C:\temp\xxx.exe"   -ArgumentList "-default", "-acceptEULA" -wait }

无论我尝试什么,我都会收到诸如“找不到指定的文件...”之类的消息,我做错了什么?FilePath 位于本地(客户端)计算机上。

标签: powershell

解决方案


您的C:\temp\xxx.exe可执行文件必须存在于服务器(远程机器)上,您的命令才能工作,因为这是您的脚本块 ( { ... }) 执行的地方。

注意:相比之下,如果您使用Invoke-Commandwith-FilePath参数来远程运行本地存在的脚本文件 ( .ps1),PowerShell会自动将其复制到远程计算机;来自文档:“当您使用此参数时,PowerShell 将指定脚本文件的内容转换为脚本块,将脚本块传输到远程计算机,并在远程计算机上运行。”

要从本地(客户端)机器复制可执行文件,您需要一个 4 步方法(PSv5+,由于使用Copy-Item -ToSession[1]):

  • $server使用显式创建远程会话New-PSSession

  • Copy-Item使用及其-ToSession参数将本地(客户端)可执行文件复制到该会话(远程计算机)

  • 使用参数(而不是)运行您的Invoke-Command命令,以便在显式创建的会话中运行(这不是绝对必要的,但无需创建另一个(临时)会话)。-Session
    -ComputerName

  • 运行Remove-PSSession以关闭远程会话。

重要提示:在 PowerShell 远程会话中,您不能运行需要交互式用户输入的外部程序

  • 虽然您可以启动GUI应用程序,但它们总是无形地运行。

  • 同样,不支持交互式控制台应用程序(尽管客户接收来自控制台应用程序的输出)。

但是,支持来自 PowerShell 命令的交互式提示。

把它们放在一起:

# Specify the target server(s)
$server = 'w764' # '.'

# Establish a remoting session with the target server(s).
$session = New-PSSession -ComputerName $server

# Copy the local executable to the remote machine.
# Note: Make sure that the target directory exists on the remote machine.
Copy-Item C:\temp\xxx.exe -ToSession $session -Destination C:\temp

# Now invoke the excutable on the remote machine.
Invoke-Command -Session $session {
  # Invoke *synchronously*, with -Wait.
  # Note: If the program is a *console* application,
  #       you can just invoke it *directly* - no need for Start-Process.
  Start-Process -Wait -FilePath C:\temp\xxx.exe -ArgumentList "-default", "-acceptEULA"
}

# Close the remote session.
# Note: This will terminate any programs that still
#       run in the remote session, if any.
Remove-PSSession $session

[1] 如果您运行的是Powershell v4 或更低版本,请考虑下载psexec


推荐阅读