代码之家  ›  专栏  ›  技术社区  ›  RC1140

在powershell中使用JScript

  •  6
  • RC1140  · 技术社区  · 16 年前

    阅读powershell add type的文档,您似乎可以将JScript代码添加到powershell会话中。

    2 回复  |  直到 16 年前
        1
  •  5
  •   rvighne    10 年前

    这也许是一个很好的起点

    PowerShell ABC's - J is for JavaScript

    以下是上述文章的代码片段:

    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
    
        2
  •  1
  •   John Fouhy    11 年前

    下面是一个简单的json解析器: 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

    如果需要,可以省略它,并按如下方式调用函数:

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

        3
  •  0
  •   js2010    7 年前

    Jscript.net http://www.functionx.com/jscript/Lesson05.htm

    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