簡體   English   中英

PowerShell:: 輸入一個列表作為參數

[英]PowerShell :: input a list as param

在同一目錄中,我有 2 個文件:

  • 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

這很奇怪,因為代碼非常簡單。

目標是輸入我稍后要解析的服務器名稱列表。

有什么幫助嗎?

要從命令(而不是表達式)中使用 output 作為參數變量的默認值,您必須將其轉換為帶有(...)的表達式, 分組運算符

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

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

注意:僅當必須通過多個命令(或整個語句,例如foreachwhile循環)確定默認值時,才需要使用$(...)子表達式運算符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM