带有参数 * 和 * 函数的 Powershell 脚本

标签 powershell params

我想编写一个接受参数并使用函数的 powershell 脚本。

我试过这个:

param
(
  $arg
)

Func $arg;


function Func($arg)
{
  Write-Output $arg;
}

但我得到了这个:
The term 'Func' is not recognized as the name 
of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At func.ps1:6 char:5
+ Func <<<<  $arg;
    + CategoryInfo          : ObjectNotFound: (Func:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

好吧,我想。我会试试这个:
function Func($arg)
{
  Write-Output $arg;
}


param
(
  $arg
)

Func $arg;

但是后来,我得到了这个:
The term 'param' is not recognized as the name 
of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At C:\Users\akina\Documents\Work\ADDC\func.ps1:7 char:10
+     param <<<<
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

我所要求的可行吗?还是我的要求不合理?

最佳答案

脚本中的 param 块必须是第一个非注释代码。之后,您需要在调用之前定义该函数,例如:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

在您的示例中,Write-Output 是不必要的,因为默认行为是将对象输出到输出流。

关于带有参数 * 和 * 函数的 Powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902501/

相关文章:

powershell - 格式化Remove-Item命令的详细输出

ruby-on-rails-3 - 通过 link_to 合并嵌套参数

grails - Grails参数映射为java.util.HashMap

grails - 在grails中请求变量

data-binding - Grails - 向 params 映射添加参数

ruby-on-rails - 如何遍历 Controller 中的一些嵌套参数? rails 3

powershell - 在 Oneliner 中的 ConvertFrom-StringData 之后删除重复项

azure - "Get-AzureRmWebApp"需要哪个模块?

powershell - 使用 Powershell 在 CSV 的特定单元格中输入结果

powershell - 错误计数和$Error自动变量不一致