Powershell命令检查变量的数据类型是否为整数,如果它有字符,它应该用消息响应 "Enter Only number"

Powershell command to check if the data type of variable is integer, if it has characters it should respond with a message "Enter Only number"

[int]$name = Read-Host Enter the KB number
If ($name -is [int]) { 
    wusa /uninstall /kb:$name
    write-Host "This will uninstall windows update KB$name"
} else {
    write-Host "Enter only the number"
}

在此 PowerShell 脚本中,无论何时键入字符都是 returns 错误而不是消息 "Enter only the number"。

PS C:\Users\User\Desktop> .\Test.ps1
45454
Enter the KB number: asfs
Cannot convert value "asfs" to type "System.Int32". Error: "Input string was not in a correct format."
At C:\Users\User\Desktop\Test.ps1:5 char:1
+ [int]$name = Read-Host Enter the KB number
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

这将卸载 windows 更新 KB0

因为你把$name声明为一个只能接受数值的变量。试试这个代码:

$name = Read-Host Enter the KB number
[int]$number = $null
if ([int32]::TryParse($name, [ref]$number)) # test if is possible to cast and put parsed value in reference variable
{
    wusa /uninstall /kb:$name
    Write-Host "This will uninstall windows update KB$name"
}
else
{
    Write-Host "Enter only the number"
}

我选择了这种方式,将输入值转换成符合这个answer的数值。

我不知道是否有任何命令可以测试该值是否为整数。但是您可以使用正则表达式来检查特定类型的数据。这里我使用正则表达式来匹配整数类型的值。您可以使用以下代码

$i = 0
do {
    If ( $i -ne '0' ) { Write-Host 'Enter only Number' } 
$i = 1
$name = Read-Host 'Enter the KB Number'
} until ( $name -match '\b\d+\b')
wusa /uninstall /kb:$name

您遇到的错误是由以下原因造成的:

[int]$name = Read-Host Enter the KB number
^^^^^

通过定义int变量类型,任何非int类型的输入都会出错。例如:

PS C:\Users\Neko> [int]$test = read-host
ABC
Cannot convert value "ABC" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$test = read-host
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

Powershell 尝试将字符串输入转换为 System.Int32 类型,但由于输入是字符串,因此这是不可能的,因此会导致此错误,这也会导致变量无法定义。如果您要将其定义为 int,请在变量最初定义后执行此操作:

:loop while ($name = read-host Enter the KB number)
    {
    $name -as [int] | findstr $name
    if ($?)
        {[int]$name = $name; break loop}
    else
        {Write-Output "Invalid Input"}
    } 
wusa /uninstall /kb:$name
write-Host "This will uninstall windows update KB$name"
}

或者您可以这样做:

:loop while ($name = read-host Enter the KB number){
    $ErrorActionPreference = 'SilentlyContinue'
    [int]$name = $name
    if (!($name -is [int]))
    {echo "Invalid input"} 
    else 
    {break loop}
    }
wusa /uninstall /kb:$name
write-Host "This will uninstall windows update KB$name"