How to find specific string, with certain starting and ending character in Powershell - powershell

how to find all the strings which starts with open square bracket and ends with close square bracket in text file.
used below code but getting some unwanted contents also. How to avoid those unwanted contents
Select-String -Path "text.txt" -Pattern '\['
input file:
some conents [hello]
adfhjadf adfjkkf [ghad]
[check] dfgsf sfgfs
required output file
[hello]
[ghad]
[check]

Here, try this:
$string = #'
some conents [hello]
adfhjadf adfjkkf [ghad]
[check] dfgsf sfgfs
'#
([regex]'\[.*?\]').Matches($string)
Note, this will match anything inside the brackets. If you're looking only for English characters you should refine the regex.
Output should look like this:
Groups : {0}
Success : True
Name : 0
Captures : {0}
Index : 13
Length : 7
Value : [hello]
Groups : {0}
Success : True
Name : 0
Captures : {0}
Index : 39
Length : 6
Value : [ghad]
Groups : {0}
Success : True
Name : 0
Captures : {0}
Index : 47
Length : 7
Value : [check]
If you just want to see the matches you can do:
PS /> ([regex]'\[.*?\]').Matches($string).Value
[hello]
[ghad]
[check]

Related

Using FromArgb for Int32[] value results in swapped Red and Blue values

I have this Int32[] value 14508153 which should be:
R : 121
G : 96
B : 221
If I use:
[System.Drawing.Color]::FromArgb(14508153)
It returns:
R : 221
G : 96
B : 121
A : 0
IsKnownColor : False
IsEmpty : False
IsNamedColor : False
IsSystemColor : False
Name : dd6079
Questions
How or why are those values swapped for R and B using that function?
Is there a built-in PowerShell method to convert them correctly?
I can't speak to why the bytes need to be rearranged (see the bottom section for thoughts), but here's how you can do it:
Add-Type -AssemblyName System.Drawing
$bytes = [System.BitConverter]::GetBytes(14508153)
[byte[]] $rearrangedBytes = $bytes[2], $bytes[1], $bytes[0], $bytes[3]
[System.Drawing.Color]::FromArgb(
[System.BitConverter]::ToInt32($rearrangedBytes, 0)
)
See System.BitConverter.GetBytes(), System.BitConverter.ToInt32().
The above yields:
R : 121
G : 96
B : 221
A : 0
IsKnownColor : False
IsEmpty : False
IsNamedColor : False
IsSystemColor : False
Name : 7960dd
It appears that only 3 of the bytes in your [int] (System.Int32) value are relevant, and that they are in Big-Endian order (see the Wikipedia article about endianness).
By contrast, System.Drawing.Color.FromArgb() expects all 4 bytes to be relevant, in Little-Endian order.

Read in a *HUGE* CSV file, export specific columns based on column name in header, output comma delimited data

So, I know I can read in a csv file using import-csv like so:
$test = import-csv BPUSAUV20FARS-1000.csv
I found another stack overflow question which gave me some code to decipher column names, like so:
$columns = $test[0].psobject.properties.name
I found a reddit post that helped me find a way to extract multiple columns using select-object like so:
$properties = #('Index', 'Year', 'Day', 'Time', 'Line', 'Beam', 'Pos TPU', 'Depth TPU', 'Status')
$test |Select-Object $properties
But the output from the above command likes like this:
Index : 1
Year : EM2040-0073-1000-20200224-222235
Day : 25
Time : Accept
Line : 0.648
Beam : 24-FEB-2020:22:22:34.98
Pos TPU : 4.617
Depth TPU : 1124834.70
Status : 10247261.01
Index : 2
Year : EM2040-0073-1000-20200224-222235
Day : 26
Time : Accept
Line : 0.749
Beam : 24-FEB-2020:22:22:34.98
Pos TPU : 4.617
Depth TPU : 1124834.73
Status : 10247261.76
Index : 3
Year : EM2040-0073-1000-20200224-222235
Day : 27
Time : Accept
Line : 0.624
Beam : 24-FEB-2020:22:22:34.98
Pos TPU : 4.617
Depth TPU : 1124834.76
Status : 10247263.05
And what I need is this:
1,EM2040-0073-1000-20200224-222235,25,Accept,0.648,24-FEB-2020:22:22:34.98,4.617,1124834.70,10247261.01
I also need to be able to perform these actions on a few hundred files with several million lines each. The smallest file is about 2.4 million lines.
As for...
I also need to be able to perform these actions on a few hundred files
with several million lines each. The smallest file is about 2.4
million lines.
... dealing with large files in general --- (too long for just a comment)
As per MSDN
[IO.File]::OpenText and as noted in another Q&A
The Get-Content cmdlet does not perform as well as a StreamReader when
dealing with very large files. You can read a file line by line using
a StreamReader like this:
$path = 'C:\A-Very-Large-File.txt'
$r = [IO.File]::OpenText($path)
while ($r.Peek() -ge 0) {
$line = $r.ReadLine()
# Process $line here...
}
$r.Dispose()
Some performance comparisons:
Measure-Command {Get-Content .\512MB.txt > $null}
Total Seconds: 49.4742533
Measure-Command {
$r = [IO.File]::OpenText('512MB.txt')
while ($r.Peek() -ge 0) {
$r.ReadLine() > $null
}
$r.Dispose()
}
Total Seconds: 27.666803

print strings and variables in powershell for loop

I need to extract an alerts from rest api and sent it to a file with powershell
I was able to extract the alerts outputs looping the xml file:
foreach ($c in $temp){$c.timeOfAlertFormatted,$c.parent,$c.child,$c.category,$c.servicePlanDisplayName,$c.message}
Thu 09/19/2019 12:00:19 AM
IL
Servername
Phase Failure
Gold
One or more source luns do not have a remote target specified/mapped.
Wed 09/18/2019 02:18:25 PM
IL
Server2
Phase Failure
Gold
One or more source luns do not have a remote target specified/mapped
I am new to PS , what i want to achieve is to add descriptive string
to each filed, i.e:
Time: Thu 09/19/2019 12:00:19 AM
Country: IL
Server: servername
etc ,the rest of the fields.
i tried :
foreach ($c in $temp){Write-Host "Time : $($c.timeOfAlertFormatted)"}
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time :
Time : Thu 09/19/2019 12:00:19 AM
its printing empty "Time" fields
here is example of the xml:
It looks like you have already loaded the xml and filtered out the properties you need in a variable $temp.
I think what you want can be achieved by doing:
$temp | Select-Object #{Name = 'Time'; Expression = {$_.timeOfAlertFormatted}},
#{Name = 'Country'; Expression = {$_.parent}},
#{Name = 'ServerName'; Expression = {$_.child}},
Category,ServicePlanDisplayName, Message
The above should output something like
Time : Thu 09/19/2019 12:00:19 AM
Country : IL
ServerName : Servername
Category : Phase Failure
ServicePlanDisplayName : Gold
Message : One or more source luns do not have a remote target specified/mapped.
Time : Wed 09/18/2019 02:18:25 PM
Country : IL
ServerName : Server2
Category : General Failure
ServicePlanDisplayName : Gold
Message : One or more source luns do not have a remote target specified/mapped.
If your variable $temp is NOT what I suspect it to be, please edit your question and show us the XML aswell as the code you use to extract the alerts from it.

Adding a single space between each consecutive separators with SED

This looked easy but it's messing with my head.
Convert this
"value:::text:::::othervalue:::::::text"
to this
"value: : :text: : : : :othervalue: : : : : : :text"
SED isn't recursive, so I get this:
$ echo "value:::text:::::othervalue:::::::text" | sed 's/::/: :/g'
> value: ::text: :: ::othervalue: :: :: ::text
Workaround, sed twice
$ echo "value:::text:::::othervalue:::::::text" | sed 's/::/: :/g;s/::/: :/g'
> value: : :text: : : : :othervalue: : : : : : :text
This doesn't look elegant, and it's not intuitive. Is there any command (in sed maybe?) that might do this more cleanly?
Thanks!
Note: I'm looking for readability.
With GNU sed:
echo '"value:::text:::::othervalue:::::::text"' | sed ':a;s/::/: :/g;ta'
Output:
"value: : :text: : : : :othervalue: : : : : : :text"
From sed man page:
t label: If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.
: label: Label for b and t commands.

How to get a child item into a variable on its own

I am relatively sure this is quite easy to do but my google fu is not running strong
At the moment I am doing:
add-pssnapin windows.serverbackup
get-wbsummary
This returns me:
NextBackupTime : 07/09/2012 12:00:00
NumberOfVersions : 210
LastSuccessfulBackupTime : 06/09/2012 21:00:13
LastSuccessfulBackupTargetPath : \\?\Volume{bf315689-e5ed-11e1-a376-d067e5f384ea}
LastSuccessfulBackupTargetLabel : SBSERVE 2012_08_21 12:20 DISK_01
LastBackupTime : 06/09/2012 21:00:13
LastBackupTarget : SBSERVE 2012_08_21 12:20 DISK_01
DetailedMessage :
LastBackupResultHR : 0
LastBackupResultDetailedHR : 0
CurrentOperationStatus : NoOperationInProgress
What I want to do is get just the result portion (not its title into a variable) so for example $lastbackuptime = 07/09/2012 12:00:00
PS> $wbs = Get-WBSummary
PS> $lastbackuptime = $wbs.NextBackupTime