C# 将多行脚本从另一个PowerShell传递到PowerShell?
我是Powershell新手,我发现很难告诉我的第一个Powershell命令行(Powershell_1)启动一个新的Powershell命令行(Powershell_2)&让它(Powershell_2)执行我的多行脚本(在Powershell下编写) 我的剧本是:C# 将多行脚本从另一个PowerShell传递到PowerShell?,c#,powershell,escaping,quoting,C#,Powershell,Escaping,Quoting,我是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!",4
$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
编辑
Ps:我没有尝试将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进程中的后台作业,我得到了以下结果:
如果需要,可以在scriptblock中运行(声明变量、定义/调用自定义函数等):
您需要使用`字符对美元符号($)以及任何其他双引号(“”进行转义
start powershell -argumentlist "-noexit","start-job -scriptblock { `$a = new-object system.net.webclient; `$a.downloadfile('https://www.stackoverflow.com','d:\file');}
关于背景工作的更多细节在下面的链接中。这解决了我的问题。谢谢大家
但为什么?只需使用scriptblock和Jobs,就可以使用
调用表达式
并将路径和参数传递给要运行的脚本(如果您正试图这样做的话)。我编辑了我的帖子。我不想将脚本存储在.ps文件中。这可能适用于help命令。但它不会运行类似于start sleep 1;'hi';start sleep 1;'hello'的命令。另外,请注意,OP正在从C#调用PowerShell。为了让您的答案对未来的读者有所帮助,请发布一个工作示例,并最好解释您最初的question是一个例子。
start powershell -argumentlist "-noexit","start-job -scriptblock { `$a = new-object system.net.webclient; `$a.downloadfile('https://www.stackoverflow.com','d:\file');}