If the token of interest is the 161st word in the file, use the following approach, which splits the file into words irrespective of line breaks[1]:
$pass = (-split (Get-Content -Raw Word_File.txt))[160]
Append .ToLower()
if you want to convert the token to all-lowercase.
Note that the above loads the entire file into memory as a single string, using -Raw
.
Since array indices are 0
-based, it is index [160]
that returns the 161st element.
The unary form of the -split
operator splits the input into an array of tokens by whitespace.
- Note: If you want to split by the stricter definition of what constitutes a word in a regular-expression context, use the following instead:
$pass = ((Get-Content -Raw Word_File.txt) -split '\W+' -ne '')[160]
[1] If your input file contains each word on its own line:
Your solution was on the right track, except that you should pass 160
to Select-Object -Index
, because the -Index
parameter expects 0
-based indices, not 1
-based line numbers:
# Extract the 161st line.
$pass = Get-Content Word_File.txt | Select-Object -Index 160
To convert to lowercase:
$pass = (Get-Content Word_File.txt | Select-Object -Index 160).ToLower()
The above will fail if the input file has fewer than 161 lines (with error message You cannot call a method on a null-valued expression
).
If you prefer to receive no output quietly instead, use the following (which uses built-in aliases select
for Select-Object
and foreach
for ForEach-Object
for brevity):
$pass = Get-Content Word_File.txt | select -Index 160 | foreach ToLower