Powershell -Replace command and escaping characters - powershell

I need to replace some strings multiple text files. I am running into an issue with the following string though. I tried escaping with a backtick ` before any special characters, but no luck, or maybe the backtick isn't in the right place.
I want to replace
Signal\s+:\s+',''
with
Signal\s+:\s+','';if (!`$signal) {`$signal='n/a'}
This is the string in the command that i am having a problem finding --> Signal\s+:\s+',''
Here is the powershell command i am using..
Get-ChildItem "f:\temp\*.ps1" | ForEach-Object -Process {(Get-Content $_) -Replace "Signal\s+:\s+',''" , "Signal\s+:\s+','';if (!`$signal) {`$signal='n/a'}" | Set-Content $_}
thank you

i just needed to escape the \ in the replace text.. thats all
-Replace "Signal\\s\+:\\s\+',''"
thanks

Related

How to replace path in text file with Powershell

I have a problem with replace text in Powershell. For e.g.
When I use:
(Get-Content C:\TEMP\App.config) -replace "one","two" | Set-Content C:\TEMP\App.config
it works. But when I use:
(Get-Content C:\TEMP\App.config) -replace "C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe","C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" | Set-Content C:\TEMP\App.config
is doesn't work. I search a lot of info in Google or documentation but still have a problem.
Can anybody help? :-)
You should be aware that the -replace command uses regex. It should work, if you escape the replace string:
$searchString = [Regex]::Escape('C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe')
$replaceString = 'C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe'
(Get-Content C:\TEMP\App.config) -replace $searchString, $replaceString | Set-Content C:\TEMP\App.config
The -replace operator uses regex on the search string and replaces that with another string.
That replacement string is a normal, unescaped string.
Since your path has characters in it that have special meaning in regex, like the backslash, you need to escape the search string by prepending a backslash in front of every such special character.
Regex has its own static method for that: [regex]::Escape()
Also worth mentioning is that if you read the file including the -Raw switch, so it wil become a single multline string, replacing values is much faster.
$search = [Regex]::Escape('C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe')
$replace = 'C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe'
(Get-Content -Path 'C:\TEMP\App.config' -Raw) -replace $search, $replace | Set-Content -Path 'C:\TEMP\App.config'

Difficulty escaping quote character in powershell script (Azure Devops Yaml)

My azure piplines yaml script uses powershell to replace a placeholder string in a .CS file with the current date string. This is the line with the value to be replaced (20200101000000)
[assembly: MyCompany.Net.Attributes.BuildDateAttribute("20200101000000")]
This is the powershell step that does it
pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "20200101000000", (get-date -f 'yyyyMMddhhmmss')} | set-content -path $(versionFile)
displayName: 'Update time stamp file'
I want to alter this step to include the quote characters " around the search string and write them into the new output value along with the new date. But I cannot seem to make that happen.
I mistakenly tried just putting escaped quote characters \" in the search and replace strings. But I guess you cannot escape inside of a single-quoted string so it did not work
pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "\"20200101000000\"", (get-date -f '\"yyyyMMddhhmmss\"')} | set-content -path $(versionFile)
This was the error:
##[command]"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1'"
ParserError: D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1:3
Line |
3 | … lyInfo.cs) | foreach-object {$_ -replace "\"20200101000000\"", (get-d …
| ~~~~~~~~~~~~~~~~~
| Unexpected token '20200101000000\""' in expression or statement.
##[error]PowerShell exited with code '1'.
I also tried to just using double quotes around the get-date part of the script so I could escape the quote characters but that doesn't seem to work either. I'm guessing that's a limitation of writing script this way.
Is there some other way to achieve what I want?
The escape character in Powershell is backtick (`), not backslash (\). Try e.g. "`"20200101000000`"".
You can use the Get-Date -UFormat instead to add arbitrary characters similar to the DateTime.ToString() function in .NET
'[Attrib("20200101000000")]' -replace '"20200101000000"', (get-date -UFormat '"%Y%m%d%H%M%S"')

Remove special characters from text file in Windows

I want to output text from a text file in Windows script like you can in Linux with grep:
grep -ve ^# -ve '^;' -ve ^$ /name of file.
I haven't had much success finding a solution. I am trying to use Powershell with little experience using it.
Use Select-String in place of grep:
Select-String -Path 'path/to/file' -Pattern '^[#;]|^$' -NotMatch
Select-String will output a Match object, if you just want to matched strings, grab the Line property:
Select-String ... |Select -Expand Line
Starting with PowerShell 7.0 you can also use the -Raw switch to have Select-String return only the matched strings and nothing else:
Select-String ... -Raw
This comes close. You can have an array of patterns seperated by commas. Just like in bash, the semicolon has to be quoted, because it means "end of statement" in powershell. The command avoids lines that start with "#", ";", or are blank.
'# comment',
'; semicolon',
'',
'one',
'two',
'three' | select-string ^#, '^;', ^$ -notmatch
one
two
three
This is what I used to output I was after; get-childitem zabbix_agentd.conf | select-string -pattern '^[#;]|^$' -notmatch
This is what I was after without all the lines that are commented out and spaces.
zabbix_agentd.conf:24:LogFile=C:\Program Files\Zabbix Agent\zabbix_agentd.log
zabbix_agentd.conf:88:Server=10.0.0.22
zabbix_agentd.conf:130:ServerActive=10.0.0.22
zabbix_agentd.conf:141:Hostname=RED-DOUG
zabbix_agentd.conf:257:Include=C:\Program Files\Zabbix Agent\zabbix_agentd.conf.d\
Thank you for the help, Doug

Replace a character with new line

Powershell ver 4. Windows 7
I wanted to replace , with new lines in a text file. I tried the script below
(Get-Content C:\Test\test.txt).Replace(',','`n') | Set-Content C:\Test\testv2.txt
but when I see the output file I see , replaced with '`n' instead of new line.
I also tried double quotes instead of single.
Replace(',',"`n")
This worked for me.
(Get-Content C:\Test\Test.txt) -replace ',',"`n" | Set-Content C:\Test\Test.txt -Force
Try this:
[IO.File]::ReadAllText(C:\Test\test.txt) -replace ',',"`r`n" | Out-File C:\Test\testv2.txt
P.S. Sorry that don't have time to explain it, now.

Replace `set` statements to `setx` in a batch script using powershell

Using powershell, I want to take a .bat file and replace all lines in which set is called to set an environment variable and change it to a corresponding setx call. Unfortunately it's not as simple as just doing a search and replace on the file, replacing set for setx, because the syntax is diffferent: set ENVNAME=abc vs setx ENVNAME abc.
Is there a simple way to do this in powershell? To just do the set for setx replacement, I have:
(Get-Content $orig_filename ) | ForEach-Object {$_ -replace "set", "setx"} | Set-Content $new_filename
Any pointers for a powershell novice would be appreciated.
Did some pretty limited testing and I'm not sure what your bat file looks like, but this may work for you.
(Get-Content $orig_filename ) | ForEach-Object {
$_ -replace 'set (.*)\=(.*)','setx $1 $2'
} | Set-Content $new_filename
You could also just chain another -replace to do the work for you. Also made the set > setx replacement a little more less error prone by ensuring you are replacing the word set at the beginning of the string. Since -replace functions as an array operator you do not need the foreach loop.
(Get-Content $orig_filename ) -replace "^set\b", "setx" -replace "="," " | Set-Content $new_filename