2016-01-24 102 views
0

我試圖調用一個新的外殼,因爲庫中有內存泄漏。當我調用shell時,我需要傳遞一個arg(真正的代碼將傳遞2個參數)。代碼塊在新shell中執行後,它需要返回一個值。我寫了一些測試代碼重現錯誤:通過腳本內的新外殼傳遞參數

Function GetLastName 
{ 
    Param ($firstName) 

    $lastName = Powershell -firstName $firstName { 
     Param ([string]$firstName) 
     $lastName = '' 
     if ($firstName = 'John') 
     { 
      $lastName = 'Doe' 
      Write-Host "Hello $firstName, your last name is registered as $lastName" 
     } 
     Write-Host "Last name not found" 
     Write-Output $lastName 
    } 
    Write-Output $lastName 
} 

Function Main 
{ 
    $firstName = 'John' 

    $lastName = GetLastName $firstName 

    Write-Host "Your name is $firstName $lastName" 
} 

Main 

我得到的錯誤...

Powershell : -firstName : The term '-firstName' is not recognized as the name of 
a cmdlet, function, script file, or operable 
At C:\Scripts\Tests\test1.ps1:5 char:15 
+   $lastName = Powershell -firstName $firstName { 
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (-firstName : Th...e, or operable :String) [], RemoteException 
    + FullyQualifiedErrorId : NativeCommandError 

program. Check the spelling of the name, or if a path was included, verify that 
the path is correct and try again. 
At line:1 char:1 
+ -firstName John -encodedCommand DQAKAAkACQAJAFAAYQByAGEAbQAgACgAWwBzAHQAcgBpAG4A ... 
+ ~~~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (-firstName:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException

誰能幫助我如何做到這一點?

+0

使用['啓動Job'方法](http://stackoverflow.com/a/34300119)。它還爲主機流提供適當的分離。 – PetSerAl

+0

似乎很複雜。你能在答案部分舉個例子嗎? –

+0

請停止將語言標籤置於您的問題主題中。 –

回答

2

調用powershell.exe以在PowerShell中執行腳本塊的語法是有點不同:

powershell.exe -command { scriptblock content here } -args "arguments","go","here" 

所以在你的腳本應該是:

$lastName = powershell -Command { 
    Param ([string]$firstName) 
    $lastName = '' 
    if ($firstName = 'John') 
    { 
     $lastName = 'Doe' 
     Write-Host "Hello $firstName, your last name is registered as $lastName" 
    } else { 
     Write-Host "Last name not found" 
    } 
    Write-Output $lastName 
} -args $firstName 
+0

哦,讓我測試一下。謝謝回覆。 –

+0

很好,謝謝:) –

1

拆分代碼成兩個獨立的腳本,並使用一個只作爲第二啓動器。事情是這樣的:

# launcher.ps1 
powershell.exe -File 'C:\path\to\worker.ps1' -FirstName $firstName 

# worker.ps1 
[CmdletBinding()] 
Param($firstName) 

$lastName = '' 
if ($firstName = 'John') { 
    $lastName = 'Doe' 
    Write-Host "Hello $firstName, your last name is registered as $lastName" 
} 
Write-Host "Last name not found" 
Write-Output $lastName 

但是請注意,從來電者的角度,新工藝的主機輸出(Write-Host)合併到其正常輸出(Write-Output)。

+0

好吧,我希望將代碼保存在一個文件中,但看起來這是最好的選擇。開始工作是在我創建的表中添加不需要的屬性。 –

相關問題