powershell - 为什么日期时间对象之间的比较会导致 powershell 崩溃?
问题描述
我正在尝试编写一个简单的脚本,让用户从 5 个选项中进行选择,以编写一些文本或运行一些基本命令。出于某种原因,当我选择选项 1 时程序崩溃。
Write-Output " "
Write-Output "Hello. I am the Augur of Dunlain. I know many things. Ask, that which you do not yet know:"
sleep 2
Write-Output "1. How many more days until Christmas?"
Write-Output "2. What processes are running on my computer?"
Write-Output "3. What is System32?"
Write-Output "4. Why are the Blades saying that I have to kill Parthunaax?"
Write-Output "5. What is my age?"
$choice = Read-Host -Prompt "Choose options 1, 2, 3, 4, or 5"
If ($choice -eq "1"){
$currentDate = Get-Date
$christmas = Get-Date "12/25/2021"
$timeSpan = New-Timespan -Start $currentDate -End $christmas
if(timeSpan.days -gt 0){
Write-Output "There are " + $timeSpan.Days + " days left until Christmas."
sleep 3
}
else {
Write-Output "It is Christmas today! Merry Christmas!"
sleep 3
}
}
elseif ($choice -eq "2"){
$processes = Get-Process
Write-Output $processes
sleep 25
}
elseif ($choice -eq "3"){
Write-Output "System 32 is the collection of the following files and directories:"
$system32 = Get-ChildItem -Path C:\Windows\System32
Write-Output $system32
sleep 25
}
elseif ($choice -eq "4"){
Write-Output "They are intollerant, plain and simple. Parthunaax is a total G, so if the Blades are telling you to kill him you can tell them that they are stinky nerds and you don't want to play with them any more."
}
elseif ($choice -eq "5"){
}
else {
Write-Output "Looks like you have failed the simple task of selecting a number 1 through 5. I figured a monkey would have been capable of doing that but I guess you're inferior to the monkey. Try again but this time be better."
}
解决方案
根据问题的当前版本,您在 If(timeSpan.days) 中缺少 $ 应该是 If($timeSpan.days) 并且在写入输出中不要尝试添加字符串,只需使用 PowerShell 字符串扩展,如图所示.
If ($choice -eq "1"){
$currentDate = Get-Date
$christmas = Get-Date "12/25/2021"
$timeSpan = New-Timespan -Start $currentDate -End $christmas
if($timeSpan.days -gt 0){
Write-Output "There are $($timeSpan.Days) days left until Christmas."
sleep 3
}
样本输出:
Choose options 1, 2, 3, 4, or 5: 1
There are 150 days left until Christmas.
高温高压
推荐阅读
- jenkins - Jenkins 高级下拉参数
- highcharts - 提升面积图使其看起来像条形图
- javascript - d3 js onclicknode函数只返回id元素
- html - TinyMCE 使用“粘贴”插件将 alpha 列表转换为复制/粘贴时的编号列表
- typescript - 打字稿不能根据可选属性缩小联合
- javascript - 如何更新reactjs中的对象数组
- javascript - MS Edge api 错误“未定义浏览器”
- multithreading - 用户空间调度困境中的线程
- java - 从源代码自动生成 Java .class 文件的最安全方法,独立于构建环境
- git - git history 是否会破坏使用 OpenSSL 加密的文件?