powershell - If/ElseIf block 不适用于 -or

标签 powershell windows-10 powershell-ise powershell-5.0

我为我儿子写的脚本有问题。我的意图是简单地提醒他记住他的家务。我最近才开始做 PowerShell,我真的很喜欢它。我买了几本书,浏览了许多其他帖子。

到目前为止,我得到的是下面的内容,似乎评估是否无法使用 -or 正常工作(或者也许我搞砸了?)

    ## REMINDERS TO DO CHORES ##

$sun = "Sunday"
$mon = "Monday"
$tue = "Tuesday"
$wed = "Wednesday"
$thu = "Thursday"
$fri = "Friday"
$sat = "Saturday"

$today = (get-date).DayOfWeek

$choreVac = "Vacuum the rooms and stairs"
$choreBath = "Clean the Bathroom Including emptying the garbage"
$choreOther = "No Chores Today -- But keep dishes done up"


if($today -eq $mon -or $wed -or $fri) {
msg /time:2500 * "Today is a Chore Day:  your job is to $choreVac" 
}

elseif ($today -eq $tue -or $sat ) {
msg /time:2500 * "Today is a Chore Day: your job is to $choreBath and PLEASE do a good job"
}
else {
msg /time:2500 * $choreOther
}

问题是我不认为它在当天被正确评估,所以今天是星期二,评估结果是 $mon -or $wed -or $fri

如果我每天按如下方式重新编码,它会按预期工作。为什么它不适用于 -or

if($today -eq $tue) {
msg /time:2500 * $choreBath
}

最佳答案

就像您自己发现 PowerShell 没有评估您的 if 语句您希望它成为什么。你的表达可以像这样更好地理解:

if(($today -eq $mon) -or ($wed) -or ($fri))

正如在您的评论中,您想要的代码是

$today -eq $mon -or $today -eq $wed -or $today -eq $fri

或者换一种方式来看待它。

($today -eq $mon) -or ($today -eq $wed) -or ($today -eq $fri)

PowerShell 不需要括号,但如果事情不顺利,最好使用它们。

当 PowerShell 中的非空/零长度字符串被转换为 bool 值时为 true。关注第二个子句,它可以重写为

"Wednesday" -or "Friday"

总是 true。这就是为什么您的 if 语句在您没有预料到的时候被触发的原因。

您编写的代码具有一定的逻辑意义,但在句法上不正确。我想向您介绍的另一种方法是 switch,如果您还不熟悉的话。 .这将有助于减少所有 if 语句的困惑,并且如果它们随着杂务的发展而变得更加复杂,将会特别有用。

$today = (get-date).DayOfWeek

$choreVac = "Vacuum The Apt"
$choreBath = "Clean the Bathroom Including empting the garbage"
$choreOther = "NO CHORES TODAY -- BUT YOU CAN Keep dishes done up, and Keep Garbage from Overflowing AND CLEAN YOUR ROOM and OR Do Laundry!!!. Especially your bedding"

Switch ($today){
    {$_ -in 1,3,5}{$message = "Today is a Chore Day:  Your job is to`r$choreVac"}
    {$_ -in 2,6}{$message = "Today is a Chore Day:  Your job is to`r$choreBath and PLEASE do a good job"}
    default{$message = $choreOther}
}

msg /time:2500 * $message

我们将对 msg 的所有调用都删除到一个语句中,因为只有 $message 发生了变化。如果杂务日没有包含在开关中的子句,那么默认值只是 $choreOther

星期几也可以表示为整数,就像您在上面看到的那样。这可能会降低代码的可读性,但我认为这是一种延伸。

关于powershell - If/ElseIf block 不适用于 -or,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084671/

相关文章:

docker - docker在Windows 10的Asp.Net Core中以代码126(0x7E)退出

visual-studio-code - wsl 的代码路径是什么,因此 Vscode 安装在用户配置文件中

android - Unity Android 构建错误 : > Illegal char <? > 在索引 7 : . .\..\l?brary_man?fest\release\AndroidManifest.xml

powershell - PowerShell ISE:如何运行新的PowerShell版本

powershell - Powershell脚本可以保存VirtualBox VM的状态,但每次都会出错

powershell - 登录后 Azure 凭据不可用

powershell - 注册表 `registry::` 的 PSPath - 为什么是双冒号?

arrays - 平均阵列Powershell的一部分

windows - 我们如何在 Powershell 中的 HttpClient 对象上添加 DefaultRequestVersion?

PowerShell ISE 如何使用 ScriptBlock 关闭自动创建新选项卡?