While working on Microservice development using NODE JS and PowerShell I have got stumped on Parameterization issue. So far I was working with single parameter all went fine and now got a new scenario where I need to work with two parameters with space as well. Interesting right? Yes, I meant the white space in the routes.
Look at this now!
http://localhost:3000/DisplayName/Chendrayan Venkatesan – Which turns out as http://localhost:3000/DisplayName/Chendrayan%20Venkatesan – Expected but didn’t work. Here my display name Chendrayan Venkatesan should be passed in routes as parameter value for PowerShell script
Failing Code – Using child_process module
app.get("/User/:DisplayName", function (request, response) { child = spawn("powershell.exe", [ "C:\\scripts\\demo.ps1 -DisplayName" + request.params.DisplayName ] ) console.log(request.params.DisplayName) child.stdout.pipe(response) })
My assumption was the value of request.params.DisplayName should be “Chendrayan%20Venkatesan” but it wasn’t
console.log(request.params.DisplayName) – Returned “Chendrayan Venkatesan” absolutely fine!
I tried for few hours over internet and didn’t find the solution to meet my need. So, with no wait I used node-powershell which works like charm!
Using node-powershell module
app.get("/user/:DisplayName", function (request, response) { ps.addCommand('./scripts/demo.ps1', [ { name: "DisplayName", value: request.params.DisplayName } ]) ps.invoke().then(output => { response.send(output) }) })
This works! Sample PS code is below!
param( $DisplayName ) process { $adsi = [adsisearcher]::new() $adsi.Filter = "(&(ObjectCategory=User)(displayname=$DisplayName))" $user = $adsi.FindOne() if($user) { $user.properties } else { "Something went wrong" } }
Parameter as Name Value Pair
ps.addCommand('./scripts/demo.ps1', [ { name: "DisplayName", value: request.params.DisplayName } ])
How to pass multiple parameters?
app.get("/add/:var1/:var2", function (request, response) { ps.addCommand("./scripts/demo.ps1", [ { name: "var1", value: request.params.var1 }, { name: "var2", value: request.params.var2 } ]) ps.invoke().then(output=>{ response.send(output) }) })
It’s that simple! Now you plan your PowerShell script ! Mine is ugly like shown below
param ( $var1, $var2 ) process { $var1 + $var2 }
Navigate to http://localhost:3000/3/4 – Returns 7 on your browser.