PowerShell ScriptBlock 和多种功能 [英] PowerShell ScriptBlock and multiple functions
本文介绍了PowerShell ScriptBlock 和多种功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下代码:
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]
它有效,但我不想在 GetFoo
内定义 GetBar
.
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]
基本上,我有选择地将我想要的函数放在 ScriptBlock 中,然后调用其中之一.这样我就不必在函数内部定义函数,我可以通过注入我想成为该 ScriptBlock 一部分的函数来构造 ScriptBlock.
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.
推荐答案
我知道这是一个旧线程,但我希望它对某人有所帮助.
I know this is an old thread, but I hope it helps someone.
[CmdletBinding()]
param()
$barScriptBlock = {
function GetBar() {
$bar = "bar"
$bar
}
}
$fooScriptBlock = {
function GetFoo() {
$foo = "foo"
$bar = GetBar
$foo
$bar
}
}
# Concatenate all functions into a script block; add a parameter for extra credit.
$scriptBlockString = @"
param(`$hello)
$($barScriptBlock.ToString())
$($fooScriptBlock.ToString())
`$hello
GetFoo
"@
Write-Verbose $scriptBlockString
# Convert combined string to script block.
$finalScriptBlock = [ScriptBlock]::Create($scriptBlockString)
# Run synchronously, passing runtime parameter.
$result = & $finalScriptBlock "Hola"
# (Async results would not be reiably accessed here yet.)
Write-Host $result[0]
Write-Host $result[1]
Write-Host $result[2]
这篇关于PowerShell ScriptBlock 和多种功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文