Cooluser
Cooluser

Reputation: 11

Retrieve text from a file in ps script

I have a text file containing some data as follows:

test|wdthe$muce

check|muce6um#%

How can I check for a particular string like test and retrieve the text after the | symbol to a variable in a PowerShell script? And also, If Suppose there is variable [email protected] and how to search the file by splitting the text before "@" ?

Upvotes: 0

Views: 214

Answers (3)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

gc input.txt |? {$_ -match '^test'} |% { $_.split('|') | select -Index 1 }

or

sls '^test' -Path input.txt |% { $_.Line.Split('|') | select -Index 1 }

or 

sls '^test' input.txt |% { $_ -split '\|' | select -Ind 1 }

or

(gc input.txt).Where{$_ -match '^test'} -replace '.*\|'

or

# Borrowing @Anthony Stringer's answer shape, but different 
# code, and guessing names for what you're doing:

$users = @{}
Get-Content .\input.txt | ForEach { 
    if ($_ -match "(?<user>.*)\|(?<pwd>.*)") {
        $users[$matches.user]=$matches.pwd 
    }
}
$users = [pscustomobject]$users

Upvotes: 0

Anthony Stringer
Anthony Stringer

Reputation: 2001

this may be one possible solution

$filecontents = @'
test|wdthe$muce

check|muce6um#%
'@.split("`n")

# instead of the above, you would use this with the path of the file
# $filecontents = get-content 'c:\temp\file.txt'

$hash = @{}
$filecontents | ? {$_ -notmatch '^(?:\s+)?$'} | % {
    $split = $_.Split('|')
    $hash.Add($split[0], $split[1])
}
$result = [pscustomobject]$hash

$result

# and to get just what is inside 'test'
$result.test

*note: this may only work if there is only one of each line in the file. if you get an error, try this other method

$search = 'test'
$filecontents | ? {$_ -match "^$search\|"} | % {
    $_.split('|')[1]
}

Upvotes: 1

Christopher Langevin
Christopher Langevin

Reputation: 76

First you need to read the text from the file.

$content = Get-Content "c:\temp\myfile.txt"

Then you want to grab the post-pipe portion of each matching line.

$postPipePortion = $content | Foreach-Object {$_.Substring($_.IndexOf("|") + 1)}

And because it's PowerShell you could also daisy-chain it together instead of using variables:

Get-Content "C:\temp\myfile.txt" | Foreach-Object {$_.Substring($_.IndexOf("|") + 1)}

The above assumes that you happen to know every line will include a | character. If this is not the case, you need to select out only the lines that do have the character, like this:

Get-Content "C:\temp\myfile.txt" | Select-String "|" | Foreach-Object {$_.Line.Substring($_.Line.IndexOf("|") + 1)}

(You need to use the $_.Line instead of just $_ now because Select-String returns MatchInfo objects rather than strings.)

Hope that helps. Good luck.

Upvotes: 0

Related Questions