RegEx with powershell and then replace - powershell

So I have this variabe:
Frontend=http://xxxx-xxx.xxx.se/nexus/service/local/repositories/xxxxx_Releases/content/xxx/1.1.1.2/xxxx-1.1.01.2.nupkg
Now I want a powershell that takes out only the 1.1.1.2 (regex?)
Then this nr should be replaced in a property file (propfile.properties) looking like this
FE=1.1.1.1
So the 1.1.1.1 should be replaced with 1.1.1.2
Is this possible to get to work with powershell?
EDIT. The numbers looking for in the variable would be 1.X (0-3).X (0-X).X (0-X)

Extracting the numbers for a start:
$str = "Frontend=http://xxxx-xxx.xxx.se/nexus/service/local/repositories/xxxxx_Releases/content/xxx/1.1.1.2/xxxx-1.1.01.2.nupkg"
$str -match '^(.*?)((\d\.){3}\d)(.*)$'
$matches[2] # 1.1.1.2

Related

Shortening this script as much as possible using wildcard/regex/code golfing

I have made a short script that will pull dns txt records down from a server and combine them into a single string.
DNS txt records are:
1.website.com
2.website.com
3.website.com
each of these are iterated through using the single digit number.
the double quotes at the beginning and the end of the strings are trimmed
This works exactly as I would like it too
I am simply interested in seeing how short I can get it
assistance is appreciated please and thank you
$i = 1
1..2 | foreach {
$w="$i.website.com"
sv -N v -Va ((nslookup -q=txt $w )[-1]).Trim().Trim('"')
$p += "$v"
$i += 1
}
and ideally i'd like to return the $p variable, that being the concatenated string
There's a number of obvious consolidations you can make here, most notably the fact that neither $i nor $w is necessary.
That being said, I'd strongly recommend using Resolve-DnsName and let that take care of parsing the output for you
1..3|%{$p+=Resolve-DnsName "$_.website.com." -Ty TXT -EA 0|% S*s}
The % S*s command will resolve the Strings property on the output records (only property matching the wildcard pattern)

Powershell add text after 20 characters

I want to add text after exactly 20 characters inklusiv blanks. Does someone have a short solution with add-content or can post a link where i can read about a way to do so.
My file looks somthing like this:
/path1/path1/path1 /path2/path2/path2 /path3/path3/path3
than an application will read this pahts (not my application and i can not edit it in any way) the application will read these paths and it will read them on their position so if the second path starts 10 characters later it wont recognize it, so i can not simply replace the path or edit it easy sinc the path has not always the same lenght. Why the application reads it that way dont ask me.
So i need to add a string at start than the next string at exactly character 20 and than the next at charcter 40.
You could use the regex -replace operator to inject a new substring after 20 characters:
PS ~> $inject = "Hello Manuel! ..."
PS ~> $string = "Injected text goes: and then there's more"
PS ~> $string -replace '(?<=^.{20})',$inject
Injected text goes: Hello Manuel! ...and then there's more
The regex pattern (?<=^.{20}) describes a position in the string where exactly 20 characters occur between the start of the string and the current position, and the -replace operator then replaces the empty string at said position with the value in $inject
This did it for me
$data.PadRight(20," ") | Out-File -FilePath F:\test\path.txt -NoNewline -Append

Powershell Nested Replace

I am looping through multiple remote machines looking for a certain string to appear in a log file (other things are being collected from each device but for simplicity I've left that out). When I find them I want to return them and write to a central log, this is all working perfectly, except I want to tidy up the central log, by removing information from each string.
So I start with
**28-Jan-2021 01:31:49,TCPServer.run(),3,JMX TCP Server running on 8085
But want to save to Central Log
28-Jan-2021 01:31:349,JMX TCP 8085
And I can achieve this using the below, but surely there is a more succinct way to do this? (have played about with -Replace but no joy)
$JMXString8085 = $JMXString8085.Replace("TCPServer.run(),3,","")
$JMXString8085 = $JMXString8085.Replace("}","")
$JMXString8085 = $JMXString8085.Replace(" Server running on","")
[...] surely there is a more succinct way to do this? (have played about with -Replace but no joy)
There is, and -replace can indeed help us here. -replace is a regex operator, it performs text replacement using regular expressions - patterns we can use to describe strings that we might not be quite sure the exact contents of.
For a string like:
$string = '**28-Jan-2021 01:31:49,TCPServer.run(),3,JMX TCP Server running on 8085'
... we could describe the fields in between the commas, and use that to tell PowerShell to only preserve some of them for example:
PS ~> $string -replace '^\*\*([^,]+),[^,]+,[^,]+,([^,]+) Server running on (\d+)', '$1,$2 $3'
28-Jan-2021 01:31:49,JMX TCP 8085
The pattern I used in this example (^\*\*([^,]+),[^,]+,[^,]+,([^,]+) Server running on (\d+)) might seem a bit alien at first, so let's try and break it down:
^ # carret means "start of string"
\*\* # Then we look for two literal asterisks
( # This open parens means "start of a capture group"
[^,]+ # This means "1 or more characters that are NOT a comma", captures the timestamp
) # And this matching closing parens means "end of capture group"
, # Match a literal comma
[^,]+ # Same as above, this one will match "TCPServer.run()"
, # Same as above
[^,]+ # You probably get the point by now
, # ...
( # This open parens means "start ANOTHER capture group"
[^,]+? # The `?` at the end means "capture as few as possible", captures "JMX TCP"
) # And this matching closing parens still means "end of capture group"
Server... # Just match the literal string " Server running on "
( # Finally a THIRD capture group
\d+ # capturing "1 or more digits", in your case "8085"
) # and end of group
Since our pattern "captures" a number of substrings, we can now refer to these individual substrings in out substition pattern $1,$2 $3, and PowerShell will replace the $N references with the capture group value.
here is yet another way to do the job. [grin]
what it does ...
assigns the string to a $Var
chains .Replace() to get rid of the asterisks and the "Server" phrase
splits on the , chars
takes the 1st & 4th items from that split
joins them into one string with , [comma then space] for a delimiter
assigns that to a new $Var
displays the results
the code ...
$InString = '**28-Jan-2021 01:31:49,TCPServer.run(),3,JMX TCP Server running on 8085'
$OutString = ($InString.Replace('**', '').Replace('Server running on ', '').Split(',')[0, 3]) -join ', '
$OutString
output ...
28-Jan-2021 01:31:49, JMX TCP 8085

How to filter powershell ssh output

I use the script described in PowerShell, read/write to SSH.NET streams to get info from my firewall. However I need to isolate only 4 values.
edit "test-connection1"
set vdom "test1"
set ip 192.168.0.1 255.255.255.0
set allowaccess ping
set inbandwidth 10000
set outbandwidth 10000
edit "test-connection2"
set vdom "test1"
set ip 192.168.1.1 255.255.255.0
set allowaccess ping
set inbandwidth 10000
set outbandwidth 10000
--
edit "test-connection3"
set vdom "test2"
set ip 192.168.2.1 255.255.255.0
set allowaccess ping
set inbandwidth 10000
set outbandwidth 10000
I need to show only bold values. New row needs to be created on each "edit". The values can be separated by comma.
I need to get following result
test-connection,test1,10000,10000
test-connection2,test1,10000,10000
test-connection3,test2,10000,10000
How can I manipulate output created in function
function ReadStream($reader)
{
$line = $reader.ReadLine();
while ($line -ne $null)
{
$line
$line = $reader.ReadLine()
}
}
If each edit is predictable, you can do something like the following:
switch -Regex -File edit.txt {
'^edit "(?<edit>[^"]+)"' {$edit = $matches.edit}
'^set vdom "(?<vdom>[^"]+)"' {$vdom = $matches.vdom}
'^set inbandwidth (?<inb>\d+)' {$inb = $matches.inb}
'^set outbandwidth (?<outb>\d+)' { $edit,$vdom,$inb,$matches.outb -join ","}
}
$matches is an automatic variable that contains the result of string comparison using the -match operator. The variable is overwritten every time there is a successful match. Capture group values can be accessed by their names using the member access operator .. This is why you see the syntax $matches.edit to retrieve the value of the edit capture group.
The switch statement can read a file line-by-line using the -File parameter and perform regex matching using the -Regex parameter.
If the format of the edit entries are predictable, we can assume that we will always have an edit, vdom, inbandwidth, and outbandwidth lines in that order. That means we can assume we will have matches in that order and can therefore output all of the edit block matches once outbandwidth is matched.
The regular expressions (regexes) are the values within the single quotes on each line. Below is a breakdown of the two types of expressions used:
^edit "(?<edit>[^"]+)":
^ asserts position at start of a line
edit matches the characters edit literally (case insensitive)
Named Capture Group edit (?[^"]+)
Match a single character not present in the list [^"]+, which means not a double quote character.
Quantifier (+) — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
" matches the character " literally (case sensitive)
^set inbandwidth (?<inb>\d+):
^ asserts position at start of a line
set inbandwidth matches the characters set inbandwidth literally (case insensitive)
Named Capture Group inb (?\d+)
\d+ matches a digit (equal to [0-9])
Quantifier (+) — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

powershell - replace line in .txt file

I am using PowerShell and I need replace a line in a .txt file.
The .txt file always has different number at the end of the line.
For example:
...............................txt (first)....................................
appversion= 10.10.1
............................txt (a second time)................................
appversion= 10.10.2
...............................txt (third)...................................
appversion= 10.10.5
I need to replace appversion + number behind it (the number is always different). I have set the required value in variable.
How do I do this?
Part of this issue you are getting, which I see from your comments, is that you are trying to replace text in a file and saved it back to the same file while you are still reading it.
I will try to show a similar solution while addressing this. Again we are going to use -replaces functionality as an array operator.
$NewVersion = "Awesome"
$filecontent = Get-Content C:\temp\file.txt
$filecontent -replace '(^appversion=.*\.).*',"`$1$NewVersion" | Set-Content C:\temp\file.txt
This regex will match lines starting with "appversion=" and everything up until the last period. Since we are storing the text in memory we can write it back to the same file. Change $NewVersion to a number ... unless that is your versioning structure.
Not sure about what numbers you are keeping
About which part of the numbers, if any, you are trying to preserve. If you intend to change the whole number then you can just .*\. to a space. That way you ignore everything after the equal sign.
Yes, you can with regex.
Let call $myString and $verNumber the variables with text and version number
$myString = "appversion= 10.10.1";
$verNumber = 7;
You can use -replace operator to get the version part and replace only last subversion number this way
$mystring -replace 'appversion= (\d+).(\d+).(\d+)', "appversion= `$1.`$2.$verNumber";