34

我被一个看似简单的问题难住了。很抱歉这里有任何愚蠢的行为。

我有清理失效备份文件的脚本。在识别出文件后,我循环并打印出正在转储的内容。当失效文件为零时,我的问题是试图提供反馈/测试。剧本看起来...

$Files = Get-ChildItem $BackupPath_Root -include *.bak -recurse 
           | where {$_.CreationTime  -le $DelDate_Backup }  

if ( $Files -eq "" -or $Files.Count  -eq 0 ) {
    write-host "   no files to delete."    #<-- this doesn't print when no files
} else {
   foreach ($File in $Files) {
      write-host “$File” 
      Remove-Item $File | out-null
   } 
}

if 检查无文件不会捕获无文件条件。什么是测试$Files没有结果的适当方法?

4

5 回答 5

59

尝试包裹在@(..). 它总是创建一个数组:

$Files = @(Get-ChildItem $BackupPath_Root -include *.bak -recurse 
           | where {$_.CreationTime  -le $DelDate_Backup })
if ($Files.length -eq 0) {
  write-host "   no files to delete." 
} else {
  ..
}
于 2011-07-28T13:56:32.517 回答
16

当没有文件时,$Files 等于 $null,因此 EBGreen 建议您应该针对 $null 进行测试。此外, $Files.Count 仅在结果是文件集合时才有用。如果结果是一个标量(一个对象),它将没有计数属性并且比较失败。

性能提示:当您只需要搜索一种扩展类型时,请使用 -Filter 参数(而不是 -Include),因为它在提供程序级别进行过滤。

于 2011-07-28T13:57:35.283 回答
9

当扫描的文件夹为空时,该变量的计算结果为空值表达式。您可以使用:

if (!$Files) {
# ...
}
于 2011-07-28T14:21:12.650 回答
4

也尝试测试 $files -eq $null 。

于 2011-07-28T13:49:41.113 回答
2

在 get-childitem 命令前面指定 [bool] 类型将在找到任何内容时返回 True,如果没有找到则返回 false。这就是埃米利亚诺的回答正在做的事情,但没有否定的要求。您可以使任何一项工作,但我更喜欢 [bool] 使用一些更复杂的条件语句,以便更容易理解。

[bool](Get-ChildItem C:\foo.txt)

在 If 语句中使用

if ([bool](Get-ChildItem C:\foo.txt)) {write-output "foo.txt exists"}
于 2018-02-21T17:36:49.223 回答