4

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!

3
  • 4
    This is why .Count is awesome! Commented Feb 3, 2022 at 22:44
  • 5
    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. Commented Feb 3, 2022 at 22:57
  • 2
    For background information on why PowerShell behaves this way, see this answer. Commented Feb 3, 2022 at 23:18

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.