Tarun
Tarun

Reputation: 11

I need to get certain values from a text file using powershell

I need to get the specific values like username (only numbers), owner name (after colon), and privileges from the text file which has similar kind of data:

Username: A044303                          Owner:  HUMARA_AZIZ_DA_201902
Account:  CORPACCT                         UIC:    [107,713] ([CORPACNT,A044303])
CLI:      DCL                              Tables: 
NETMBX    TMPMBX
Default Privileges: 
  NETMBX    TMPMBX

How can I do that using powershell commands ?

Upvotes: 1

Views: 371

Answers (2)

mklement0
mklement0

Reputation: 437100

You can use the following approach:

You can then directly access the resulting hashtable with property (key) names such as .Username (or ['Username']).

$htProps = [ordered] @{}
$i = 0; 
(Get-Content -Raw file.txt) -split '((?:Default )?\w+:)' -ne '' | ForEach-Object {
  if ($i++ % 2) { $htProps[$propName] = $(-split $_.Trim()) }  
  else          { $propName = $_ }
}

Outputting $htProps then yields the following ({...} indicates that a property contains an array of values):

Name                           Value
----                           -----
Username:                      A044303
Owner:                         HUMARA_AZIZ_DA_201902
Account:                       CORPACCT
UIC:                           {[107,713], ([CORPACNT,A044303])}
CLI:                           DCL
Tables:                        {NETMBX, TMPMBX}
Default Privileges:            {NETMBX, TMPMBX}

And $htProps.UserName, for instance, then returns A044303

Upvotes: 1

lylam
lylam

Reputation: 46

Try this

$test = "Username: A044303 Owner: HUMARA_AZIZ_DA_201902 Account: CORPACCT UIC: [107,713] ([CORPACNT,A044303]) CLI: DCL Tables: NETMBX TMPMBX Default Privileges: NETMBX TMPMBX"

if ($test -match "^Username: [a-zA-Z]([0-9]+) Owner: ([A-Z_]+[0-9]+)") {
   write-host "UserName: "$matches[1]
   write-host "Owner: "$matches[2]   
}

Upvotes: 0

Related Questions