首页 > 解决方案 > 在我的函数中使用 Switch 的问题

问题描述

我做了一个学习 PowerShell 的函数。 https://github.com/dcazman/MRNAP 如果有人想完整地看到它。

当我第一次制作这个函数时,它都是 If 语句。然后我了解到我可以在代码中使用开关,它可能会更好。也是为了学习。

我更改了代码并在其中添加了两个开关,但现在它无法正常工作。

我的问题是我认为当有人使用 -UTC 时会使用该开关,但在我看来,如果开关存在与否,我会“随机”得到不同的结果。这是代码的片段。

Switch ($UTC) {
            { $JustDate -and !$NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyy_MM_dd-") + ($ReportNameExt)); break }
            { $NoSeconds -and !$NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((get-date).ToUniversalTime().ToString("yyyy_MM_ddThhmm-") + ($ReportNameExt)); break }
            { !$NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyy_MM_ddThhmmss-") + ($ReportNameExt)); break }

            # Remove dash and underscores with NoSeperators switch.
            { $JustDate -and $NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyyMMdd") + ($ReportNameExt)); break }
            { $NoSeconds -and $NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((get-date).ToUniversalTime().ToString("yyyyMMddThhmm") + ($ReportNameExt)); break }
            { $NoSeperators } { $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyyMMddThhmmss") + ($ReportNameExt)); break }
        }

我的 $fullpath 填充不正确 MRNAP -UTC 不会始终创建具有通用时间的文件名。代码随机进入我的两个开关之一。

我不明白什么?我要回到 If 语句吗?

标签: powershell

解决方案


switch语句不是-语句的一对一替代品if

switch至少在 PowerShell 中,语句是简化的循环语句。您当前的switch声明可以重写为:

foreach($_ in $UTC){
  if($JustDate -and !$NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyy_MM_dd-") + ($ReportNameExt))
  }
  if($NoSeconds -and !$NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((get-date).ToUniversalTime().ToString("yyyy_MM_ddThhmm-") + ($ReportNameExt))
  }
  if(!$NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyy_MM_ddThhmmss-") + ($ReportNameExt))
  }
  if($JustDate -and $NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyyMMdd") + ($ReportNameExt))
  }
  if($NoSeconds -and $NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((get-date).ToUniversalTime().ToString("yyyyMMddThhmm") + ($ReportNameExt))
  }
  if($NoSeperators){
    $FullPath = Join-AnyPath $DirectoryName ((Get-Date).ToUniversalTime().ToString("yyyyMMddThhmmss") + ($ReportNameExt))
  }
}

将其作为循环重新阅读foreach,您可能会发现 的值没有$UTC任何区别

我希望这能解释:)


推荐阅读