【问题标题】:Passing multiline script to PowerShell from another PowerShell?将多行脚本从另一个 PowerShell 传递到 PowerShell?
【发布时间】:2019-02-03 11:04:03
【问题描述】:

我是 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 的好方法。

编辑

Ps:我不想将 someScript.ps 的路径传递给第二个 powershell 命令行。我想以多行格式逐字传递。

【问题讨论】:

标签: c# powershell escaping quoting


【解决方案1】:

解决方案

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

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

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

如果您愿意,可以在脚本块内运行类似(声明变量、定义/调用自定义函数等):

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

您需要转义美元符号 ($) 以及任何其他双引号 (") 使用 ` 字符。

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

有关后台作业的更多详细信息在下面的链接中。这解决了我的问题。谢谢大家。

PowerShell: Start-Job -scriptblock Multi line scriptblocks?

【讨论】:

  • 为了让未来的读者受益,请发布一个工作示例,并在理想情况下解释为什么您的原始问题是 XY problem 的一个实例。
【解决方案2】:

我不知道是否是正确的方式,但你可以用下面的代码做同样的事情

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

【讨论】:

  • 这可能适用于帮助命令。但它不运行类似 start-sleep 1;'hi';start-sleep 1;'hello'
  • 另外,请注意 OP 正在调用 PowerShell 从 C#
猜你喜欢
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 2021-08-04
  • 2015-07-07
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2019-07-07
相关资源
最近更新 更多