When I try to connect and run a PowerShell script manually from CMD I can do it, but when I try to do the same in my Java code an error is displayed, my code for the connection is this:
String command = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell C:\\scr.ps1";
Process powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();
String line;
System.out.println("Standard Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
powerShellProcess.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
//En caso de error se obtiene
System.out.println("Standard Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
powerShellProcess.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
Before I tried to put all the commands in a the command string, but that didn't work, so I decided to put it in a script. The script contains this:
$pass = ConvertTo-SecureString "pass" -AsPlainText -Force
$cred = New-Object System.management.Automation.PSCredential("user", $pass)
Enter-PSSession -ComputerName User-Pc -Credential $cred ;
dir
but the last command dir
is done in mi local desktop not in the remote one, I debug and I don't find any error the script works, the connection was done but I don't understand why the dir
command doesn't execute in the remote desktop, somebody have any idea of what is happening?
Enter-PSSession
is for interactive use. For non-interactive command execution use Invoke-Command
:
Invoke-Command -Computer 'User-Pc' -Scriptblock {
Get-ChildItem
} -Credential $cred
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments