我需要检查 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/