PowerShell如何仅编写一次条件判断即可应用于多条命令执行
PowerShell 重复条件判断优化方案
方案1:合并同条件代码块(当前场景最优)
直接把所有需要满足条件才执行的命令放到同一个if代码块内,仅触发一次判断即可执行所有内部命令:
If ((Get-ChildItem -Force "C:\Document" -ErrorAction SilentlyContinue) -eq $Null) { Move-Item -Path "C:\new1\*" -Destination "C:\Document_test" -Force -Verbose Move-Item -Path "C:\new2\*" -Destination "C:\Document_test" -Force -Verbose }
新增的-ErrorAction SilentlyContinue参数可以避免C:\Document路径不存在时抛出异常,同时路径不存在时判断结果也会为真,兼容目录不存在的场景。
方案2:预存判断结果实现多位置复用
如果满足条件的命令需要分散在代码不同位置执行,可以先把判断结果存入布尔变量,后续直接调用变量即可,无需重复执行Get-ChildItem查询:
# 仅执行一次查询,存储判断结果 $isDocumentEmpty = (Get-ChildItem -Force "C:\Document" -ErrorAction SilentlyContinue) -eq $Null # 位置1调用 if ($isDocumentEmpty) { Move-Item -Path "C:\new1\*" -Destination "C:\Document_test" -Force -Verbose } # 中间可插入其他无关逻辑 # ... # 位置2调用 if ($isDocumentEmpty) { Move-Item -Path "C:\new2\*" -Destination "C:\Document_test" -Force -Verbose }
方案3:封装为函数(适合跨脚本高频复用)
如果该判断逻辑需要在多个脚本中重复使用,可以封装为独立函数,调用更简洁:
# 定义复用判断函数 function Test-DocumentFolderIsEmpty { return (Get-ChildItem -Force "C:\Document" -ErrorAction SilentlyContinue) -eq $Null } # 调用示例 if (Test-DocumentFolderIsEmpty) { Move-Item -Path "C:\new1\*" -Destination "C:\Document_test" -Force -Verbose Move-Item -Path "C:\new2\*" -Destination "C:\Document_test" -Force -Verbose }
内容的提问来源于stack exchange,提问作者Shahpari
相关产品推荐
相关产品推荐

