Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active July 24, 2023 09:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/5d66332069674de4914765a9c628474a to your computer and use it in GitHub Desktop.
Save cecilemuller/5d66332069674de4914765a9c628474a to your computer and use it in GitHub Desktop.
Run Powershell 7 commands in Node.js
import {exec} from "node:child_process";
/**
* Runs a Powershell 7 command.
* @param {string} command
* @returns {string}
* @example const stdout = await pwsh(`Write-Output "Hello World"`);
* @example const stdout = await pwsh(`Write-Output "Hello"; Write-Output "World"`);
*/
export async function pwsh(command) {
return new Promise((resolve, reject) => {
exec(
`[System.Console]::InputEncoding = [System.Console]::OutputEncoding = [System.Text.Utf8Encoding]::new();${command}`,
{
shell: "pwsh.exe",
execArgv: "-nologo -noninteractive -noprofile -command"
},
(error, stdout, _stderr) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
}
);
});
}
// --------------------------------- //
// Usage examples
// --------------------------------- //
// Single command
const stdout = await pwsh(`Write-Output "Hello World"`);
// Multiple commands
const stdout = await pwsh(`Write-Output "Hello"; Write-Output "World"`);
// Non-ASCII
const stdout = await pwsh(`Write-Output "Héllô"`);
const stdout = await pwsh(`Write-Output "asdbščřoldTxtéíáuijhj"`);
const stdout = await pwsh(`Write-Output "帰国"`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment