检查文件是否为空

时间:2019-06-17 15:27:12

标签: powershell

我需要检查在PowerShell版本2.0和5.0中文件"file.txt"是否为空。我在这里面临的问题是在PowerShell 5.0中使用的命令在PowerShell 2.0中无法使用

(Get-Content -Path .\file.txt).length -eq $Null)-即使文件在PowerShell 5.0中为空,也返回false,但在PowerShell 2.0中它返回true。

(Get-Content -Path .\file.txt).length -eq 0)-在PowerShell 5.0中返回true,但在PowerShell 2.0中返回false

这个问题有解决方案吗?

2 个答案:

答案 0 :(得分:1)

我相信这应该可行。

if (Get-Content .\File.txt){$true}else{$false}

在PS 2.0中,我认为(Get-Content -Path .\file.txt).Length不会返回任何内容。您将必须使用Get-Content -Path .\file.txt | select -ExpandProperty Length

但是出于您的目的,您甚至不需要查看文件的length,只需查看内容即可。

答案 1 :(得分:0)

这是我写的一个函数来检查这个。

它使用 .NET 读取所有文本,并且还有一个匹配项 \S,它匹配除空格之外的任何内容,该空格基本上忽略任何空格并搜索其他所有内容。

这意味着文件中可以有空格,该函数将返回 $true,因为它不包含任何文本。

使用 [IO.File]::ReadAllLines($file) 的原因是,在我的测试中,它在读取 100k 行时比 Get-Content 快 10 倍左右。

如果性能是一个问题,那么这是我会使用的,否则使用底部的 Get-Content 方法代码。

.NET 方法:

$fileToCheck = "$PSScriptRoot\Test-FileEmpty.ps1"

Function Test-FileEmpty {

  Param ([Parameter(Mandatory = $true)][string]$file)

  if ((Test-Path -LiteralPath $file) -and !(([IO.File]::ReadAllText($file)) -match '\S')) {return $true} else {return $false}

}

Test-FileEmpty $fileToCheck

Get-Content 方法:

$fileToCheck = "$PSScriptRoot\Test-FileEmpty.ps1"

Function Test-FileEmpty {

  Param ([Parameter(Mandatory = $true)][string]$file)

  if ((Test-Path -LiteralPath $file) -and !((Get-Content -LiteralPath $file -Raw) -match '\S')) {return $true} else {return $false}

}

Test-FileEmpty $fileToCheck