PowerShell : Spliting text into two (or more) lines - powershell

I just finished working on menu generator, but I need to add warning message or popup like this one :
the warning message, like the other elements of menu, should have same width of 80 (inner width is 78, because border takes two). I built a function with one parameter which can easy generate that message for the text that will be displayed. The problem is when I put text longer than 78 characters, I get errors. I want to split it into two (or more depending on how many lines we would get) parameters cause no one will count to 78 on each parameter/line. I'm looking for a possibility to split text into two or more lines to fit the inner width of 78.
Since this time I decided to split text with " "(space) separator
$textsplit = $text.Split(" ")
Then I decided to add each element of $textsplit to an array using a Do-Until loop
$warningmsgline1.Add($textsplit[$i])
$warningmsgline1.Add(" ")
to make a new variable that will contain a sentence (words) that contains less then 78 characters.
I hope you are keeping up :)
How can I create such a condition? Nested loops? What kind of loops? For? Do-Until?
Feel free to ask if something is unclear.

I am a little fuzzy on understanding your question. But if I understand you correctly, you want to handle line wrapping at a max of 78 characters? This is not complete, but should set you in the right direction.
$message = "This is a really long message that is longer than 80 characters. It will need to be wrapped onto a second line."
$wordArray = $message.Split(' ')
$output = #()
$currentLine = ""
$wordArray | ForEach-Object {
if ($currentLine.Length + 1 + $_.Length -le 78) {
$currentLine = "$currentLine $_"
}
else {
$output += $currentLine
$currentLine = $_
}
}
## Add remainder to output
$output += $currentLine
$output

Related

Extract log lines from a starting string to the first time stamp after with PowerShell

It is my first time that I am reaching back to you as I am stuck on something and been scratching my head for over a week now. It is worth saying that I just started with PowerShell a few months ago and I love using it for my scripts, but apparently my skills still need improving. I am unable to find a simple and elegant solution that would extract a log from clearly defined start line until the first empty line CF\LF or time stamp that follows.
I am attaching the log I am trying to extract the data from. To specify the problem and give some more details about the log lines - they can vary in number, the end line of each log can also vary and the time stamp is different for each log depending on the time the test was executed.
cls
# Grab the profile system path
$userProfilePath = $env:LOCALAPPDATA
# Define log path
$logPath = "$userProfilePath\DWIO\logs\IOClient.txt"
# Define the START log line matching string
# This includes the the tests that PASS and FAIL
$logStartLine = " TEST "
# Find all START log lines matching the string and grab their line number
$StartLine = (Get-Content $logPath | select-string $logStartLine)
#Get content from file
foreach ($start in $StartLine) {
# Extract the date time stamp from every starting line
$dateStamp = ($start -split ' ')[0]
#Regex pattern to compare two strings
$pattern = "(.*)$dateStamp"
#Perform the opperation
$result = [regex]::Match($file,$pattern).Groups[1].Value
Write-Host $result
}
The log format is like:
08-31 16:32:20 INFO - [IOBridgeThread - mPerformAndComputeIntegrityCheck] - BridgeAsyncCall - mPerformAndComputeIntegrityCheck Result = TEST PASSED
Average Camera Temperature :40.11911°C
Module 0
Nb Points: 50673 pts (>32500)
Noise:
AMD: 0.00449238 mm (<0.027)
STD DEV: 0.006961088 mm
Dead camera: false
Module 1
Nb Points: 53809 pts (>40000)
Noise:
AMD: 0.0055302843 mm (<0.027)
STD DEV: 0.00869096 mm
Dead camera: false
Module consistency
Weak module: false
M0 to M1
Distance: 0.007857603 mm (<0.015)
Angle: 0.022567615 degrees (<0.07)
Target
Position: 0.009392071 mm (<5.0)
Angle: 0.54686683 degrees (<5.0)
Intensity: 120.35959
08-31 16:32:20 INFO - [cIOScannerService RUNNING] - Scanner State is now Scan-Ready
The issue is that the line at the end of every log would be different as well as the log lines would differ so it is the only logical way to achieve the correct extraction is to match the first line which would always contain: " TEST " and then grab the log to the first timestamp appearance after or the empty line which also shows every time at the end of the log.
Just not sure how to achieve that and the code I have is returning no/empty matches, however if I echo $StartLine - it shows correctly the log starting lines.
You can match the first line that starts with a date time like format and contains TEST in the line. Then capture in group 1 all the content that does not start with a date time like format.
(?m)^\d{2}-\d{2} \d{2}:\d{2}:\d{2}.*\bTEST\b.*\r?\n((?:(?!\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*(?:\r?\n|$))*)
Explanation
(?m) Inline modifier for multiline
^ Start of line
\d{2}-\d{2} \d{2}:\d{2}:\d{2}.*\bTEST\b.* Match a date time like pattern followed by TEST in the line
\r?\n Match a newline
( Capture group 1
(?: Non capture group
(?!\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*(?:\r?\n|$) If the line does not start with a date time like pattern, match the whole line followed by either a newline or the end of the line
)* Close non capture group and repeat 0+ times
) Close group 1
See a regex101 demo and a .NET regex demo (click on the Table tab) and a powershell demo
You can use Get-Content -Raw to get the contents of a file as one string.
$textIOClient = Get-Content -Raw "$userProfilePath\DWIO\logs\IOClient.txt"
$pattern = "(?m)^\d{2}-\d{2} \d{2}:\d{2}:\d{2}.*\bTEST\b.*\r?\n((?:(?!\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*(?:\r?\n|$))*)"
Select-String $pattern -input $textIOClient -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value}
I found an approach I really loved in this answer elsewhere on the site:
PowerShell - Search String in text file and display until the next delimeter
Using that, I wrote a little code around it in the following to show you how to use the results:
$itemCount = 1
$Server = ""
$Data = #()
$Collection = #()
Switch(GC C:\temp\stackTestlog.txt){
{[String]::IsNullOrEmpty($Server) -and !([String]::IsNullOrWhiteSpace($_))}{$Server = $_;Continue}
{!([String]::IsNullOrEmpty($Server)) -and !([String]::IsNullOrEmpty($_))}{$Data+="`n$_";Continue}
{[String]::IsNullOrEmpty($_)}{$Collection+=[PSCustomObject]#{Server=$Server;Data=$Data};Remove-Variable Server; $Data=#()}
}
If(!([String]::IsNullOrEmpty($Server))){$Collection+=[PSCustomObject]#{Server=$Server;Data=$Data};Remove-Variable Server; $Data=#()}
if(($null -eq $collection) -or ($Collection.Count -eq 0)){
Write-Warning "Could not parse file"
}
else{
Write-Output "Found $($collection.Count) members"
ForEach($item in $Collection){
#add additional code here if you need to do something with each parsed log entry
Write-Output "Item # $itemCount $($item.Server) records"
Write-Host $item.Data -ForegroundColor Cyan
$itemCount++
}
}
You can extend this in the line with a comment, and then remove the Write-output and Write-Host lines too.
Here's what it looks like in action.
Found 2 members
Item #1 08-31 16:32:20 INFO - [IOBridgeThread - mPerformAndComputeIntegrityCheck] - BridgeAsyncCall - mPerformAndCompu
teIntegrityCheck Result = TEST PASSED records
Average Camera Temperature :40.11911°C
#abridged...
Item #2 blahblahblah

Loop through multiple array in powershell

I have 2 arrays here one contains the servername and other contains the IP.
I need to loop through them and create a key value pair like below for each server
server1:ip1
server2:ip2
I have written below code, but the problem is if i debug the code using F11, it is working fine, but i don't it gives some error which is different every time.
so feeling like it is not that reliable piece to continue.
$NewDNSEntryName = $DNSEntryName.Split(",")
$DNSIPs = $DNSIP.Split(",")
if($DNSEntryName -match "," -or $DNSIP -match ",")
{
0..($NewDNSEntryName.Count - 1) | ForEach-Object {
$fullName=""
$fullName += #("$($NewDNSEntryName[$_]):$($DNSIPs[$_])")
This is the line where i am facing trouble
0..($NewDNSEntryName.Count - 1) | ForEach-Object
Please let me know why this code is behaving like this else any alternate idea is appreciated
Assuming each item in each list corresponds with each other exactly, you can use a for loop and loop through the array indexes.
$NewDNSEntryName = $DNSEntryName.Split(",")
$DNSIPs = $DNSIP.Split(",")
for ($i = 0; $i -lt $DNSIPs.count; $i++) {
"{0}:{1}" -f $NewDNSEntryName[$i],$DNSIPs[$i]
}
For the code above to work, $DNSEntryName and $DNSIP must be single strings with commas between names and IPs. If $DNSEntryName and $DNSIP are already lists or arrays, something else will need to be done.
In your attempt, technically, your logic should work given everything written above is true. However, $fullName is emptied at every single iteration, which may produce undesirable results.

powershell extracting data from strings or other suggestions

I have a script I am writing that essentially reads data from an excel document that is generated from another tool. It lists file ages in the format listed below. My issue is I would like to process each cell value and change the cell color based on that value. So anything older than 1 year gets changed to RED, 90+ days gets yellow\orange.
So after a bit of research, I elected to use an if statement to determine when it is greater than 0 years which seems to work fine, however when I reach the days portion I'm not sure how to extract JUST the digits portion to the left of d in each cell when you get to the y if its there just stop OR possibly just read the left digits only if the $_ contains d then I could further process if that value is -gt 90? I am unsure of how to extract variable length strings only if they are digits left of a character. I considered using a combination of the below method of finding a character and returning up to y or something else.
Find character position and update file name
Possible Age Formats:
13y170d
3y249d
8h7m
1y109d
1y109d
1y109d
5d22h
3y281d
3y184d
11y263d
7m25s
1h14m
[regex]$years = "\d{1,3}[0-9]y"
[regex]$days_90 = "\d{0,3}[0-9]d"
conditionally formatting/coloring row based on age (years)
if ( $( A$_ -match "$years") -eq $True ) {
$($test_home).$("Last Accessed") | ForEach-Object { $( $($_.Contains("y") -eq $True ) { New-ConditionalText -Text Red } }
conditionally formatting/coloring row based on age (90+ days)
if ( $( A$_ -match "$days_90") -eq $True ) { New-ConditionalText -Text Yellow }
What you are after is a positive lookahead and lookbehind. Effectivly it gets the text between two characters or sets. Really handy if you have a consistently formatted set of data to work with.
[regex]$days_90 = '(?<=y).*?(?=d)'
. Matches any characters without line breaks.
* Matches 0 or more of the preceding token.
? Makes the regex lazy and try to match as few as possible.

Replace string untill its length is less than limit with PowerShell

I try to update users AD accounts properties with values imported from csv file.
The problem is that some of the properties like department allow strings of length of max length 64 that is less than provided in the file which can be up to 110.
I have found and adopted solution provided by TroyBramley in this thread - How to replace multiple strings in a file using PowerShell (thank You Troy).
It works fine but... Well. After all replaces have place the text is less meaningful than originally.
For example, original text First Department of something1 something2 something3 something4 would result in 1st Dept of sth1 sth2 sth3 sth4
I'd like to have control over the process so I can stop it when the length of the string drops just under the limit alowed by AD property.
By the way. I'd like to have a choice which replacement takes first, second and so on, too.
I put elements in a hashtable alphabetically but it seems that they are not processed this way. I can't figure out the pattern.
I can see the resolution by replacing strings one by one, controlling length after each replacement. But with almost 70 strings it leds to huge portion of code. Maybe there is simpler way?
You can iterate the replacement list until the string reaches the MaxLength defined.
## Q:\Test\2018\06\26\SO_51042611.ps1
$Original = "First Department of something1 something2 something3 something4"
$list = New-Object System.Collections.Specialized.OrderedDictionary
$list.Add("First","1st")
$list.Add("Department","Dept")
$list.Add("something1","sth1")
$list.Add("something2","sth2")
$list.Add("something3","sth3")
$list.Add("something4","sth4")
$MaxLength = 40
ForEach ($Item in $list.GetEnumerator()){
$Original = $Original -Replace $Item.Key,$Item.Value
If ($Original.Length -le $MaxLength){Break}
}
"{0}: {1}" -f $Original.Length,$Original
Sample output with $MaxLength set to 40
37: 1st Dept of sth1 sth2 sth3 something4

How do I put the value into txt file(file contains blank spaces)? Powershell

I have problem with data in the file. Data in the text file looks like:
ADSE64E...Mobile phone.....................
EDW8......Unknown item.....................
CAR12.....Peugeot 206 with red colour......
GJ........Parker model 2...................
Por887W8..Black coffe from Peru............
The dots represents blank spaces. First column is Product_Code (long 1-10) and second (long 1-255) is Description. All i need is:
ADSE64E;Mobile phone
EDW8;Unknown item
CAR12;Peugeot 206 with red colour
GJ;Parker model 2.
Por887W8;Black coffe from Peru
My solusions are:
First column get to the variable (and same process with second column) and merge both variables to one.. But i dont know how..
$variabletxt = get-content C:\Product.txt
$firstcolumn = $variablestxt.substring(1,10)
$secondcolumn = $variablestxt.substring(10)
$final = ???
Replace blank spaces but problem is that product_code may by long 1-10.
Have you any suggestion how I resolve this problem?
split your sting then replace "more than one space" with nothing :
gc file.txt |%{
($_.substring(0,9) -replace "[ ]{2,}","")+";"+($_.substring(10,254) -replace "[ ]{2,}","")+";"
}
Remove trailing dots with the TrimEnd method and replace the ones that left.
Get-Content C:\Product.txt |
Foreach-Object { $_.TrimEnd() -replace '^([^\s]+)(\s+)(.+)$','$1;$3'}
ADSE64E;Mobile phone
EDW8;Unknown item
CAR12;Peugeot 206 with red colour
GJ;Parker model 2
Por887W8;Black coffe from Peru
Per #Kayasax comment (thanks!), if code length is 10 characters long there will be no space between the first and second column, so it may be safer to use this instead:
Get-Content C:\Product.txt |
Foreach-Object { '{0};{1}' -f $_.Substring(0,10).Trim(), $_.Substring(10).Trim() }