传递给函数的 Powershell 参数似乎不起作用 [英] Powershell argument passing to function seemingly not working

查看:80
本文介绍了传递给函数的 Powershell 参数似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我在做一些愚蠢的事情,但问题是:

I sense that I am doing something silly, but here is the issue:

Function getPropertyOfFile($a, $b, $c)
{
    $a.GetDetailsOf($b, $c)
}

如果我传递了适合函数的 $a, $b, $c 变量,它会说

If I pass $a, $b, $c variables that are appropriate to the function, it fails saying that

方法调用失败,因为 [System.Object[]] 不包含名为 'GetDetailsOf' 的方法."

"Method invocation failed because [System.Object[]] doesn't contain a method named 'GetDetailsOf'."

但是,如果我直接用我传递的参数替换 $a、$b、$c,然后尝试运行它,它就可以正常工作.

However, if I directly replace $a, $b, $c with the arguments that I was passing, and then try to run that, it works fine.

到底是怎么回事?

注意:我正在使用 powershell ISE,并通过将其复制/粘贴到控制台来将该函数输入到 powershell.我也一直在假设如果我输入一个同名的新函数,它会被覆盖.有没有更好的方法让 PS 从 .ps1 中读取?

Note: I am using powershell ISE, and am inputting the function to powershell by copy/pasting it into the console. I have also been working under the assumption that if I input a new function with the same name, it would overwrite. Is there a better way to just have PS read from the .ps1?

我正在尝试回答 这个问题变成函数.

I am trying to wrap the answer to this question into functions.

编辑 2:

Function getPropertyOfFile $a $b $c
{
    $a.GetDetailsOf($b, $c)
}

给出一个在函数声明中缺少函数体.在 line:1 char:28 错误.

推荐答案

PowerShell 中的函数的调用方式类似于 cmdlet,因此您无需使用逗号分隔参数.

Functions in PowerShell are called similar to cmdlets, so you don't need to separate arguments with commas.

您的调用可能如下所示:

Your invocation likely looks like this:

getPropertyOfFile($foo, $bar, $baz)

这导致 $a 具有值 $foo, $bar, $baz (一个数组)而 $b$c$null.

which results in $a having the value $foo, $bar, $baz (an array) while $b and $c are $null.

你需要这样称呼它:

getPropertyOfFile $foo $bar $baz

如前所述,这与您调用 cmdlet 的方式相同.你甚至可以这样做

which, as noted, is identical to how you call cmdlets. You could even do

getPropertyOfFile -a $foo -c $baz -b $bar

此时您可能会注意到您的函数参数没有很好地命名;-)

at which point you probably notice that your function arguments aren't named very well ;-)

编辑:如前所述,您对函数的声明很好.问题出在您没有发布的代码中,但对于具有 PowerShell 经验的人来说很容易推断出来.即,您的函数的调用.

As noted before your declaration of the function is fine. The problem is in the code you didn't post but is easily inferrable for people with PowerShell experience. Namely, the invocation of your function.

这篇关于传递给函数的 Powershell 参数似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆