rannn505 / child-shell

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

How to run script this script run as Administrator #131

Closed writingdeveloper closed 3 years ago

writingdeveloper commented 3 years ago

I'm developing 'Windows Local User Management App' with Node.js and Express.js.

When I search to do this, it has two methods.

First, Using 'node-powershell' package in npm. Second, Using 'child_process' built-in to Node.js.

I thought 'node-powershell' package has some examples on google. So I think it is easy, but It's seems that it's not working, and also there are no error messages either!

This is the working script in Windows PowerShell.

[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$Password = ('qwertyNewPassword' | ConvertTo-SecureString -asPlainText -Force)
New-LocalUser "myName" -Password $Password -FullName "myName" -Description "myName" -PasswordNeverExpires
echo 'Group Manage Process'
Add-LocalGroupMember -Group "GEOMECEX" -Member "myName"
echo 'end'

So I put this code into Node.js code. But it's not working. The reason why I put the [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8 code, is When I put Korean characters it brokes.

This is the code uses node-powershell package.

 /* PowerShell Process */
ps.addCommand(`[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8`)
ps.addCommand(`$Password = ('${password}' | ConvertTo-SecureString -asPlainText -Force)`)
ps.addCommand(`New-LocalUser "${name}" -Password $Password -FullName "${name}" -Description "${name}" -PasswordNeverExpires`);
ps.addCommand(`Add-LocalGroupMember -Group "${result[0].company[0]}" -Member "${name}"`)
ps.invoke()
  .then(output => {
    console.log(output);
  })
  .catch(err => {
    console.log(err);
  });

And it should be run as Administrator but I set powershell, always run as Administrator.

Jack-Barry commented 3 years ago

You can either run the Node process from an elevated shell or use Start-Process with flags to open an elevated PowerShell and run your script from it. There's a working example of how to do this here. I'm not sure if that example will work for your script in particular but I've had success triggering elevated prompts for a lot of things.

Just a head's up the main issue I've run into with this is that it gets hairy really fast translating strings from JS into strings that PowerShell understands because the syntax for escape characters in PS is bonkers.

robinmalik commented 3 years ago

@Jack-Barry Re: the heads up issue: Couldn't you between JSON to make that easier?