繁体   English   中英

将多行脚本从另一个PowerShell传递到PowerShell?

[英]Passing multiline script to PowerShell from another PowerShell?

我是Powershell的新手,我发现很难告诉我的第一个powershell命令行(powershell_1):启动新的powershell命令行(powershell_2)并让它(powershell_2)执行多行脚本(在powershell下编写)。

我的脚本是:

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop;
$wshell.Popup("Are you looking at me?",0,"Hey!",48+4);

我用来启动第一个Powershell命令行并按预期工作的代码

    Process powershell_1 = new Process();
    powershell_1.StartInfo.FileName = "powershell";

    string argPowershell_2 = "help";

    powershell_1.StartInfo.Arguments = "Start-Sleep -Milliseconds 500; start powershell -argumentlist \" "+ argPowershell_2 + " \"";
    MessageBox.Show(powershell_1.StartInfo.Arguments);

    powershell_1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    powershell_1.Start();

在上面的示例中,我可以告诉第二个命令行在第二个命令行中执行帮助。 我正在寻找一种避免引用问题并以正确的方式告诉它如何执行myscript的好方法。

编辑

附言:我不打算将someScript.ps的路径传递给第二个powershell命令行。 我想按字面传递多行格式。

我不知道是否正确的方法,但是您可以对下面的代码进行相同的操作

$argPowershell_2 = "help";
Start-Process -Wait powershell -ArgumentList "Start-Sleep -Milliseconds 500; start powershell -argumentlist $argPowershell_2" 

在我的情况下,传递给我的powershell_1进程的参数可能是:

start powershell -argumentlist "-noexit","start-job -scriptblock { help; start-sleep 1;}

使用此行代码,并通过在新的powershell进程中跟踪后台作业,我得到了以下结果:

(工作).childjobs |选择*跟踪工作结果

如果需要,可以在脚本块中运行类似的内容(声明变量,定义/调用自定义函数等):

$a = new-object System.net.webclient;
$a.downloadfile('https://www.stackoverflow.com','d:\file');

您需要使用` char来转义美元符号($)以及其他任何双引号(“)

start powershell -argumentlist "-noexit","start-job -scriptblock { `$a = new-object system.net.webclient; `$a.downloadfile('https://www.stackoverflow.com','d:\file');}

有关后台作业的更多详细信息,请参见下面的链接。 这解决了我的问题。 谢谢你们。

PowerShell:启动作业-scriptblock多行脚本块?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM