简体   繁体   English

PowerShell:: 输入一个列表作为参数

[英]PowerShell :: input a list as param

In the same directory I have 2 files:在同一目录中,我有 2 个文件:

  • Servers.txt (which contains a list of server names) Servers.txt (包含服务器名称列表)
  • test.ps1 (which is my PowerShell script) test.ps1 (这是我的 PowerShell 脚本)

my test.ps1 contains this code:我的 test.ps1 包含以下代码:

param(
    $Servers = get-content -Path "Servers.txt"
    ForEach($Server in $Servers) {
        $instance = $Server}
)

As soon as I try to run it I incur in the error:一旦我尝试运行它,我就会遇到错误:

At C:\test.ps1:2 char:15
+     $Servers = get-content -Path "Servers.txt"
+               ~
Missing expression after '='.
At C:\test.ps1:2 char:13
+     $Servers = get-content -Path "Servers.txt"
+             ~
Missing ')' in function parameter list.
At C:\test.ps1:5 char:1
+ )
+ ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingExpressionAfterToken

Which is very odd as the code is so simple.这很奇怪,因为代码非常简单。

The goal is to input a list of server names that I'm later going to parse.目标是输入我稍后要解析的服务器名称列表。

Any help?有什么帮助吗?

To use output from a command (as opposed to an expression ) as a parameter variable's default value, you must convert it to an expression with (...) , the grouping operator :要从命令(而不是表达式)中使用 output 作为参数变量的默认值,您必须将其转换为带有(...)的表达式, 分组运算符

# Parameter declarations
param(
    $Servers = (get-content -Path "Servers.txt")
)

# Function body.
ForEach($server in $Servers) {
  $instance = $server
}

Note: Use of $(...) , the subexpression operator , is only required if the default value must be determined via multiple commands (or whole statement (s), such as foreach or while loop).注意:仅当必须通过多个命令(或整个语句,例如foreachwhile循环)确定默认值时,才需要使用$(...)子表达式运算符

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

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