RC1140
RC1140

Reputation: 8663

Using JScript in powershell

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

Firstly is there a decent example of how this is done and secondly can you use this to validate normal javascript code (as I understand JScript is the MS implementation)

Upvotes: 8

Views: 17331

Answers (3)

js2010
js2010

Reputation: 27423

Jscript.net http://www.functionx.com/jscript/Lesson05.htm (or VisualBasic, F# ...) It has to compile into a 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

Upvotes: 0

Doug Finke
Doug Finke

Reputation: 6823

This may be a good starting point

PowerShell ABC's - J is for JavaScript (by Joe Pruitt)

Here is a 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

Upvotes: 5

John Fouhy
John Fouhy

Reputation: 42183

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 give you an object (actually two objects; you want the second one) that you can use to call the functions.

You can omit it if you want, and call the function like this:

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

but that's a bit of a pain.

Upvotes: 1

Related Questions