powershell - 检查文件是否为空

标签 powershell

我需要检查 PowerShell 2.0 和 5.0 版本中的文件 "file.txt" 是否为空。我在这里面临的问题是 PowerShell 5.0 中使用的命令 let 在 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

这个问题有解决办法吗?

最佳答案

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

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

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

使用[IO.File]::ReadAllLines($file)的原因是,在我的测试中,读取时它比Get-Content快大约10倍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

获取内容方法:

$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

关于powershell - 检查文件是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634415/

相关文章:

AZ 存储 Blob 上的 Azure CLI IF 存在结果

powershell - 如何从Docker传递参数给 “find”?

powershell - 通过 Powershell 获取子 OU

Powershell查找并替换注册表值?

regex - 如何制作正则表达式以排除带括号的字符串

powershell - 在 SharePoint 中获取 "Shared with Everyone"文件夹信息

javascript - Clockify 中的登录表单

PowerShell ErrorRecord.CategoryInfo.Activity (CategoryActivity)

powershell - 检查目录是否存在(如果不执行任何操作)

powershell - 为什么 PowerShell 使用双冒号 (::) 来调用 .NET 类的静态方法?