1

I extract some data from my computer and it creates either a variable or I've written it to a .txt file. The output looks like this:

RVR7RYR

RVR7RYR

I I only need the first 7 characters so I wrote this:

$line = get-content "c:\temp\file.txt"
$var = $line
$result = $var.SubString($var.length - 7, 7)
$result

It gives me this error:

Exception calling "Substring" with "2" argument(s): "StartIndex cannot be less than zero. Parameter name: startIndex" At line:5 char:1

  • $result = $var.SubString($var.length - 7, 7)
  •   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentOutOfRangeException
    
    
    

my file does have spaces inbetween the values and even after the second value, not sure if that matters.

how do I get just the first 7 characters?

3
  • 1) First (as a debugging method), echo "$var" and $var.length" to make sure they're really what you think they are. 2) Q: Why not simply $result = $var.SubString(0, 7)? Commented Nov 29, 2021 at 18:08
  • Hello. when I echo "$var" it shows me both occurrences of the string. When I run "$result = $var.SubString(0,7) I get the exact same error as shown above. Commented Nov 29, 2021 at 18:13
  • Thank you for trying; sorry it didn't help. Let me try to reproduce the problem myself. Commented Nov 29, 2021 at 19:08

1 Answer 1

0

The problem was that you were inadvertently reading an ARRAY, not just a single text string.

.ps1:

$line = get-content "c:\temp\file.txt" 
echo "line: " $line ", line.length: " $line.length ", line[0].length: " $line[0].length
$result = $line[0].SubString(0, 7)
echo "result: " $result

Sample output:

line:
RVR7RYR

RVR7RYR

cow pig chicken goat
, line.length:
5
, line[0].length:
7
result:
RVR7RYR

In other words, you want to take the first 7 characters of the first line ($line[0]).

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.