具有参数*和*功能的Powershell脚本 [英] Powershell script with params *and* functions

查看:78
本文介绍了具有参数*和*功能的Powershell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个包含参数并使用函数的powershell脚本.

I want to write a powershell script that takes in params and uses functions.

我尝试过:

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

好,我想.我会尝试以下方法:

Fine, I thought. I'll try this instead:

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

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

Is what I'm asking for doable? Or am I being unreasonable in my request?

推荐答案

脚本中的param块必须是第一个非注释代码.之后,您需要先定义函数,然后再调用它,例如:

The param block in a script has to be the first non-comment code. After that, you need to define the function before you invoke it e.g.:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

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

The Write-Output is unnecessary in your example since the default behavior is to output objects to the output stream.

这篇关于具有参数*和*功能的Powershell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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