基本上,我需要使用驗證模式來驗證一些數字。我需要能夠運行 .\Myfilename "number" "number" "number" "number" "number" 并且它應該對腳本中的這些數字做一些事情。
我要輸入的內容的一個實際示例是: .\Myfilename 100 100 20 30 50
我無法弄清楚的是如何使用 validatepattern 來確保這些數字是整數。
這是我嘗試過的:
Param ([ValidatePattern("\d")] $G1 = 0, $G2= 0, $G3 = 0, $G4 = 0, $G5 = 0)
我也試過:
Param ([ValidatePattern("\d\s\d\s\d\s\d\s\d")] $G1 = 0, $G2= 0, $G3 = 0, $G4 = 0, $G5 = 0)
無濟于事......任何幫助將不勝感激!
uj5u.com熱心網友回復:
我認為ValidatePattern Attribute在這種情況下不需要a ,除非您確實希望引數具有特定模式。此外,您不需要每個引數都有一個引數。您只能有一個引數并對其進行型別約束,[int[]]并使用該引數ValueFromRemainingArguments argument來確保您捕獲所有輸入。
- 示例腳本.ps1:
[cmdletbinding()]
param(
[parameter(ValueFromRemainingArguments)]
[int[]]$Numbers
)
$i = 0
foreach($number in $Numbers)
{
[pscustomobject]@{
ArgumentNumber = ($i )
Input = $Number
IsInt = $Number -is [int]
}
}
- 樣本輸入和輸出:
PS /> ./script.ps1 123 345 567
ArgumentNumber Input IsInt
-------------- ----- -----
0 123 True
1 345 True
2 567 True
如果您要使用無效輸入,例如string:
PS /> ./script.ps1 123 345 567 'asd'
$Error[0].Exception.InnerException.Message將是:
無法將值“System.Collections.Generic.List`1[System.Object]”轉換為型別“System.Int32[]”。錯誤:“無法將值“asd”轉換為型別“System.Int32”。錯誤:“輸入字串的格式不正確。”
注意:通過使用此方法,輸入應始終遵循以下格式之一:
<int><white space><int><white space><int>...., IE:123 345 567<int><comma><int><comma><int><comma>...., IE:123, 345, 567
不遵循此語法的輸入將導致例外。
<int><comma><int><white space><int>, IE:123, 345 567
會給你以下例外:
無法將值“System.Collections.Generic.List`1[System.Object]”轉換為型別“System.Int32[]”。錯誤:“無法將“System.Object[]”型別的“System.Object[]”值轉換為“System.Int32”型別。”
[ValidatePattern("\d")]不是您要查找的有效模式(每個引數一個或多個數字)。\d將接受任何至少有 1 個數字的輸入:
[cmdletbinding()]
param (
[ValidatePattern("\d")] $Grade1 = 75
)
"Input was: $Grade1"
PS /> ./script.ps1 1asd
Input was: 1asd
PS /> ./script.ps1 asd2
Input was: asd2
如果您希望輸入全部為數字,最簡單的方法是輸入約束引數,如果確實需要使用Validate Pattern,則所有數字的模式為^\d $:
[cmdletbinding()]
param (
[ValidatePattern("^\d $")]
[int] $Grade1 = 75
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368896.html
標籤:电源外壳
