1

I'm trying to be able to interact with powershell using node-powershell.

Powershell output is typically a dataframe type object you can store in a variable. I'm just not clear on how to get the output back into JS to store/display it.

I think I need to be able to read the stdout but I'm not sure how to do this and keep the data in a formatted way.I'd like the data returned in an object.

In my code, im getting a pending promise back, i don't understand why.

const { PowerShell } = require('node-powershell')

const poshInstance = async () => {
    const ps = new PowerShell({
        executionPolicy: 'Bypass',
        noProfile: true,
    })

    const command = PowerShell.command`Get-LocalGroup`
    const output = await ps.invoke(command)
    //const output = await PowerShell.$`Get-LocalGroup`
    ps.dispose()
  const stringFromBytes = String.fromCharCode(...output.stdout)
    // console.log(stringFromBytes)
  return JSON.stringify(stringFromBytes)
}


const op = poshInstance()

console.log(op)


1
  • poshInstance is async function, so it is expected that it returns a promise. You can show the output like this: poshInstance().then( output => console.log( output ) ). Commented Apr 2, 2022 at 9:50

1 Answer 1

2

This library seams to return raw text output of the command. To create objects from this the simplest solution is to serialize the result to JSON format inside powershell session. Then you just have to parse the output.

const { PowerShell } = require('node-powershell')

const poshInstance = async () => {
    const ps = new PowerShell({
        executionPolicy: 'Bypass',
        noProfile: true
    })

    const command = PowerShell.command`Get-LocalGroup | ConvertTo-Json`
    const output = await ps.invoke(command)
    ps.dispose()
    console.log(output)
    const result = JSON.parse(output.raw)
    console.log(result)
}

(async () => 
{
    await poshInstance()
})();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, sir. This will help me get started. One question, at the end - what is this? })() The () part I've not seen before.
You have to await async function inside another async function. The parentheses create Immediately-Invoked Function Expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.