Home > other >  Identify position of a word in a line stored in a variable using Powershell
Identify position of a word in a line stored in a variable using Powershell

Time:07-11

I have a text file which is stored in a variable say $RC. It looks like below.

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :        49        10         0         0         0         0
   Files :       212       170        37         0         5         2
   Bytes :   6.517 t   6.517 t    24.5 k         0  136.37 m       550

When I run

$RC | Measure-Object -Word -character -Line

it gives me the output as

Lines Words Characters Property
----- ----- ---------- --------
    4    34        280         

if I run $RC[1], it gives me the first line as:-

Dirs :        39         9         0         0         0         0

Now I want to navigate to 7th word in this above line (which is 0), how do I do that?

If that's not possible, my ultimate goal is to find values under Failed column (which are 0,5,136.37) in above text file and store them in another variable for comparison. How can it be done? Thank you in advance.

CodePudding user response:

In case you don't want tot reinvent the wheel; using this ConvertFrom-SourceTable cmdlet:

$RC = '
               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :        49        10         0         0         0         0
   Files :       212       170        37         0         5         2
   Bytes :   6.517 t   6.517 t    24.5 k         0  136.37 m       550'

$Data = ConvertFrom-SourceTable -Literal $RC
$Data |Format-Table

Total             Copied  Skipped Mismatch FAILED   Extras
-----             ------  ------- -------- ------   ------
Dirs :        49  10      0       0        0        0
Files :       212 170     37      0        5        2
Bytes :   6.517 t 6.517 t 24.5 k  0        136.37 m 550

Taking the first -zero based ([0])- row and column Extras:

$Data[0].Extras
0

and taking the whole failed column using Member-Access Enumeration:

$Data.Failed
0
5
136.37 m
  • Related