Reputation: 12297
In the same directory I have 2 files:
Servers.txt
(which contains a list of server names)test.ps1
(which is my PowerShell script)my test.ps1 contains this code:
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?
Upvotes: 0
Views: 1976
Reputation: 439193
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:
# 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).
Upvotes: 2