javascript 在 powershell 中使用 JScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3360441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:57:22  来源:igfitidea点击:

Using JScript in powershell

javascriptpowershell

提问by RC1140

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

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

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)

首先有一个很好的例子说明这是如何完成的,其次你可以使用它来验证普通的javascript代码(据我所知,JScript是MS实现)

采纳答案by Doug Finke

This may be a good starting point

这可能是一个很好的起点

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

PowerShell ABC's - J 用于 JavaScript(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

回答by John Fouhy

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

这是一个简单的 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)

-PassThruwill give you an object (actually two objects; you want the second one) that you can use to call the functions.

-PassThru会给你一个对象(实际上是两个对象;你想要第二个),你可以用它来调用函数。

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.

但这有点痛苦。

回答by js2010

Jscript.net http://www.functionx.com/jscript/Lesson05.htm(or VisualBasic, F# ...) It has to compile into a dll.

Jscript.net http://www.functionx.com/jscript/Lesson05.htm(或VisualBasic、F#...)它必须编译成一个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