PowerShell :: 输入一个列表作为参数
PowerShell :: input a list as param
在同一目录中我有 2 个文件:
Servers.txt
(包含服务器名称列表)
test.ps1
(这是我的 PowerShell 脚本)
我的测试。ps1 包含此代码:
param(
$Servers = get-content -Path "Servers.txt"
ForEach($Server in $Servers) {
$instance = $Server}
)
一旦我尝试 运行 它,我就会遇到错误:
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
这很奇怪,因为代码是如此简单。
目标是输入我稍后要解析的服务器名称列表。
有什么帮助吗?
要使用命令(相对于表达式)的输出作为参数变量的默认值,您必须将其转换为(...)
的表达式,grouping operator:
# Parameter declarations
param(
$Servers = (get-content -Path "Servers.txt")
)
# Function body.
ForEach($server in $Servers) {
$instance = $server
}
注意:仅当必须通过 多个 命令(或整个 语句(s),如foreach
或while
循环).
在同一目录中我有 2 个文件:
Servers.txt
(包含服务器名称列表)test.ps1
(这是我的 PowerShell 脚本)
我的测试。ps1 包含此代码:
param(
$Servers = get-content -Path "Servers.txt"
ForEach($Server in $Servers) {
$instance = $Server}
)
一旦我尝试 运行 它,我就会遇到错误:
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
这很奇怪,因为代码是如此简单。
目标是输入我稍后要解析的服务器名称列表。
有什么帮助吗?
要使用命令(相对于表达式)的输出作为参数变量的默认值,您必须将其转换为(...)
的表达式,grouping operator:
# Parameter declarations
param(
$Servers = (get-content -Path "Servers.txt")
)
# Function body.
ForEach($server in $Servers) {
$instance = $server
}
注意:仅当必须通过 多个 命令(或整个 语句(s),如foreach
或while
循环).