gpt4 book ai didi

整数的 Powershell 输入验证

转载 作者:行者123 更新时间:2023-12-02 22:57:50 25 4
gpt4 key购买 nike

我想编写一个脚本,提示用户输入以分钟为单位的时间以启动关机计时器。我让它工作但没有输入验证。这就是我所拥有的。

DO{
try{

$numOk= $true
[int] $minutes= Read-Host "Enter the amount in minutes until a shut down (0 to cancel)"
#$minutes= [int]$minutes

}
catch{

#if($minutes -isnot [int]){}
$numOk= $false
Write-Host "Input is not an integer!!!!!"
}

} while ($numOk = $false)


[int] $seconds= $minutes*60

if($seconds -eq 0){
shutdown -a
}
else{
shutdown -s -t $seconds
}

当我输入一个字母时,我得到了一个非常奇怪的值。

PS C:\Users\USER\Desktop\shut down> .\shutdownTimer.ps1
Enter the amount in minutes until a shut down (0 to cancel): a
Input is not an integer!!!!!
Cannot convert value "555555555555555555555555555555555555555555555555555555555555" to type "System.Int32". Error: "Value was either
too large or too small for an Int32."
At C:\Users\USER\Desktop\shut down\shutdownTimer.ps1:25 char:1
+ [int] $seconds= $minutes*60
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger

shutdown : Unable to abort the system shutdown because no shutdown was in progress.(1116)
At C:\Users\USER\Desktop\shut down\shutdownTimer.ps1:29 char:1
+ shutdown -a
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Unable to abort...progress.(1116):String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

不太清楚所有这些 5 是从哪里来的。

最佳答案

您的代码在 while ($numOk = $false) 处有错误。在 powershell 中,= 是赋值运算符。比较运算符是 shell 样式的:-eq-ne-gt-gte-lt-lte-like 等。见 here

您可能希望使用 [int]::TryParse 来测试输入,如下所示:

$inputValue = 0
do {
$inputValid = [int]::TryParse((Read-Host 'gimme a number'), [ref]$inputValue)
if (-not $inputValid) {
Write-Host "your input was not an integer..."
}
} while (-not $inputValid)

关于整数的 Powershell 输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805855/

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