Search code examples
powershelltext-parsing

How to read specific line value with argument using PowerShell?


I have a file with this format.

English
Name
    Gerry
Class
    Elementry
ID Number
    0812RX
Gender
    *Male
     Female
Address
     St.Joseph Rd.78
Member Name
     Jack

The structure of this file is, the value of Name, there is one enter and one tab and then the value Gerry

I want to read the value of the each item. I tried this code.

Param(
  [parameter(mandatory=$true)][string]$FilePath, $Key
)

$FileContent = Get-Content $FilePath | Where-Object{"^($Key)","`$1$Value"}
$FileContent

My expectation, when I execute this command

powershell.ps1 -FilePath file.txt -Key Name

It will return : Gerry

Please, anyone give me idea. Thanks


Solution

  • The best option is to use the switch statement with the -File parameter:

    $found = $false
    $value = switch -File file.txt {
      'Name' { $found = $true }
      default { if ($found) { $_.Substring(1); break } }
    }
    

    With your sample input, $value should then contain Gerry.

    $found is set to $true once 'Name' is found on a line of its own; in the default block, which is executed for all other line, the following line is then returned, stripped of its initial (tab) char.

    Wrapped in a script with parameters, simulated here with a script block for brevity:

    # Create a sample file; "`t" creates a tab char.
    @"
    Name
    `tGerry
    Class
    `tElementary
    ID Number
    `t0812RX
    "@ > file.txt
    
    # Script block that simulates a script file.
    & {
    
      param(
        [Parameter(Mandatory)] [string] $FilePath,
        [Parameter(Mandatory)] [string] $Key
      )
    
      $found = $false
      switch -File $FilePath { 
        $Key { $found = $true }
        default { if ($found) { return $_.Substring(1) } }
      }
    
    } -FilePath file.txt -Key Name
    

    The above yields Gerry.

    Note that if your key name has spaces, you must pass it quoted to the script; e.g.:

    ... -FilePath file.txt  -Key 'ID Number'