2012-10-27 53 views
1

我寫了下面的代碼:的PowerShell腳本塊和多種功能

cls 
function GetFoo() { 
    function GetBar() { 
     $bar = "bar" 
     $bar 
    } 

    $foo = "foo" 
    $bar = GetBar 
    $foo 
    $bar 
} 


$cred = Get-Credential "firmwide\srabhi_adm" 
$result = Invoke-Command -Credential $cred -ComputerName localhost 
-ScriptBlock ${function:GetFoo} 
Write-Host $result[0] 
Write-Host $result[1] 

它的工作原理,但我不想定義GetBarGetFoo內。

我可以這樣做嗎?

cls 
function GetBar() { 
    $bar = "bar" 
    $bar 
} 

function GetFoo() {  
    $foo = "foo" 
    $bar = GetBar 
    $foo 
    $bar 
} 


$cred = Get-Credential "firmwide\srabhi_adm" 
$result = Invoke-Command -Credential $cred -ComputerName localhost 
-ScriptBlock ${function:GetFoo; function:GetBar; call GetFoo} 
Write-Host $result[0] 
Write-Host $result[1] 

基本上我選擇性地把我想要的功能放在ScriptBlock中,然後調用其中的一個。這樣我就不必在函數內部定義函數了,我可以通過注入我想成爲ScriptBlock的一部分的函數來構造ScriptBlock。

回答

0

問題是Invoke-Command只能看到ScriptBlock裏面有什麼,它看不到外面定義的函數。如果你真的想 - 你可以在一個線路上運行的一切,就像這樣:

$result = Invoke-Command -ComputerName localhost -ScriptBlock { function GetBar() { $bar = "bar"; $bar }; function GetFoo() { $foo = "foo"; $bar = GetBar; $foo; $bar }; GetFoo } 

但我個人會建議你保存功能腳本,並調用Invoke-Command-FilePath參數,就像這樣:

$result = Invoke-Command -ComputerName localhost -FilePath "\1.ps1"