我在PowerShell函数参数上做错了什么?

时间:2018-07-24 07:02:10

标签: function powershell parameter-passing

如果有人能指出我在将参数从函数传递回主线代码时做错了什么,我将非常感激。我有一个已成功提取到函数中的变量,但似乎无法将其传递回主代码

这是我正在使用的代码:

function get-field ($field, $heading) {
    $fieldPos = $script:source.AllElements.InnerText.IndexOf($heading) +1
    $field = $script:source.AllElements.InnerText[$fieldPos]    

    # If states "Not Available", or contains a heading, process as if not found.
    if ($field -eq "Not Available ") {$fieldPos = 0}
    if ($field -eq $heading) {$fieldPos = 0}

    # Check that a valid entry was received
    if ($fieldPos -eq 0) {
        Write-Host "Warning:" $heading "was not found" 
    } else {
        $field = $field.Trim()
    }

    return $field
}    

get-field $email "Name"
get-field $address "Address"

我已验证函数内的$field$heading参数包含正确的信息,那么为什么不填充$email$address字段呢?

2 个答案:

答案 0 :(得分:2)

您并没有完全错误。

看看这个例子:

function get-field ($field, $heading) {

    return "$field - $heading"
}

$address = get-field "AddressFiled" "AddressHeading"
$address

要在变量中捕获返回的值以备将来使用,应像上面的示例一样调用该函数。

答案 1 :(得分:0)

PowerShell中的

参数通常用于将值传递给一个函数。必须将函数的输出分配给调用该函数的语句中的变量。另外,在函数内使用全局变量也是一种糟糕的设计,因为这会使调试变得更加困难。

您的代码应该看起来像这样:

function Get-Field ($data, $heading) {
    $fieldPos = $data.IndexOf($heading) + 1
    $field    = $data[$fieldPos].Trim()

    # If states "Not Available", or contains a heading, process as if not found.
    if ($field -eq 'Not Available' -or $field -eq $heading) {
        Write-Host "Warning: ${heading} was not found" 
    }

    $field
}    

$email   = Get-Field $script:source.AllElements.InnerText 'Name'
$address = Get-Field $script:source.AllElements.InnerText 'Address'

如果需要,您可以 设置参数,但是在PowerShell中它们很少见,这可能是因为它们不如人们想要的那样简单易用。

function Get-Field ([ref]$field, $data, $heading) {
    $fieldPos    = $data.IndexOf($heading) + 1
    $field.Value = $data[$fieldPos].Trim()

    # If states "Not Available", or contains a heading, process as if not found.
    if ($field -eq 'Not Available' -or $field -eq $heading) {
        Write-Host "Warning: ${heading} was not found" 
    }
}    

$email = $null
Get-Field ([ref]$email) $script:source.AllElements.InnerText 'Name'
$address = $null
Get-Field ([ref]$address) $script:source.AllElements.InnerText 'Address'