首页 > 解决方案 > PowerShell While循环多个条件不起作用

问题描述

想在一个while循环中检查多个条件,但它们不起作用。

#Debug
if ($DatumArray -notcontains $DatumAktuellerFeiertag) {echo "true"} else {echo "false"}
if ($TagAktuellerFeiertag -ne "Samstag") {echo "true"} else {echo "false"}
if ($TagAktuellerFeiertag -ne "Sonntag") {echo "true"} else {echo "false"}

上面的代码给出了以下结果:

真的
错误的
真的

请注意,其中一个结果是“假”。

while (($DatumArray -notcontains $DatumAktuellerFeiertag) -and ($TagAktuellerFeiertag -ne "Samstag") -and ($TagAktuellerFeiertag -ne "Sonntag")) {
    # some code...
}

不执行循环,即使结果之一是“假”。

归档我的目标的可能方法是什么?为什么这个while循环不起作用?

编辑:

这不像预期的那样工作,因为我认为你不知道我的情况。所以我将尝试解释:

得到一个带有公共假期的数组$DatumArray(01.01.2019、19.04.2019、21.04.2019 像这样......)。

$DatumAktuellerFeiertag是实际的公共假期日期。

$TagAktuellerFeiertag是实际的公共假期工作日。

现在我正在尝试确定下一个工作日(但如果下一个工作日也是公共假期,则必须考虑这一点)。

所以我的情况是这样的:当有公共假期或周六或周日时,加$DatumAktuellerFeiertag1。

while (($DatumArray -notcontains $DatumAktuellerFeiertag) -and (($TagAktuellerFeiertag -ne "Samstag") -or ($TagAktuellerFeiertag -ne "Sonntag"))) {
    $DatumAktuellerFeiertag = (Get-Date $DatumAktuellerFeiertag).AddDays(1).ToString("dd/MM/yyy")
    $TagAktuellerFeiertag = (Get-Date $DatumAktuellerFeiertag -Format "dddd")

    echo $DatumAktuellerFeiertag
}

编辑:

试过你的版本,在“正常”的日子里完美无瑕,但在公共假期给了我无尽的循环。

$ListPublicHoliday = Import-Csv 'datum.csv'

$DateArray = $ListPublicHoliday.Datum
$DateArray = $DateArray | ForEach-Object { (Get-Date $_).Date }

$ActuallyDay = Get-Date 19.04.2019

while (($DateArray -contains $ActuallyDay.Date) -or ('Samstag', 'Sonntag' -contains $ActuallyDay.DayOfWeek)) {
    $ActuallyDay.AddDays(1)
}

我的 CSV:

#TYPE Selected.System.String
"基准","Feiertag","Wochentag","值"
"01.01.2019","Neujahrstag","Dienstag","01.01.2019 18:33:01"
"19.04.2019","Karfreitag","Freitag","19.04.2019 18:33:01"
"21.04.2019","Ostersonntag","Sonntag","21.04.2019 18:33:01"

PS:你能解释一下吗?(Get-Date $_).Date? 我在 Microsoft 文档上没有找到这个。

标签: powershell

解决方案


不执行循环,即使结果之一是“假”。[...] 为什么这个while循环不起作用?

循环不起作用,因为其中一个结果是$false. 您的条件由 3 个与-and运算符连接的子句组成,这意味着所有子句都必须评估为$true才能使循环运行。但是,由于您的第 2 条和第 3 条是互斥的,这永远不会发生。

我不太确定您的条件应该是什么样子,但至少您需要条件是A && (B || C)而不是A && B && C.

改变这个:

while (($DatumArray -notcontains $DatumAktuellerFeiertag) -and ($TagAktuellerFeiertag -ne "Samstag") -and ($TagAktuellerFeiertag -ne "Sonntag")) {
    # some code...
}

进入这个:

while (($DatumArray -notcontains $DatumAktuellerFeiertag) -and (($TagAktuellerFeiertag -ne "Samstag") -or ($TagAktuellerFeiertag -ne "Sonntag"))) {
    # some code...
}

编辑:

在你更新你的问题,澄清你真正想要完成的事情之后,你的条款确实应该与-or运营商联系起来,正如 Mathias 在评论中所怀疑的那样。但是,子句中的运算符不得在此之上否定(您需要-containsand-eq而不是-notcontainsand -ne)。$DatumArray此外,如果包含DateTime对象而不是字符串,您的代码会变得更加简单。两个工作日的比较也可以合二为一。

像这样的东西应该工作:

$DatumArray = $DatumArray | ForEach-Object { (Get-Date $_).Date }

$startDate = ...
$cur = Get-Date $startDate
while (($DatumArray -contains $cur.Date) -or ('Samstag', 'Sonntag' -contains $cur.DayOfWeek)) {
    $cur = $cur.AddDays(1)
}

推荐阅读