Reputation: 13
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
+ 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?
Upvotes: 1
Views: 87
Reputation: 121699
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]
).
Upvotes: 0