【问题标题】:Using the same variable as parameter and storage when calling a function in powershell在powershell中调用函数时使用与参数和存储相同的变量
【发布时间】:2019-10-31 09:31:51
【问题描述】:

最近我遇到了this 问题。在调查了很多小时后,我终于发现问题在于使用相同的变量:

  • 存储函数返回的值
  • 将其作为参数传递给函数

所以考虑到以下功能:

Function Create-Filter($filter)
{    
    $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"}
    return
}

(上面的函数获取一个字符串变量如"csproj, vbproj"并转换成*.csproj *.vbproj)

...下面的代码不起作用,用于 -Include 参数的变量 $filter 不喜欢 Get-ChildItem 并且它什么也不返回:

$filter = "csproj, vbproj"
$filter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $filter -Recurse

下面一个是通过使用不同的变量来存储并将其作为参数传递的:

$filter = "csproj, vbproj"  
$formattedfilter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $formattedfilter -Recurse

... 现在 Get-ChildItem 可以工作了。

在其他语言中,可以使用相同的变量将其作为参数传递并存储函数返回的值。那么你能解释一下为什么在 powershell 中如果使用相同的变量这不起作用吗?

【问题讨论】:

  • 你的代码产生 >>> Get-ChildItem 'D:\Path\To\My\Root\Folder' -Include *.csproj *.vbproj -Recurse Create-Filter 输入周围的括号...众所周知,这会导致奇怪的问题,因为不应该使用括号中的参数值调用 PoSh 函数。
  • 您使用哪个 PowerShell 版本?我无法在 5.1 和 6.2 上重现(我现在手头上只有这两个)。
  • 我无法在 5.1、4.0 和 2.0 上重现。我认为调用Create-Filter $Filter 是不带括号的尝试。
  • 它的行为就像$filter 的第一个分配永久地赋予它一个字符串类型。所以重新分配只是将数组输出转换为字符串(空格分隔)。
  • @robdy 我用的是 v5.1.17763.316

标签: function powershell powershell-3.0 powershell-4.0 get-childitem


【解决方案1】:

不确定为什么您的代码不起作用,因为您的情况下的返回是多余的,并且结果被放在输出流中。

所以同样的代码但是重构了:

function New-Filter
{    
    param (
        [Parameter(Mandatory=$true)]
        [String[]] $filter
    )

    return $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"}
}

$filter = @("csproj, vbproj")
$filter = New-Filter $filter
Get-ChildItem -Path "D:\Path\To\My\Root\Folder" -Include $filter -Recurse

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多