powershell - PowerShell Remoting 时设置可执行文件的工作目录

标签 powershell remoting powershell-remoting working-directory

我正在使用 PowerShell 远程处理在远程服务器上执行 exe 文件。问题是 exe 需要将其工作目录设置为 exe 所在的目录才能正常运行。如果我从命令提示符在本地(在服务器上)运行 exe,它工作正常,如果我使用 Enter-PSSession(从我的工作站)然后使用 Start-Process -FilePath [PathToExe] -WorkingDirectory [DirectoryPath] 效果很好,但是如果我使用 Invoke-Command -ComputerName [Blah] -ScriptBlock [MyScriptBlock]$session = New-PSSession -ComputerName [Blah]; Invoke-Command -Session $session -ScriptBlock [MyScriptBlock](从我的工作站)然后工作目录没有设置。

这就是 [MyScriptBlock] 的样子:

$scriptBlock = {
        param($version, $database)
        $hubSyncronizerExeDirectoryPath = "C:\inetpubLive\ScheduledJobs\$version\"
        $hubSyncronizerExePath = Join-Path $hubSyncronizerExeDirectoryPath 'Test.exe'
        Set-Location -Path $hubSyncronizerExeDirectoryPath
        Get-Location
        Write-Output "$version $database"
        Start-Process -FilePath $hubSyncronizerExePath -WorkingDirectory $hubSyncronizerExeDirectoryPath -ArgumentList '/database',$database
}

我也尝试过使用 Invoke-Command 代替 Start-Process,但效果相同;工作目录未设置。

我已经使用 SysInternals Process Explorer 验证了这一点,右键单击进程并选择属性。当我在本地启动它或使用 Enter-PSSession 时,会设置命令行和当前目录属性,但在使用 New-PSSession 或仅使用 ComputerName 调用命令时则不会。

enter image description here

我正在使用 Set-Location 和设置 -WorkingDirectory,这是设置工作目录的两种典型推荐方法,Get- Location 确实显示预期的(服务器的本地)路径(例如 C:\inetpubLive\ScheduledJobs\1.2.3.4)。我猜这只是 PowerShell 的一个错误(我在工作站和服务器上使用 V4),或者我可能遗漏了什么?


更新

事实证明,工作目录是一个红色鲱鱼(至少,我认为是)。出于某种原因,如果我从命令提示符调用我的可执行文件,一切正常。

所以在我的 Invoke-Command 中(我用 Invoke-Command 替换了 Start-Process),改变这个:

& ""$hubSyncronizerExePath"" /database $database

为此:

& cmd /c ""$hubSyncronizerExePath"" /database $database

解决了问题。

感谢大家的建议:)

最佳答案

尝试查看 New-PSDrive 看看是否有帮助

我猜你会想要类似的东西

New-PSDrive -Name WorkingDir -PSProvider FileSystem -Root "\\RemoteServer\c$\inetpubLive\ScheduledJobs\1.2.3.4"

光盘工作目录:

我假设您应该能够修改您的脚本以包含 $version 变量并将其放入 New-PSDrive 命令的路径中...

不确定这是否会完成您需要它做的事情,但这是我想到的第一件事...

或者,尝试按如下方式修改您的脚本:

$hubSyncronizerExeDirectoryPath = "\\remoteserver\C$\inetpubLive\ScheduledJobs\$version\"

关于powershell - PowerShell Remoting 时设置可执行文件的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249506/

相关文章:

powershell - Azure VM 设置中的 DefaultWinRMCertificateThumbprint 字段为空

powershell - 无需外部工具即可设置新的 Azure 虚拟机

Azure 文件共享无法使用 powershell 脚本连接?

powershell - PowerShell:读取文本,正则表达式排序,将输出写入文件和格式化

c# - 方法组中泛型调用的 RealProxy Invoke Message 中的 TargetException

powershell - 如何在Powershell上运行长时间运行的程序的远程程序

powershell - 检测管道中外部程序已退出的方法

powershell - 从 PowerShell 运行 MsiExec 并获取返回代码

c# - .NET Core 的 .NET Remoting TCPChannel 模拟

c# - 使用 MarshalByRefObject 的 [Serializable] 属性或子类化?