PowerShell ScriptBlock and multiple functions

非 Y 不嫁゛ 提交于 2020-01-02 12:45:55

问题


I have written the following code:

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]

It works but I don't want to define GetBar inside of GetFoo.

Can I do something like this?

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]

Basically I am selectively putting the functions which I want in the ScriptBlock and then calling one of them. This way I don't have to define function inside of function and I can construct the ScriptBlock by injecting the functions which I want to be a part of that ScriptBlock.


回答1:


The problem is that Invoke-Command can only see what's inside ScriptBlock, it can't see functions definded outside. If you really want to - you can run everything in one line, like this:

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

But I personally would advise you to save functions in script and call Invoke-Command with -FilePath parameter, like this:

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


来源:https://stackoverflow.com/questions/13100945/powershell-scriptblock-and-multiple-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!