我刚接触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();在上面的例子中,我可以告诉第二个命令行在第二个命令行中执行help。我正在寻找一个好的方法来逃避引号问题,并以正确的方式告诉它如何执行myscript。
编辑
Ps :我并没有试图将someScript.ps的路径传递给第二个powershell命令行。我想按字面意思传递,以多行格式。
发布于 2018-08-29 03:00:34
我不知道这是不是正确的方式,但是你可以用下面的代码做同样的事情
$argPowershell_2 = "help";
Start-Process -Wait powershell -ArgumentList "Start-Sleep -Milliseconds 500; start powershell -argumentlist $argPowershell_2" 发布于 2018-08-29 07:07:55
解决方案
在我的例子中,传递给powershell_1进程的参数可能是:
start powershell -argumentlist "-noexit","start-job -scriptblock { help; start-sleep 1;}使用这行代码,并通过跟踪新powershell进程中的后台作业,我得到了以下结果:

如果您愿意,可以在scriptblock中运行类似于(声明变量,定义/调用自定义函数,...等):
$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');}有关后台作业的更多详细信息,请参阅以下链接。这解决了我的问题。谢谢你们所有人。
https://stackoverflow.com/questions/52064203
复制相似问题