rannn505 / child-shell

Node.js bindings 🔗 for shell
http://rannn505.github.io/child-shell/
MIT License
300 stars 71 forks source link

Can't get Invoke-Command to work using node-powershell #125

Open Cliff-R-K opened 4 years ago

Cliff-R-K commented 4 years ago

I am trying to get some powershell commands to run on an remote computer when I make a POST-request to a andpoint but cant figure out how to get it to work. I can run the same commands from a powershell prompt/ISE and it works

But when I try the same using node-powershell I get an errormessage: "Principal Gäst was not found."

This works running from a remote using powershell:

$Hostname = "HOSTNAME"
$Username = "LANTM\admuser"
$Password = ConvertTo-SecureString "Password" -AsPlainText -Force
$Member = "Gäst"

$Credentials = New-Object -TypeName System.Management.Automation.PSCredential($Username, $Password)
$Session = New-PSSession –ComputerName $Hostname -Credential $Credentials

Invoke-Command -Session $Session -ScriptBlock {Add-LocalGroupMember -Group "Administratörer" -Member $Using:Member}
Remove-PSSession $session

This does not work running from a node applikation:

const shell = require("node-powershell");
const config = require("./config");

let ps = new shell({
  executionPolicy: "Bypass",
  noProfile: true,
});

let username = config.AK_USER;
let password = config.AK_PASSWORD;

const runPowerShell = async (typeOfOperation, operations) => {

  try {
   if (typeOfOperation === "LocalAdmin") {
      operations.scriptname = "addUserToLocalAdminGroup";
      const response = await addUserToLocalAdminGroup(operations);
      return response
    } else {
      return;
    }
  } catch (error) {
    console.error(error.message);
    ps.dispose();
  }
};

const addUserToLocalAdminGroup = async (operations) => {

  username = config.LOCAL_ADMIN_USER
  password = config.LOCAL_ADMIN_PASSWORD
  console.log(`LocalAdmin ${username} ${password} ${operations.hostname} ${operations.member}`)
  ps.addCommand(`../../Scripts/${operations.scriptname}.ps1`);
  ps.addArgument(operations.hostname);
  ps.addArgument(username);
  ps.addArgument(password);
  ps.addArgument(operations.member);

  const output = (await ps.invoke()).trim();
    return output;
};

module.exports = { runPowerShell };

addUserToLocalAdminGroup.ps1

$Hostname = $args[0]
$Username = $args[1]
$Password = ConvertTo-SecureString $args[2] -AsPlainText -Force
$Member = $args[3]

$Credentials = New-Object -TypeName System.Management.Automation.PSCredential($Username, $Password)
$Session = New-PSSession –ComputerName $Hostname -Credential $Credentials

#Invoke-Command -Session $Session -ScriptBlock {(Add-LocalGroupMember -Group "Administratörer" -Member $Member), (${function:ScheduleServiceRemoval} | Out-Null)}
Invoke-Command -Session $Session -ScriptBlock {(Add-LocalGroupMember -Group "Administratörer" -Member $Using:Member)}
Remove-PSSession $session
robinmalik commented 3 years ago

@burton666 Did you solve this?