Last active
July 24, 2023 09:44
-
-
Save cecilemuller/5d66332069674de4914765a9c628474a to your computer and use it in GitHub Desktop.
Run Powershell 7 commands in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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