为什么 PowerShell Where-Object 在传递变量时不起作用? [英] Why doesn't PowerShell Where-Object work when passing a variable?
问题描述
功能
function findf {
Write-Host "Find files that match: $args"
gci -r | Where-Object { $_.name -match ".*$args.*" }
}
似乎不起作用.例如,
findf .exe
-- 打印一堆不限制输出到 EXE 文件的内容 --
-- Prints a bunch of stuff not limiting output to EXE files --
知道我做错了什么吗?
如果我从 PowerShell 命令窗口运行相同的命令,该命令将起作用:
If I run the same command from the PowerShell command window the command works:
gci -r | Where-Object { $_.name -match ".*.exe.*" }
这有效并正确地向我显示了与 *.EXE 模式匹配的文件
This works and correctly shows me the files that match the *.EXE pattern
推荐答案
$args
是一个表示 集合 参数的对象.
$args
is an object representing a collection of arguments.
你应该:
- 参考
$args[0]
获取表示第一个参数的字符串 - 使用
param
定义输入参数,如:
- Reference
$args[0]
to get the string representing the first argument - Use
param
to define the input parameter like:
.
function findf {
param ([string]$SeachStr)
Write-Host "Find files that match: $SeachStr"
gci -r | Where-Object { $_.name -match ".*$SeachStr.*" }
}
我总是提倡在可能的情况下使用 param
,因为您可以像我在示例中所做的那样强输入变量.否则可能会做一些令人困惑的事情,比如将数组作为参数传递,这会导致各种难以追踪的问题.
I always advocate using param
when possible, since you can strongly type your variables like I did in the example. Otherwise it might be possible to do something confusing like pass an array as a parameter which can cause all sorts of hard-to-trace issues.
这篇关于为什么 PowerShell Where-Object 在传递变量时不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!