3

I am trying to check the beginning of the first 2 lines of a text file.

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

This works fine except if the file has only 1 line. Then it seems to return a string rather than an array of strings, so the indexing pulls out a character, not a string.

Error if file has only 1 line: Method invocation failed because [System.Char] doesn't contain a method named 'StartsWith'.

How can I detect if there are too few lines? $ascii.Length is no help as it returns the number of characters if there is only one line!

Adamarla
  • 739
  • 9
  • 20
  • 3
    This is why `.Count` is awesome! – Santiago Squarzon Feb 03 '22 at 22:44
  • 4
    you can force `G-C` to always give you an array - even with just one line - by enclosing the call in `@()`. then you can use the `.Count` property to decide if you otta try for the 2nd line. – Lee_Dailey Feb 03 '22 at 22:57
  • 2
    For background information on why PowerShell behaves this way, see [this answer](https://stackoverflow.com/a/60020105/45375). – mklement0 Feb 03 '22 at 23:18

1 Answers1

3

From 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.

I see you have tagged your question with , if you're actually running this version of PowerShell, you would need to use the Array subexpression operator @( ) or type cast [array] for below example on how you can approach the problem at hand:

$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
}

For PowerShell 2.0, the first line should be either:

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

Or

# [object[]] => Should also work here
[array]$ascii = Get-Content -LiteralPath $path -Encoding ascii -TotalCount 2
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37