远程PSSession连接异常:Java调用PowerShell脚本时dir本地执行
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
ProcessBuilderinstead ofRuntime.execfor better control over the process. It handles arguments more safely, especially if you have spaces in paths:
Using try-with-resources ensures your readers are closed properly, andProcessBuilder 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);waitFor()lets you know if the process succeeded or failed.
内容的提问来源于stack exchange,提问作者rogeliofca

