簡體   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