简体   繁体   English

我可以在Powershell中创建一系列函数吗?

[英]Can I create an array of functions in Powershell?

I would like to have an array that contains a set of functions that I can iterate through and call. 我想有一个包含一组函数的数组,我可以迭代并调用它们。 The issue is that the functions all run via the line that adds them to the array (ie. $scripts). 问题是所有函数都通过将它们添加到数组的行(即$ scripts)运行。

Example: 例:

function Hello
{
    $BadFunction = "Hello"
    Write-Host "Hello!"
}

function HowAreYou
{
    $BadFunction = "HowAreYou"
    Write-Host "How are you?"
    #$false = $true
}

function Goodbye
{
    $BadFunction = "Goodbye"
    Write-Host "Goodbye!"
}

$scripts = @((Hello), (HowAreYou), (Goodbye))

foreach ($script in $scripts)
{
    $script
}

Functions can only be called by using their name, not referenced, but you can get the scriptblock via the Function: drive: 只能使用未引用的名称来调用函数,但可以通过Function:驱动器获取scriptblock:

$scripts = $Function:Hello, $Function:HowAreYou, $Function:GoodBye

# call them with the & operator
$scripts | ForEach-Object { & $_ }

# You can also call them by calling Invoke on the scriptblock
$scripts | ForEach-Object Invoke

Joey's answer contains good information, but if all you need is to reference your functions by name , define your array as containing the function names as strings , and invoke the functions by those strings with & , the call operator : Joey的答案包含很好的信息,但是如果您只需要按名称引用函数, 则将数组定义为包含函数名称作为字符串 ,并使用&调用这些字符串的函数,调用运算符

function Hello {  "Hello!" }

function HowAreYou { "How are you?" }

function Goodbye { "Goodbye!" }

# The array of function names *as strings*.
# Note that you don't need @(...) to create an array.
$funcs = 'Hello', 'HowAreYou', 'Goodbye'

foreach ($func in $funcs)
{
  # Use & to call the function by the name stored in a variable.
  & $func
}

The issue is that the functions all run via the line that adds them to the array (ie. $scripts). 问题是所有函数都通过将它们添加到数组的行(即$ scripts)运行。

That's because your array elements are expressions (due to the enclosing (...) ) that call the functions (eg, (Hello) calls Hello and makes its output the array element), given that they're being referenced without single- or double-quoting . 那是因为你的数组元素是表达式 (由于封闭(...)调用函数(例如, (Hello) 调用 Hello并使其输出成为数组元素),因为它们被引用而没有单个或者双引号

Unlike in, say, bash , you cannot define string array elements as barewords (tokens without enclosing single- or double-quoting); bash ,你不能将字符串数组元素定义为单词 (没有包含单引号或双引号的标记); for instance, the following is a syntax error in PowerShell: 例如,以下是PowerShell中的语法错误

# !! Does NOT work - strings must be quoted.
$funcs = Hello, HowAreYou, GoodBye # ditto with @(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM