Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get-Content returns array or string

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!

like image 293
Adamarla Avatar asked Oct 19 '25 05:10

Adamarla


1 Answers

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 powershell-2.0, 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
like image 122
Santiago Squarzon Avatar answered Oct 22 '25 04:10

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!