Git Product home page Git Product logo

child-shell's People

Contributors

bitdeli-chef avatar davidkassa avatar litomore avatar mistergf avatar rannn505 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

child-shell's Issues

when to dispose

I think its worth adding something to the API documentation about the advantages of putting ps.dispose() in your .then() block when you are using more than 1 powershell script or command.

The only way to invoke a second command or script is to create a new instance so I don't see any use case for keeping the first powershell console open after we've used it once.

Unable to send [switch] options.

I was trying to send a switch options to node-powershell

var shell = require('node-powershell');

var ps = new shell

ps.addCommand('write-host "powerShell"', [{name: 'nonewline'}]).then( ps.invoke())

result from console.log is write-host "powerShell" -nonewline "undefined" rather than write-host "powerShell" -nonewline

node-powershell was unable to start powershell

I'm adding a feature to Atom Beautify to support formatting PowerShell files/text using PowerShell Beautifier. I came across this package to be able to run the PowerShell module needed for this to happen, however I'm running into this error: Opss... node-powershell was unable to start PowerShell. Please make sure that PowerShell is installed properly on your system, and try again., and a separate message: 'powershell' could not be spawned. Is it installed and on your path? If so please open an issue on the package spawning the process. I'm on a Mac and have installed PowerShell via Homebrew. Atom-Beautify is currently written in CoffeeScript, so the syntax is a little different but here is my code. The relevant part is in the beautify function where it errors out on ps = new shell(). It's all WIP (and just started)

"use strict"
Beautifier = require('./beautifier')
shell = require('node-powershell')

module.exports = class PowerShellBeautifier extends Beautifier
  name: "powershell-beautifier"
  link: "https://github.com/DTW-DanWard/PowerShell-Beautifier"

  options: {
    PowerShell: false
  }

  beautify: (text, language, options) ->
    ps = new shell()
    tempFile = @tempFile("input", text)
    ps.addCommand("Set-PSRepository -Name PSGallery -InstallationPolicy Trusted")
    ps.addCommand("Install-Module -Name PowerShell-Beautifier")
    ps.addCommand("Edit-DTWBeautifyScript " + tempFile)
    ps.invoke().then(=> @readFile(tempFile)).catch(err => {})

Issue with ps dispose

Hi,

I am trying to use the library to invoke ps and then return to callback function. If I include ps.dispose in my code, the callback is never called. Below find my code snippet below

image

Can you please tell me when I should call ps.dispose in this case. Should it be before callback function or after that

Thanks
Gopi

Installing SharePoint Online Management Shell

I am currently building a MS Bot which can run 'normal' PS scripts. I really want to have the bot run SharePoint Online scripts but this needs the specific management shell to be installed.

Can your module do this? Is it possible?

Cheers!

npm install for 2.0.0 doesn't pull down ./dist

Running npm install node-powershell I get the following:

$ ls -1
LICENSE
README.md
example
node_modules
package.json

If I manually create dist and drop in the files from the git repo, everything works as expected.

Can I supress errors or warnings?

Hi,
I run a powershell script that has to import a pssession first (to get access to the Add-MailboxPermission Command).
It does import it but it also returns a little warning:

Warning: The names of a few imported commands on modul "tmp_4wm2ycxh.e5r" contains not approved verbs....

So I don't care about the warning but then the script cancels out into the "error" function and doesn't get to the actual Add-MailboxPermission command.

How can I solve this problem?
Great Project btw.!

Keep existing powershell session after a command?

Hi, I wasn't sure if this was possible but I was wondering if we could keep the same powershell session open?

For example:

Command #1:
$a = Get-Command

Command #2:
$a[0] >> test.txt

Let's say I wanted to execute Command #1 then execute Command #2 at a later time programatically. Is this possible?

How do I reference my powershell scripts in my electron application after building and packaging?

I have made a Electron Application, mainly for my helpdesk colleagues at work.

What it does (Context):

It provides a simple gui with different "Tasks" it can do. Example:

enter image description here

For this I'm using a combination of:

  • Node with Electron
  • React
  • Node-Powershell

The Problem:

The app when I run it in Development Mode is running as it should. But after I build and package it with electron, the NPM package node-powershell can't find the .ps1 scripts anymore.
I think I already identified the problem, but I don't know what the solution to this problem is.
node-powershell needs a path to a script and an array of commands.
I have set it up like this:

    const p1 = require('path').resolve();
    const scriptPath = require('path').join(p1, 'src/PowershellScripts/AddMailboxPermissions.ps1');

And then ps.addCommand(scriptPath, commands); (node-powershell)

As said before this works fine in development mode with a webpack server, but when run after packaging I get this error:

C:\Users\Huberdo\Projekte\Powershell-SAS-App\Client\builds\basic-electron-react-boilerplate-win32-x64\src\PowershellScripts\GetRemoteMac.ps1 cannot be found.

The reason is because the packaging has following structure. The .ps1 files now have following path:

C:\Users\Huberdo\Projekte\Powershell-SAS-App\Client\builds\basic-electron-react-boilerplate-win32-x64\resources\app\src\PowershellScripts

So this is the main issue. How do I package this "the right way" so that it's actually working afterwards.

Infos:

  • I run this on a windows 10 x64 machine
  • package.json scripts:
    • "dev": "webpack-dev-server --hot --host 0.0.0.0 --config=./webpack.dev.config.js", "build": "webpack --config webpack.build.config.js", "package": "webpack --config webpack.build.config.js",
  • When I run it in dev mode it resolves the correct path and everything is working just fine

I hope someone of you can help me or guide me into the right direction.

Possible Idea:

Reference a completely other path and copy the ps1 files into another directory with a gulp task? Never used it. Could this be a possible solution? If yes how to best approach this?

Update
When I copy the src folder from C:\Users\Huberdo\Projekte\Powershell-SAS-App\Client\builds\basic-electron-react-boilerplate-win32-x64\resources\app into the root C:\Users\Huberdo\Projekte\Powershell-SAS-App\Client\builds\basic-electron-react-boilerplate-win32-x64 it's working again. So it's mainly a path issue and I don't know how to solve it.

Last but not least a direct link to the project on github:

https://github.com/dhuber666/Powershell-SAS-Tool

Here I call the ps1 script:

https://github.com/dhuber666/Powershell-SAS-Tool/blob/SendAs/src/components/scriptsComponents/AddMailboxPermissions.js

!Thank you!

Unable to send array of strings

I am unable to send an array of Strings. When I send a JS array it reads it as one long string in the powershell script (i.e. it only loops through once in my powershell foreach loop) . I've also tried sending it formatted as a powershell array @()

JS

let users = ["account1", "account2"]
let params = [{name: 'Accounts', value: users}]
ps.addCommand(filePath + 'Enable-ADUser.ps1', params)
return ps.invoke()

Powershell

Param (
   [Parameter(Mandatory = $true)]
   [String[]] $Accounts
)

Not sure where I'm going wrong. Are we able to send an array to powershell?

Thank you!

'end' event not fired, outputs merged

I have this simple PS script which logs some messages but never exits, otthat is; It will never reach the ps.on('end').
Also, sometimes Write-Output are merged or i get output messages which are empty

` ps.on('output', function(data) {
console.log('output', data);
wss.clients.forEach(function each(client) {
client.send("broadcast:"+data);
});
});

ps.on('end', function(code) {
  console.log('END', code);
  ps.dispose();
  wss.clients.forEach(function each(client) {
    client.send("broadcast: "+code+ " END!!");
  });
});    
ps.invoke();`

the powershell code:

` param (
[string]$Name = $args.name
)

Write-Output 'Message 1';
Write-Output 'Message 2';
Write-Output 'Message 3';
Write-Output 'Message 4';
Return; # also tried: Exit, Exit(1), exit 1`

Intermittently the data from the power shell instance is blank

Intermittently but frequently, I get back an empty string from node-power shell in the then of the promise when the console shows it received data. Rerunning of the command on a new shell instance returns the data.

This is most previlant when I pool and reuse powershell instances, but I can also see this behavior on freshly spawned instances of the shell object.

Any ideas how to get around this and get a reliable return?

Test powershell command is ls | convert-to-json -compress. (Large file set)

Also have bluebird overwriting my Promise object. Node 6.9.1 windows 10

addCommand("ls c:") followed by invoke() always emits nothing (blank string)

Software used:

  • node-powershell 3.1.1
  • node 7.9.0
  • PowerShell 5.1.14393.1198
  • Windows 10 (1607)

I have noticed that addCommand("ls c:") followed by invoke() always emits nothing (just a blank string).

While I can get very simple "toy" commands (e.g., "echo hello") to work, even the following basic "non-toy" (i.e., one might actually want to do this) example always returns nothing:

const shell = new Shell({ debugMsg: false });
await shell.addCommand("ls c:");
const output = await shell.invoke();
console.log(output); // "" (blank)

Yet, when the same command (ls c:) is run manually at the PowerShell prompt, it obviously emits the top-level of my C: drive (several files and folders).

Then, I tried some experiments.

Experiment 1

const shell = new Shell({ debugMsg: false });
await shell.addCommand("echo HEAD; ls c:; echo TAIL");
const output = await shell.invoke();
console.log(output); // "HEAD\nTAIL"

The echoes come through, but the ls output is still missing.

Experiment 2

const shell = new Shell({ debugMsg: false });
await shell.addCommand("& { echo HEAD; ls c:; echo TAIL } | ConvertTo-Json -Compress");
const output = await shell.invoke();
console.log(output); // "[\"HEAD\"",\"TAIL\"]"

Again, just the ls output is missing.

Experiment 3

const shell = new Shell({ debugMsg: false });
await shell.addCommand("&{ echo HEAD; Get-UICulture; echo TAIL } | ConvertTo-Json -Compress");
const output = await shell.invoke();
console.log(output); // "[\"HEAD\",{\"Parent\":{\"Parent\":\"\",\"LCID\":9 ... },\"TAIL\"]"

Hmm, the Get-UICulture output is there (I show it truncated in the comment above), so why doesn't ls (aka, Get-ChildItem) also come through?

It seems some kinds of output is being dropped, but not others. Any idea what is going on?

TypeError: shell is not a constructor

I am running the following: var ps = new shell({executionPolicy: 'Bypass', debugMsg: true, noProfile: true});
and received the following error: [TypeError: shell is not a constructor]

any thoughts

Electron packaging with --asar argument

Hi,
I think this is not an issue of the node-powershell but a limitation.

I have packaged my electron application with electron-packager with parameter --asar . (If I don't use asar argument it works.)
When using the app, I'm unable to execute PowerShell scripts because all the files are inside an app.asar file.
I already use the path variable like
ps.addCommand(path.join(__dirname, "/scripts/testing.ps1"), [ ....... ]);

I think I know the answer but Is it possible to use scripts inside that file?
Anyone know any alternative to hide the scripts?

Console Error
[MYPATH]\resources\app.asar\scripts\testing.ps1 is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Executing scripts with special characters on the path

Hi,

I'm trying to invoke the following command

& 'C:\folder\folder\ãpplic ation\scripts\script.ps1'

I know the issue is on the "ã" but i'm not able to find a solution to escape this.

Error

& : The term 'C:\folder\folder\ãpplic ation\scripts\script.ps1' is not recognized as
the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.

I tried things like

& (Convert-Path -LiteralPath 'C:\folder\folder\ãpplic ation\scripts\script.ps1')

or

$command = Convert-Path -LiteralPath 'C:\folder\folder\ãpplic ation\scripts\script.ps1';
& $command

But i get the error

Cannot find path 'C:\folder\folder\ãpplic ation\scripts\script.ps1' because it does not exist

When executing on the powershell command line this work but using the node-powershell to invoke the command does not.
Someone have any way to resolve this?

String parameters with quotes hang shell

If a string containing a single (') or double (") quote is passed to addCommand the shell instance hangs. It is expecting a matching quote, which may or may not come. In Utils.js there is only a check for whitespace in strings.

PR to come.

Relative paths to PS scripts on Windows machines

I'm having some issues loading a ps1 file using a relative path on a Windows machine.

When I try to add a ps1 using a direct path, such as this, everything works great:
ps.addCommand("C:/dev/powershell-electron-demo/Get-Drives", [{ ComputerName: computer }]);

But then when I try a relative path, such as this, I get an error about it not being found:
ps.addCommand("./Get-Drives", [{ ComputerName: computer }]);

I'm 100% positive my Get-Drives.ps1 is in my root folder, the same folder with my index.html and renderer.js. Everything works great with a direct path. I've tried every combination of forward slash, back slash, double slash, single periods, double periods, etc. Any ideas?

"EOI" marker matching logic often "eats" last chunk of output

Software used:

  • node-powershell 3.1.1
  • node 7.9.0
  • PowerShell 5.1.14393.1198
  • Windows 10 (1607)

I have debugged and discovered that the code in node-powershell that matches the internal End-of-Input (EOI) marker can blindly throw away entire swaths of output just because it is emitted as part of the same data chunk that happens to contain the characters "EOI":

Excerpt from Shell.js

    _this._proc.stdout.on('data', function (data) {
      if (data.indexOf(EOI) !== -1) {
        _this.emit(_type, _output.join(''));  // <== Any other output in "data" is lost here.  :(
        _output = [];
        _type = '_resolve';
      } else {
        _this.emit('output', data);
        _output.push(data);
      }
    });

I have definitely seen cases where ALL of the expected output of a command appeared in the same chunk as the "EOI" marker. In these cases, the entire output is simply lost (even though node-powershell goes on to complete the request successfully).

I made the following modification, and started getting a lot more expected output:

    _this._proc.stdout.on('data', function (data) {

      // BEGN OLD
      // if (data.indexOf(EOI) !== -1) {
      // END OLD

      // BEGIN NEW
      var offset = data.indexOf(EOI);
      if (offset !== -1) {
        data = data.substr(0, offset); // <== Grab any output before the "EOI" marker
        _this.emit('output', data);    // <== and process it
        _output.push(data);            // <== as usual.
      // END NEW

        _this.emit(_type, _output.join(''));
        _output = [];
        _type = '_resolve';
      } else {
        _this.emit('output', data);
        _output.push(data);
      }
    });

An even further improved implementation might:

  • use something more unique than just the characters "EOI" (perhaps a GUID), and
  • also carefully preserve ANY output that is part of the EOI chunk, not just the stuff that appears before the EOI marker (which is all my experimental modification above does). In theory, there might also be some more output following the EOI marker too (that is part of the output of another command) which, I would assume, should be grabbed and added to the output for the next command.

Also, note that issue #20 might be due to, and at least related to, this behavior.

Cannot run import-csv argv

I was trying to use this :
powershell.exe import-csv file.txt -Delimiter "t"> file.csv`

It works fine when pasted into console but fails saying "Missing an argument for parameter "Delimiter"".

I think some issue when the node process converts argv on console. Please help!

NO output from powershell when an argument value changes

Hello

I am trying to execute a simple get-aduser command and it works fine for most of the users.
But for some users the output is null.

When I log the command being invoked and execute from a standalone powershell it works just fine.

Thanks!

Using this within an Electron App

When just importing the shell and not using it I am getting this error.

Failed to compile: Module not found: 'child_process' in node_modules/node-powershell/dist/Shell.js

read ECONNRESET

My requirement is to call PowerShell from node.js Lambda.

I packed PowerShell in same zip and change source path for spawn from
powershell to /var/task/powershell

PowerShell is starting but not finishing properly I think commands are executing also but I am not getting a result whether the command is finish or not. I am getting the ECONNRESET error

read ECONNRESET
at _errnoException (util.js:1022:11)
at Pipe.onread (net.js:628:25)
      NPS>  Process 11 started
   Inside ShellWrite echo node-powershell
   NPS>  Command invoke started
   NPS>  echo node-powershell
   inside invoke 1
   Inside ShellWrite 
   inside invoke 2
   Inside ShellWrite echo EOI
   inside invoke 3
   Inside ShellWrite 
   Error: read ECONNRESET
   at _errnoException (util.js:1022:11)
   at Pipe.onread (net.js:628:25)

I added some logs to confirm which part is making a problem.
I am not getting any error on my local environment

Handling Execution Policy

Also, is it possible to set the ExecutionPolicy when calling the PowerShell, for example by using "bypass" option?

Spaces in path names to scripts don't seem to work

Hi There,
I'm unable to get Powershell to spawn with my script. My path has a space in it and I'm not sure if that's tripping it up. For example, this does not work:

var PS = require('node-powershell');
var shell = new PS('C:\\Path\\To\\My Favorite\\Directory\\test.ps1');

Nor does the following work

var PS = require('node-powershell');
var shell = new PS('C;/Path/To/My\ Favorite/Directory/test.ps1');

Can't create windows folder

hi,

If I use the command New-Item C:\test –type directory in powershell it works, but not in node-powershell. also not with c:\test


W20171009-08:19:18.586(2)? (STDERR)     + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

Can't I use my javascript variables in this way? Should I use parameters?

all code:

 let ps = new shell({
        executionPolicy: 'Bypass',
        noProfile: true
    });
    var folder = Meteor.settings.qlikSense.sharedPersistanceFolder;
    var name = Meteor.settings.qlikSense.sharedPersistanceFolderName;

    // ps.addCommand('Write-Host Creating a shared folder on: ' + folder);
    ps.addCommand('New-Item ' + 'C:\\test' + ' –type directory');
    // ps.addCommand('New-SmbShare –Name ' + name + ' –Path ' + folder + ' –FullAccess Everyone  ')

    ps.invoke()
        .then(output => {
            console.log(output);
        })
        .catch(err => {
            console.error('Installation failed, make sure you check the log file in GitHub\QRSMeteor\.automation\InstallationSoftware\log.txt', err)
            ps.dispose();
        });

Working with SecureString and PSCredential

I'm invoking a command that create a System.Security.SecureString object but I can't use the output to create a System.Management.Automation.PSCredential object, because the returned value is a 'System.Security.SecureString' string literal.

Is it possible to add commands with SecureString and PSCredential objects as parameters or it's only can be done using a ps script?

Thanks in advance,

Zak.

How can I run the scripts under another user?

Hi guys,

I have to run some scripts with a different users. For example the Exchange Command:
Add-MailboxPermissions doesn't take a -Credential Parameter.

But I have to provide it because the normal domain User has no rights for that command. If there is no way to run a script as could you give me a tip to solve this in another way? If I would start my IDE (Visual Studio Code) as another User and then run the app, the scripts should get run from that user, am I right?

No console logs

Is there a way to make NPS run silently? Without any logs to the console?

Node commands in Powershell

Hi,
I have downloaded and installed via:
npm i -S node-powershell
yarn add node-powershell

I run the 'Quick Start' script from within a PS script and get:

At C:\Users\jonathon2\Ethereum Projects\helloWorldVoting\NPSdemo.ps1:10 char:11

  • ps.invoke()
  •       ~
    

An expression was expected after '('.
At C:\Users\jonathon2\Ethereum Projects\helloWorldVoting\NPSdemo.ps1:16 char:14

  • ps.dispose();
  •          ~
    

An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : ExpectedExpression

I want to script a series of node commands from within PowerShell.

I'm probably missing something basic. What am I doing wrong?
Thx.

error running example on linux

When I try to run provided example on ubuntu with powershell 6 installed on it i getting folowing error:

<node-powershell>:: Process undefined started

<node-powershell>:: Command invoke started



Error: This socket is closed
    at Socket._writeGeneric (net.js:673:19)
    at Socket._write (net.js:725:8)
    at doWrite (_stream_writable.js:307:12)
    at writeOrBuffer (_stream_writable.js:293:5)
    at Socket.Writable.write (_stream_writable.js:220:11)
    at Socket.write (net.js:651:40)
    at /home/ed/git/alsocloud.visualstudio.com/ac-worker/node_modules/node-powershell/dist/Shell.js:133:36
    at Shell.invoke (/home/ed/git/alsocloud.visualstudio.com/ac-worker/node_modules/node-powershell/dist/Shell.js:130:20)
    at /home/ed/git/alsocloud.visualstudio.com/ac-worker/src/index.js:7:19
    at process._tickCallback (internal/process/next_tick.js:103:7)
    at Module.runMain (module.js:592:11)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Race condition with reset of _self._cmds in invoke().

The invoke() function only clears the internal _self._cmds array of "added" commands upon asynchronous completion of the PowerShell execution of the commands. This sets up a race condition with other command executions.

In certain circumstances, it is possible for additional commands to be added and invoke() called again before the processing of the previous invoke()has completed -- and before node-powershell has cleared the _cmds array. In these cases, the secondary invoke() calls "inherit" and extend the current contents of _cmds array already being processed by the original invoke() call.

In short, this race condition can result in PowerShell commands being executed multiple times and other unexpected chaos.

I quite easily ran into this in a project I was working on, where node-powershell was being hosted on a remote machine with addCommand() and invoke() calls being sent to it. Throw in any moderately long-running command (thus causing invoke() to take some time to complete), and the race condition is exposed.

The fix would appear to be to eliminate the race condition by simply clearing the _cmds array earlier, as the PowerShell command is submitted, rather than after it completes.

Like so:

      var _self = this;
      return new Promise(function (resolve, reject) {
        var _cmdsStr = _self._cmds.join('; ');

        // NEW
        // To avoid races, the commands array should be cleared up-front, here:
        _self._cmds = [];
        // END

        _self.__print__(OK_MSG, 'Command invoke started');
        _self._cfg.debugMsg && console.log(' ' + colors.gray(_cmdsStr));

        function resolve_listener(data) {
          _self.__print__(OK_MSG, 'Command invoke finished\n');
          reset();
          return resolve(data);
        }
        function reject_listener(error) {
          _self.__print__(ERROR_MSG, 'Command invoke failed\n');
          reset();
          return reject(ERROR_MSG(error));
        }
        function reset() {
          _self.removeListener('_resolve', resolve_listener);
          _self.removeListener('_reject', reject_listener);

          // OLD
          // Clearing it here (the current code) is way too late and creates race conditions.
          // _self._cmds = [];
          // END
        }

        _self.on('_resolve', resolve_listener);
        _self.on('_reject', reject_listener);

        _self._proc.stdin.write(_cmdsStr);
        _self._proc.stdin.write(os.EOL);
        _self._proc.stdin.write('echo ' + EOI);
        _self._proc.stdin.write(os.EOL);
      });

It might also be helpful for node-powershell to internally serialize multiple asynchronousinvoke() executions (perhaps with some kind of "operation queue"), since the target PowerShell process can only process one invocation at a time.

The node-powershell API also isn't helping out here, by separating into independent and potentially "racy" steps (addCommand() and invoke()) what really should be tied together. An improved API might instead provide a way to build a set of "commands" as an entity, which can then be specifically "invoked" (with no possible confusion with other any commands, as can occur with the current API).

Usage might look like this:

    let shell = new Shell();
    let commands = new shell.Commands();
    await commands.add('echo Now I can');
    await commands.add('echo build my commands');
    await commands.add('echo as a unit');
    let output = await commands.invoke();

Trouble Passing multiple parameters to PowerShell Script

I want to pass multiple parameters to my powershell Script file, but it is giving me errors . I am not able to figure out what I am doing wrong.

script.js

let params = [{name: 'KeyStorePassword_', value: "iddfggdff@96"},
{name: '$KeyAlias', value: 'key454'}
]
ps.addCommand('./WrappingPowerShellScript.ps1',params)
ps.invoke()

WrappingPowerShellScript.ps1

param (
[Parameter(Mandatory = $true)]
[string]$KeyStorePassword_,
[string]$keyAlias

)

Synchronous Invokation

I know it goes against node's grain but is there any way to invoke the PS commands synchronously?

Partial pipeline return

I love this library!

Is there any way to return pipeline output for a long running process? I need to query and update ACLs on remote machines. In a PowerShell window I use Write-Output to pass output down the pipeline. Is there a feature in this library to accomplish this, or are my users going to have to just wait for all the output at once?

ps.dipose() does not work in all instances

Hi,

Just wanted to let you know that I have found that ps.dipose, which I call in then() of ps.invoke() does not dispose the shell in every case, though it does work in most cases. Even if I call ps.dispose().then(), and then return my promise, the shell still sometimes remains open. I am unsure of why.

Please let me know if I could provide you with additional details.

Thank for for making this module.

new-webserviceproxy isn't supported

does node-powershell/powershell 6.0 support new-webserviceproxy?

if not, is there a way to rollback node-powershell to powershell 5 so it does support this cmdlet?

in powershell you can run previous versions of it, using "powershell -version 5 'echo test'", but for some reason, I can't do it here

Thanks!

Escaping string input

Correct me if I'm wrong on this. I've been passing JSON strings into PowerShell scripts then using ConvertFrom-Json to convert it to a hashtable. I noticed a few issues on the first few attempts. The workaround is simple enough, but perhaps JSON strings should be passable as params without needing to manually escape or wrap the input strings.

Using a parm block like { name: JSON.stringify({ name: "Mike" }) }
results in a call like test-string.ps1 -name {"name":"Mike"} which breaks on the powershell call.
To fix this I have to serialize my JSON then wrap it in single quotes or double quotes if it is escaped.

Here is a contrived example.

test-string.ps1

param (
    [Parameter(Mandatory = $true)]
    [string] $Name
)
$Name

test-script.js

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

    let scriptPath = require("path").resolve(__dirname, './test-string.ps1')
    ps.addCommand(scriptPath, [
        //  { name: "Hello World" } // Good
        //  { name: "Hello 'again' World" } // Good
        //  { name: 'Hello World' } // Good
        //  { name: 'Hello "again" World' } // Bad
        //  { name: JSON.stringify({name: 'Mike'}) } // Bad
        //  { name: "'" + JSON.stringify({name: 'Mike'}) + "'" } // Good
    ])
    ps.invoke()
    .then(output => {
        console.log(output)
    })
    .catch(err => {
        console.log(err);
        ps.dispose();
    });

32 vs 64 bit dlls

I have a module(3rd party module, not anything I have authored) that I use with PowerShell that is a 32bit dll, and I am running on a 64bit machine, so the instruction is to open with the 32bit ISE. This is the first time I am trying to use NodeJS to run my PS scripts, and I am getting the error "An attempt was made to load a program with an incorrect format", which on initial investigation seems to be related to this 32 vs 64bit clash. If anyone has any experience with this or has a workaround that would be hugely appreciated.

Usage with webpack

Hey,

So I've used webpack "file-loader" to load my powershell,

http://localhost:1212/dist/9d67ce14b061421ea6486929162ddaee.ps1

with

import powershell with "../../example/powershell.ps1"

then attempt to use it with

let ps = new Powershell({
      executionPolicy: 'Bypass',
      noProfile: true
    });

    ps.addCommand(powershell, [{ GigaWatts: 1.0 }]);

I get

is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I'm guessing I'll need to read in the file then paste it as string into the command to bypass this but it would be great if it supported it.

Better Error passing to JS

Given a simple throw "whoops" in PowerShell the message

whoops
At line:2 char:5
+     throw "whoops"
+     ~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (whoops:String) [], RuntimeException
    + FullyQualifiedErrorId : whoops

gets passed along to the JS.

It would be much easier to handle custom exceptions and display messages in the JS/frontend side if the exception object was serialized and passed from PS->JS. On the JS side, I may want to use the message, error id, line number, script name, etc.

try {
    throw "whoops"
} catch {
    $_ | ConvertTo-Json
}

With the above example, you mainly rely on the $_.Exception.Message or $_.Message

Some projects, Pester for instance, use a custom function to make their own Error ID.
Take the following:

function New-ErrorRecord ([string] $ErrorID, [string] $Message, [HashTable] $Custom) {
    $errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
    $exception = New-Object Exception $Message
    $errorRecord = New-Object Management.Automation.ErrorRecord $exception, $ErrorID, $errorCategory, $Custom

    $errorRecord
}

try {
    throw New-ErrorRecord -ErrorID "Crap.Its.Friday" -Message "You probably shouldn't do this today."
}
catch {
    $_ | ConvertTo-Json
}

Now you can use:

$_.FullyQualifiedErrorId
$_.Message

to get the type and message.

Version 1.2.0 is not backward compatible with 1.1.0

Latest bits look great, but probably qualify as a semver major release?

Usage that broke with 1.2.0
var PowerShell = require("node-powershell");
var psCommand = new PowerShell(scriptBlock);

Node is defaulting to ^ (caret) now so I had modules breaking after doing a simple npm update.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.