Using JScript in PowerShell

Reading the documentation for powershells add-type seems like you can add JScript code to a powershell session.

Firstly, there is a worthy example of how this is done, and secondly, you can use this to check for normal JavaScript code (as I understand it, JScript is an MS implementation)

+6
javascript powershell
source share
3 answers

This could be a good starting point.

PowerShell ABC - J for JavaScript (Joe Prewitt)

Here is the code snippet from the above article:

function Create-ScriptEngine() { param([string]$language = $null, [string]$code = $null); if ( $language ) { $sc = New-Object -ComObject ScriptControl; $sc.Language = $language; if ( $code ) { $sc.AddCode($code); } $sc.CodeObject; } } PS> $jscode = @" function jslen(s) { return s.length; } "@ PS> $js = Create-ScriptEngine "JScript" $jscode; PS> $str = "abcd"; PS> $js.jslen($str); 4 
+5
source share

Here is a simple json parser: https://gist.github.com/octan3/1125017

 $code = "static function parseJSON(json) {return eval('(' +json + ')');}" $JSONUtil = (Add-Type -Language JScript -MemberDefinition $code -Name "JSONUtil" -PassThru)[1] $obj = $JSONUtil::parseJSON($jsonString) 

-PassThru will provide you with an object (in fact two objects, you want a second) that you can use to call functions.

You can omit it if you want and call the function as follows:

 [Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.JSONUtil]::parseJSON($jsonString) 

but it's a little pain.

+1
source share

Jscript.net http://www.functionx.com/jscript/Lesson05.htm (or VisualBasic, F # ...) should compile in dll.

 Add-Type @' class FRectangle { var Length : double; var Height : double; function Perimeter() : double { return (Length + Height) * 2; } function Area() : double { return Length * Height; } } '@ -Language JScript $rect = [frectangle]::new() $rect Length Height ------ ------ 0 0 
0
source share

All Articles