gpt4 book ai didi

PowerShell ScriptBlock 和多种功能

转载 作者:行者123 更新时间:2023-12-02 23:47:43 27 4
gpt4 key购买 nike

我写了以下代码:

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 中,然后调用其中一个。这样我就不必在函数内部定义函数,我可以通过注入(inject)我想成为该 ScriptBlock 一部分的函数来构造 ScriptBlock。

最佳答案

问题是 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"

关于PowerShell ScriptBlock 和多种功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com