我想编写一个脚本,提示用户输入以分钟为单位的时间来启动关闭计时器。我可以使用它,但是没有输入验证。这就是我所拥有的。
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
不太确定所有这五个数字来自何处。
答案 0 :(得分:3)
您的代码在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)
答案 1 :(得分:0)
如果将变量强制转换为int
,PowerShell将自动检查输入。无法将a
分配给$minutes
,因为不能将其转换为int
。我确定您的变量已在您的PowerShell会话中以a
的形式分配给string
。 'a' * '60'
是a
的60倍,这会产生错误。清理变量,更好地重写代码。不需要Read-Host
和所有输入验证。 PowerShell将为您完成所有这些工作。
param(
# Enter the amount in minutes until a shut down
[int]$Minutes = 1
)
$Seconds = $Minutes * 60
Start-Sleep -Seconds $Seconds
Stop-Computer