是否可以从JavaScript调用powershell脚本?

时间:2016-04-19 08:57:17

标签: javascript powershell

我试图从js(像csript这样的命令)调用powershell脚本。 有可能吗?

谢谢

1 个答案:

答案 0 :(得分:0)

JScript (Windows)

简单的方法。

效果很好。适用于简单的操作,但在接收换行作为单个 \n 而不是预期的 \r\n 时会丢失一些数据。 Split by \r\n 误解了数组,导致需要重新格式化字符串数组。基本上我就这么写了,可能还有其他问题。

var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
    $OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
    Write-Output '"+toPStext+"'");
var output = std.StdOut.ReadAll().split('\r\n');// split('\n') - leads to the loss of some data
if (output.length>0){WScript.echo(output)}
//var x=WScript.StdIn.ReadLine();   

一行一行。

不幸的是,powershell 不接受外部数据作为行序列,这与带有 /q /k 选项的 cmd.exe 不同,它简化了此代码,但会解决多行输出代码的问题。当然,如果需要,您可以将代码作为base64字符串传输到powershell

var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var output=[],errors=[],WshRunning=0,WshFinished=1,WshFailed=2,i=0,tryCount=0;
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
$OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
Write-Output '"+toPStext+"'");
do{
    if (std.Status==WshFailed){
        errors.push('String '+i+' data read error: \n   '+std.StdErr.ReadLine());
        tryCount++
    }
    else if(std.Status==WshRunning){
        output.push(std.StdOut.ReadLine());
        tryCount=0;
        WScript.Echo('Running ...')
    }
    else if(std.Status==WshFinished){
        var last=std.StdOut.ReadLine();
        if(last.length>0){output.push(last)};last=undefined;
        tryCount=21;
        WScript.Echo('Finished ...')
    }i++;
}while(tryCount<21);        
if (output.length>0){WScript.echo(output)}
if (errors.length>0){WScript.echo(errors)}
var x=WScript.StdIn.ReadLine();
相关问题