powershell - 在我的函数中使用 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 语句吗?
解决方案
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
任何区别!
我希望这能解释:)
推荐阅读
- azure - 带有布尔值的 SCIM 问题的 Azure 用户/组预配
- angular - 如何在选定的列表项上添加 CSS 类
- javascript - 目前业界最常用的发送 HTTP 请求的方式是什么(AJAX、Fetch API、Async/Await)?
- javascript - 如何通过淘汰赛实现 CSS 星级评分
- reactjs - 如果我在 React 中只有一个 Provider,如何跨多个上下文访问状态?
- unix - 内核驱动程序如何与另一个设备通信?
- android - 如何从 EditActivity 中删除房间条目?
- amazon-web-services - AWS ElastiCache Redis-如何在集群重启时使用最近的每日备份(只有 1 个节点,没有多可用区)
- css - 从 Typescript Angular 获取 CSS 参数
- javascript - 如何使用 jquery 在 div 中显示多选值?