问题描述
-
Servers.txt
(包含服务器名称列表) -
test.ps1
(这是我的 PowerShell 脚本)
我的 test.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
循环)。