[英]Using the same variable as parameter and storage when calling a function in powershell
Recently I had this problem. 最近我有这个问题。 After investigating a lot of hours, finally I discovered that the problem was in using the same variable for:
经过大量的研究,终于发现问题出在以下方面:
So taken into account below function: 因此考虑到以下功能:
Function Create-Filter($filter)
{
$filter.Split(',') | ForEach-Object {"*.$($_.Trim())"}
return
}
(Above function gets a string variable such as "csproj, vbproj" and converts it into *.csproj *.vbproj) (以上函数获取字符串变量,例如“ csproj,vbproj”,并将其转换为* .csproj * .vbproj)
...below code is not working, variable $filter used for -Include parameter does not like to Get-ChildItem and it is returning nothing: ...下面的代码不起作用,用于-include参数的变量$ filter不喜欢Get-ChildItem,它什么也不返回:
$filter = "csproj, vbproj"
$filter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $filter -Recurse
Instead below one is working by using a different variable for storing and pass it as a parameter: 相反,下面是通过使用其他变量来存储并将其作为参数传递的方法:
$filter = "csproj, vbproj"
$formattedfilter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $formattedfilter -Recurse
... now Get-ChildItem works. ...现在,Get-ChildItem起作用了。
In other languages one can use the same variable for passing it as a parameter and storing the value returned by the function. 在其他语言中,可以使用相同的变量将其作为参数传递并存储该函数返回的值。 So could you explain me why in powershell this does not work if one uses the same variable?
那么,您能否解释一下为什么在Powershell中如果使用相同的变量却不起作用?
Not sure why your code won't work, as the return in your case is redundant and the result is put on the output stream. 不确定代码为什么不起作用,因为这种情况下的返回是多余的,并且结果将放在输出流中。
So the same code but refactored: 因此,相同的代码但经过了重构:
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.