How can I execute PowerShell ps1 scripts from package.json
"scripts"?
I know how to set up a basic script in package.json "scripts". For example with the following configuration, I can exec npm run test
which will output "this is only a test" to the console:
"scripts": {
"test": "echo \"this is only a test\""
}
However, I have a more advanced scenario where I'd like to execute a PowerShell script. Something like this:
"scripts": {
"buildAngular": "buildAngular.ps1"
}
Can I exec a ps1 script like this via the scripts object? Is any special setup/config required? Are there any additional constraints?
json file: To execute your Script, use the 'npm run <NAME-OF-YOUR-SCRIPT>' command. Some predefined aliases convert to npm run, like npm test or npm start, you can use them interchangeably.
To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.
1. Created a batch file which will have the code to execute the ps1 file & the batch file will be executed by C# code @echo offPowershell.exe -executionpolicy remotesigned -File <ps1 file path> 2. Created RunSpace & Pipeline to execute the ps1 file directly from C# code
The first line defines the variable name and store the string value and the second line prints the value of the variable. Note: Before executing a powershell script file through java make sure it executes from powershell command line or terminal. Next, we will create a java program to execute the script file we have created.
The simplest way is to right-click the file and choose 'Run with PowerShell'. As others have suggested, you can also run your .ps1 file using powershell.exe either in command prompt or from a BATCH or CMD file. As follows:
The error message states the script is not digitally signed and therefore cannot be loaded. To circumvent this, the Execution Policy is set to Unrestricted. Everything seems to be ready to execute the PowerShell script.
Assuming powershell is in you PATH you can call it like this:
"scripts": {
"test": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./test.ps1"
}
Tested on Windows 7 with Powershell v4.
Limitations are that you need Powershell installed and in your PATH. I didn't test it with Powershell for Linux, so not sure if this solution will be portable to other platform for now.
You might set the script-shell config - either via npm config set script-shell "powershell"
or environment variable $env:npm_config_script_shell="powershell"
Then you could use
"scripts": {
"test": "Write-Host 'this is only a test'"
}
or
"scripts": {
"buildAngular": ".\\buildAngular.ps1"
}
I'm not sure whether you can supply parameters like -NoProfile though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With