You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

远程PSSession连接异常:Java调用PowerShell脚本时dir本地执行

Troubleshooting Remote PowerShell Execution from Java

Root Cause of the Problem

The issue here is that Enter-PSSession is built for interactive use—like when you're sitting at a PowerShell prompt and want to type commands directly on a remote machine. When you run it in a script (especially a non-interactive one triggered by Java), it doesn't "stick" the subsequent commands to the remote session. So after Enter-PSSession tries to establish a connection, your dir command just runs locally because the script isn't actually operating within the remote session context anymore.

Fix: Use Invoke-Command Instead

To run commands on a remote machine from a script, you should use Invoke-Command instead. This cmdlet executes the specified commands directly in the remote session and returns the results, which is perfect for non-interactive scenarios like your Java call.

Here's the updated version of your PowerShell script:

$pass = ConvertTo-SecureString "pass" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("user", $pass)
# Execute 'dir' directly on the remote machine
Invoke-Command -ComputerName User-Pc -Credential $cred -ScriptBlock { dir }

Bonus Tips for Robustness

  • Error Handling: Add try/catch blocks to your script to catch and report issues with the remote connection or command execution. This will help you debug if something goes wrong:
    try {
        $pass = ConvertTo-SecureString "pass" -AsPlainText -Force
        $cred = New-Object System.Management.Automation.PSCredential("user", $pass)
        Invoke-Command -ComputerName User-Pc -Credential $cred -ScriptBlock { dir } -ErrorAction Stop
    } catch {
        Write-Error "Remote command failed: $_"
    }
    
  • Java Code Improvements: Consider using ProcessBuilder instead of Runtime.exec for better control over the process. It handles arguments more safely, especially if you have spaces in paths:
    ProcessBuilder processBuilder = new ProcessBuilder(
        "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
        "-File", "C:\\scr.ps1"
    );
    Process powerShellProcess = processBuilder.start();
    
    // Read standard output
    System.out.println("Standard Output:");
    try (BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()))) {
        String line;
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
    }
    
    // Read standard error
    System.out.println("Standard Error:");
    try (BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()))) {
        String line;
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
    }
    
    // Wait for process to finish and get exit code
    int exitCode = powerShellProcess.waitFor();
    System.out.println("Done with exit code: " + exitCode);
    
    Using try-with-resources ensures your readers are closed properly, and waitFor() lets you know if the process succeeded or failed.

内容的提问来源于stack exchange,提问作者rogeliofca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:21:46