powershellpowershell-3.0

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"
}

Here in this PowerShell scripts, whenever a characters is typed is returns an error instead of message "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

This will uninstall windows update KB0


Solution

  • The error you are facing is cause by this:

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

    By defining the int variable type, any non-int input will cause an error. For example:

    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 tries to convert the string input to the type System.Int32 but since it is not possible as the input is a string, this error is caused which also causes the variable to not be defined whatsoever. If you are going to define it as a int, do it after the variable was initially defined like so:

    :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"
    }
    

    or alternatively you can do:

    :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"