gpt4 book ai didi

powershell - 检查传递的参数是字符串和整数

转载 作者:行者123 更新时间:2023-12-02 23:18:13 27 4
gpt4 key购买 nike

我是Powershell脚本的新手。我应该检查传递的第一个参数是否为字符串,第二个参数是否为int。

function positions { 
param (
[string] $inputstring,
[int] $num )
}

$inputstring=read-host "Enter your name"
if ( !$inputstring -eq "" ) {
Write-Output "The first recieved parameter is: " $inputstring "and its type is a string"}
else { Write-Output "The first received parameter is:" $inputstring "and its type is not a string" }

$num=read-Host "Enter a number"
if ( $num -eq int ) {
Write-Output "This second parameter is" $num "and its type is a integer"}
else { Write-Output "This second parameter is" $num "and its type is not a integer"}


我认为该字符串的if语句是错误的,因为只有当我用'!'取反时,它才能为我提供正确的输入。

另外,对于int而言,如果if语句在-eq之后不读取“int”。

我对此非常陌生,因此需要帮助。

最佳答案

首先,当您使用read-host从屏幕上获取输入时,无论您输入什么内容,输入都会被读取并存储为字符串。您可以通过运行以下命令并输入数字来确认这一点:
($checkInt = read-host).GetType().Name
无论您输入什么,都会输出字符串。等效的方法是定义输入变量,如下所示:
$checkInt = "10"

$StringVariable = "This is a string"
$IntVariable = 10
$StringIntVariable = "10"

## Print out variable types
"String variable is type " + $StringVariable.GetType().Name
"Int variable is type " + $IntVariable.GetType().Name
"StringInt variable is type " + $StringIntVariable.GetType().Name

同样,如果您检查该变量的类型,将返回 字符串

您需要做的是将 强制转换为int并检查该值是否为空或检查该值是否为数字:
## Checking if user input is alphanumeric
$stringIntVariable = Read-Host "Enter a number"
if (($stringIntVariable -as [int]) -ne $null) {
"StringIntVariable is numeric"
}
else {
"StringIntVariable is not numeric"
}

关于您的代码,以下将按您希望的方式工作:
$inputstring = read-host "Enter your name" 

if (($inputstring -as [int]) -eq $null) { ## Check if not castable to int
Write-Output "The first recieved parameter is: " $inputstring "and its type is a string"
}
else {
Write-Output "The first received parameter is:" $inputstring "and its type is not a string"
}

$num=read-Host "Enter a number"

## Checking if user input is numeric
if (($num -as [int]) -ne $null) {
Write-Output "This second parameter is" $num "and its type is a integer"
}
else {
Write-Output "This second parameter is" $num "and its type is not a integer"
}

正如 @TheMadTechnician所指出的,使用 ($num -as [int]) -ne $null比使用正则表达式匹配更宽容。

关于powershell - 检查传递的参数是字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59277611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com