In PowerShell, how can I test if a variable holds a numeric value?

前端 未结 14 2087
轮回少年
轮回少年 2020-12-16 09:15

In PowerShell, how can I test if a variable holds a numeric value?

Currently, I\'m trying to do it like this, but it always seems to return false.

14条回答
  •  春和景丽
    2020-12-16 10:05

    I ran into this topic while working on input validation with read-host. If I tried to specify the data type for the variable as part of the read-host command and the user entered something other than that data type then read-host would error out. This is how I got around that and ensured that the user enters the data type I wanted:

    do
        {
        try
            {
            [int]$thing = read-host -prompt "Enter a number or else"
            $GotANumber = $true
            }
        catch
            {
            $GotANumber = $false
            }
        }
    until
        ($gotanumber)
    

提交回复
热议问题