繁体   English   中英

在Powershell中调用函数时,使用与参数和存储相同的变量

[英]Using the same variable as parameter and storage when calling a function in powershell

最近我有这个问题。 经过大量的研究,终于发现问题出在以下方面:

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

因此考虑到以下功能:

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中如果使用相同的变量却不起作用?

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

因此,相同的代码但经过了重构:

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

暂无
暂无

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

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