PowerShell ScriptBlock和多个功能

问题描述 投票:2回答:1

我写了以下代码:

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]

它有效,但我不想在GetBar中定义GetFoo

我可以这样做吗?

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。

powershell powershell-remoting scriptblock
1个回答
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"
© www.soinside.com 2019 - 2024. All rights reserved.