我们的服务器空间不足(剩余 435Gb),我们想知道什么时候会耗尽空间,因为每 15 小时就会创建新的 1Gb 文件。因此,我制作了一个脚本,用户可以在其中输入开始日期和 15 小时的单位。提供两个参数后,脚本将显示日期和时间。我面临的挑战是 Powershell 返回并超出范围错误。 AddHours 是否以某种方式违反了所提供日期的可变性?不知道如何解决这个问题。
# enter start date
$startDate = Read-Host "Enter the start date (MM/dd/yyyy)"
# enter in increments of 15 hours
$increments = Read-Host "Enter the number of 15-hour increments"
# convert the start date
$startDateObj = [DateTime]::ParseExact($startDate, "MM/dd/yyyy", $null)
# calculate future date applying 15 hr increments
$endDateObj = $startDateObj.AddHours($increments * 15)
# display the end date and time
Write-Host "End Date and Time: $($endDateObj.ToString("MM/dd/yyyy hh:mm tt"))"
这是生成的错误
Exception calling "AddHours" with "1" argument(s): "Value to add was out of range.
Parameter name: value"
At line:11 char:1
+ $endDateObj = $startDateObj.AddHours($increments * 15)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
You cannot call a method on a null-valued expression.
At line:14 char:34
+ ... t "End Date and Time: $($endDateObj.ToString("MM/dd/yyyy hh:mm tt"))"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
问题是您的乘法左侧有一个来自
Read-Host
的字符串,在 PowerShell 中,乘法 (*
) 运算符 将在左侧创建该字符串的副本按右侧的计数:
"2" * 10 # 2222222222
解决方案很简单,只需将整数放在前面,以便将右侧的字符串强制为整数并执行正常的算术运算:
10 * "2" # 20