I have a Java application which is started with non admin rights. From my Java application I want to start different PowerShell scripts. The PowerShell scrips have input and output parameter. Inside the scripts PSRemoting commands are executed in order to control other Windows PCs. I need to start the PowerShell scripts from Java as admin. In my Java application the admin user and admin password is known.
Starting the PowerShell script, passing the arguments and returning the return values, does work so far. But I have not managed to start the script as admin.
List<String> cmd = new ArrayList<>();
cmd.add("powershell.exe");
cmd.add("-ExecutionPolicy");
cmd.add("Bypass");
cmd.add("-File");
cmd.add(tempScriptPath.toString());
// Add the arguments for the PowerShell file
Iterator<Map.Entry<String, JsonNode>> fields = jsonArgs.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
String key = field.getKey();
String value = field.getValue().asText(); // Get value as text
// Add the key and value to the list
cmd.add("-" + key);
cmd.add(value);
}
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true); // Combine stdout and stderr
// Start the process
Process process = pb.start();
This is a dummy PowerShell script:
param (
[string]$ip
)
Write-Output "PS INFO: Check if ps remoting is active"
$hostname = Invoke-Command -ComputerName 127.0.0.1 -ScriptBlock { hostname }
Write-Output "PS INFO: Hostname is $hostname"
$result = @{
PsErrorCode = 0
Hostname = $hostname
}
$result | ConvertTo-Json -Depth 10
I guess I have to add the runAs option and the user and password to the cmd but until now I have not managed it.
Maybe someone does know how to start the script as admin.
Update: I forgot to mention that the pc has to users. A standard user and an admin user. The java application is started by the standard user. For executing the power shell commands I need elevated privileges which are only available by the admin user.
"powershell.exe Start-Process -verb RunAs java.exe -ArgumentList " + argList + " -Wait", so I guess it's the tagRunAsthat you need to add.