Function powershell使用脚本函数中的where对象不起作用
我正在尝试使用一个函数启用我的powershell配置文件脚本,该函数将允许我在当前powershell终端会话中执行文本和通配符搜索以查找函数的存在 在我的powershell配置文件脚本[$env:userprofile\Documents\WindowsPowerShell\Microsoft.powershell\u profile.ps1]中,我创建了以下函数Function powershell使用脚本函数中的where对象不起作用,function,powershell,pipe,Function,Powershell,Pipe,我正在尝试使用一个函数启用我的powershell配置文件脚本,该函数将允许我在当前powershell终端会话中执行文本和通配符搜索以查找函数的存在 在我的powershell配置文件脚本[$env:userprofile\Documents\WindowsPowerShell\Microsoft.powershell\u profile.ps1]中,我创建了以下函数 function Get-Fnc { #Get-ChildItem function:\ | Where-Objec
function Get-Fnc {
#Get-ChildItem function:\ | Where-Object { $_.Name -like "$args" }
Get-ChildItem function:\$args
}
使用注释掉的行getchilditem函数:\\\\124; Where对象{$\.Name-like“$args”}
不起作用,即使我可以在命令行上使用它,例如getchilditem函数:\\\124; Where对象{$\.Name-like“Get-*}
它按预期工作。使用未注释行Get ChildItem函数:\$args
在配置文件脚本函数和命令行中都起作用,例如Get ChildItem函数:\Get-*
在net和stackoverflow中搜索时,我无法找到关于使用输出管道|
到另一个cmdlet和/或在函数中使用Where-Object cmdlet来确定如何使其工作的任何详细信息。在命令行中已知对象工作时,如何将输出管道化到脚本函数中对象工作的位置
更新
除了提供的答案外,solutin还能够使用以下内容
function Get-Fnc {
$argsFncScope = $args # works because we make function scoped copy of args that flows down into Where-Object script block / stack frame
Write-Host "function scoped args assigned variable argsFncScope = $argsFncScope and count = $($argsFncScope.Count) and type = $($argsFncScope.GetType().BaseType)"
Get-ChildItem function:\ | Where-Object { $_.Name -like "$argsFncScope" }
}
调试输出
get-fnc *-env
[DBG]: PS C:\Users\myusrn\Documents\WindowsPowerShell>
function scoped args assigned variable argsFncScope = *-env and count = 1 and type = array
[DBG]: PS C:\Users\myusrn\Documents\WindowsPowerShell>
CommandType Name Version Source
----------- ---- ------- ------
Function Get-Env
每个scriptblock都有自己的$args自动变量
function Get-Fnc {
Get-ChildItem function:\ | where-object { write-host $args;
$_.name -like "$args" } }
get-fnc get-*
# lots of empty lines
其中对象为$null数组的$args
function Get-Fnc {
Get-ChildItem function:\ | where-object { $global:myargs = $args;
$_.name -like "$args" } }
get-fnc get-*
$myargs
$myargs.count
0
$myargs.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
但是,您可以使用不使用scriptblock的where对象的其他版本:
function Get-Fnc {
Get-ChildItem function:\ | where-object name -like $args }
get-fnc get-*
CommandType Name Version Source
----------- ---- ------- ------
Function Get-Fnc
另见:
实际上,我不知道如何在where对象scriptblock中设置$args,但这里是scriptblock和$args的另一个示例$args实际上是一个数组
我怀疑您看到的是范围问题。大多数情况下,函数都有自己的作用域,而您可能不知道在该特定作用域中,
$Args
包含哪些内容另外,$Args
是保留的$var名称之一[并且是一个数组]。除非您确定该名称在任何给定情况下都是正确的,否则您可能不会使用该确切名称。感谢您详细了解造成此问题的$args范围问题。非常出乎意料的是,$args只在函数作用域中可用,但不会向下流到子脚本块中,我认为它是函数中的堆栈帧。我发现,如果我将$args分配给函数作用域中的变量,该变量在函数中的子脚本块中是有效的。似乎任何脚本块都有自己的$args,包括作业和调用命令。
& { $args[0]; $args[1] } hi there
hi
there