简体   繁体   English

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

[英]Powershell script with params *and* functions

I want to write a powershell script that takes in params and uses functions. 我想写一个PowerShell脚本,它接受参数并使用函数。

I tried this: 我试过这个:

param
(
  $arg
)

Func $arg;


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

but I got this: 但我得到了这个:

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

Fine, I thought. 很好,我想。 I'll try this instead: 我会尝试这样做:

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


param
(
  $arg
)

Func $arg;

But then, I got this: 但是,我得到了这个:

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

Is what I'm asking for doable? 我要求的是可行的吗? Or am I being unreasonable in my request? 或者我的请求是不合理的?

The param block in a script has to be the first non-comment code. 脚本中的param块必须是第一个非注释代码。 After that, you need to define the function before you invoke it eg: 之后,您需要在调用函数之前定义函数,例如:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

The Write-Output is unnecessary in your example since the default behavior is to output objects to the output stream. 在您的示例中不需要写入输出,因为默认行为是将对象输出到输出流。

你只需要确保PARAM是你脚本的第一个字符串。

You can put the param tag inside the function.. 你可以把param标签放在函数里面。

Something like this: 像这样的东西:

function func($avg)
{
    param
    (
         $avg
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM