Reputation: 11
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
Reputation: 437100
You can use the following approach:
-split
, the string splitting operator, to split the content into an array in which property names and their values alternate.ForEach-Object
to fill an (ordered) hash table.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
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