Read-Host
從主控台讀取一行輸入。
語法
Read-Host
[[-Prompt] <Object>]
[-MaskInput]
[<CommonParameters>]
Read-Host
[[-Prompt] <Object>]
[-AsSecureString]
[<CommonParameters>]
Description
Read-Host
Cmdlet 會從控制台 (stdin) 讀取一行輸入。 您可以使用它來提示使用者輸入。 因為您可以將輸入儲存為安全字串,因此您可以使用此 Cmdlet 來提示使用者輸入安全數據,例如密碼。
注意
Read-Host
有 1022 個字元的限制,它可以接受使用者作為輸入。
範例
範例 1:將主控台輸入儲存至變數
此範例會以提示顯示字串 「Please enter your age:“。 輸入值並按下 Enter 鍵時,該值會儲存在 $Age
變數中。
$Age = Read-Host "Please enter your age"
範例 2:將主控台輸入儲存為安全字串
此範例會在提示中顯示字串 「Enter a Password:“。 輸入值時,星號 (*
) 會出現在控制臺上,以取代輸入。 按下 Enter 鍵時,值會儲存為 SecureString 物件,並儲存在 $pwd_secure_string
變數中。
$pwd_secure_string = Read-Host "Enter a Password" -AsSecureString
範例 3:遮罩輸入和作為純文字字串
此範例會在提示中顯示字串 「Enter a Password:“。 輸入值時,星號 (*
) 會出現在控制臺上,以取代輸入。 按下 Enter 鍵時,值會儲存為純文本 String 物件在 $pwd_string
變數中。
$pwd_string = Read-Host "Enter a Password" -MaskInput
範例 4:正規化輸入
本範例會提示使用者輸入以分號分隔的城市清單。 它會顯示使用者輸入的字串值。 在範例中,使用者新增了部分項目之間的空格。 這可能會導致腳本稍後出現錯誤,其中程式代碼需要確切的名稱。
此範例示範如何將輸入字串轉換成項目陣列,而不需要任何額外的空格。
$prompt = @(
'List the cities you want weather information for.'
'When specifying multiple cities, separate them with a semi-colon, like:'
"'New York; Osan; Koforidua'"
) -join ' '
$cities = Read-Host $prompt
"Input cities string: `n`t'$cities'"
$splitCities = $cities -split ';'
"Split cities array:"
$splitCities | ForEach-Object -Process { "`t'$_'" }
$normalizedCities = $splitCities | ForEach-Object -Process { $_.Trim() }
"Normalized split cities array:"
$normalizedCities | ForEach-Object -Process { "`t'$_'" }
Input cities string:
' New York; Osan ;Koforidua '
Split cities array:
' New York'
' Osan '
'Koforidua '
Normalized split cities array:
'New York'
'Osan'
'Koforidua'
此範例會使用 -split
運算符,將輸入字串轉換成字元串陣列。 陣列中的每個字串都包含不同城市的名稱。 不過,分割字串包含額外的空格。
Trim()
方法會從每個字串中移除前置和尾端空格。
參數
-AsSecureString
指出 Cmdlet 會顯示星號 (*
),以取代使用者輸入為輸入的字元。 當您使用此參數時,Read-Host
Cmdlet 的輸出是 SecureString 物件(System.Security.SecureString)。
類型: | SwitchParameter |
Position: | Named |
預設值: | None |
必要: | False |
接受管線輸入: | False |
接受萬用字元: | False |
-MaskInput
指出 Cmdlet 會顯示星號 (*
),以取代使用者輸入為輸入的字元。 當您使用此參數時,Read-Host
Cmdlet 的輸出是 String 物件。
這可讓您安全地提示傳回為純文字的密碼,而不是 SecureString。
此參數已在PowerShell 7.1中新增。
類型: | SwitchParameter |
Position: | Named |
預設值: | None |
必要: | False |
接受管線輸入: | False |
接受萬用字元: | False |
-Prompt
指定提示的文字。 輸入字串。 如果字串包含空格,請以引弧括住它。 PowerShell 會將冒號 (:
) 附加至您輸入的文字。
類型: | Object |
Position: | 0 |
預設值: | None |
必要: | False |
接受管線輸入: | False |
接受萬用字元: | False |
輸入
None
您無法使用管線將物件傳送至此 Cmdlet。
輸出
根據預設,此 Cmdlet 會傳回字串。
當您使用 AsSecureString 參數時,此 Cmdlet 會傳回 SecureString。
備註
此 Cmdlet 只會從主機進程的 stdin 數據流讀取。 通常,stdin 數據流會連線到主機控制台的鍵盤。