Get-Content returns 数组或字符串

Get-Content returns array or string

我正在尝试检查文本文件前两行的开头。

$ascii = Get-Content -LiteralPath $path -Encoding ascii -TotalCount 2
if ($ascii[0].StartsWith("aa")) {}
if ($ascii[1].StartsWith("bb")) {}

除非文件只有 1 行,否则这工作正常。 然后它似乎 return 一个字符串而不是一个字符串数组,所以索引拉出一个字符,而不是一个字符串。

如果文件只有 1 行则出错: Method invocation failed because [System.Char] doesn't contain a method named 'StartsWith'.

如何检测行数是否太少? $ascii.Length 没有帮助,因为如果只有一行,它 return 是字符数!

来自about_Arrays

Beginning in Windows PowerShell 3.0, a collection of zero or one object has the Count and Length property. Also, you can index into an array of one object. This feature helps you to avoid scripting errors that occur when a command that expects a collection gets fewer than two items.

我看到你已经用 , if you're actually running this version of PowerShell, you would need to use the Array subexpression operator @( ) 标记了你的问题,或者在下面的例子中输入 cast [array] 来说明你如何解决手头的问题:

$ascii = Get-Content -LiteralPath $path -Encoding ascii -TotalCount 2

if($ascii.Count -gt 1) {
    # This is 2 lines, your original code can go here
}
else {
    # This is a single string, you can use a different approach here
}

对于 PowerShell 2.0,第一行应该是:

$ascii = @(Get-Content -LiteralPath $path -Encoding ascii -TotalCount 2)

# [object[]] => Should also work here
[array]$ascii = Get-Content -LiteralPath $path -Encoding ascii -TotalCount 2