Parsing "" - Unrecognized escape sequence \T - powershell

I am trying to modify .config file. this line of code is only meant to be repleced in this file and few others with a new one from xml file but that goes later in code, currently I have issue with this line as I am not able to pass it to variable in a way that it will be treated as a regular string, will not be changed it in any way and will not throw "Parsing "" - Unrecognized escape sequence \T" exeption
I have always been doing it in this way if I don't need to use variables inside:
$oldValueSU = '<add key="splunk_username" value="${(splunk_username=D:\Tools\localtokens.xml)}"/>'
I also tried in this way
$oldValueSU = "<add key=""splunk_username"" value='`${(splunk_username=D:\Tools\localtokens.xml)}'/>"
None of these options work I am still receiving error "parsing "[Path I provided above]" - Unrecognized escape sequence \T."
How Script works:
The script works in a way that it takes that variable and looks through the whole file in order to find a mathing one of it does then it takes a path to that file and adds it to other variable and then changes it's value to a diffrent string.
If more information is needed I will be happy to provide it

Alright I found the issue and solution in my code
The issue was while trying to check if content of a file matches given string
if (($file -match $oldValueSU) -and ($file -match $oldValueSP))
It was using -match which uses Regex which was cousing the exeption I changed it to:
if (($file -like "*$oldValueSU*") -and ($file -like "*$oldValueSP*"))
After that in a part where in my code I was using -replace (which also uses Regex):
$fileContentPathTemp -replace "*$oldValueSU*", $newValueSU
I changed it to .Replace which works directly on String and it solved the issue:
$fileContentPathTemp.Replace($oldValueSU,$newValueSU)
So the whole issue was based on using Regex this solution is more like a workaround which just does not use it at all
I hope this solution will help somebody in the future, I am sorry for not providing all of the nececary information at the beggining. Thanks everyone for spending time on my issue

Related

powershell -match Unexpect Results

i've written a simple PowerShell script that is designed to take a file name and then move the file into a particular folder.
The files in question are forms scanned in as PDF documents.
Within the file name, I have defined a unique string of characters used to help identify which form it is and then my script will sort the file into the correct folder.
I've captured the file name as a string variable.
I am using -match to evaluate the file name string variable and my issue is that match is acting like...well -like.
For example, my script looks for (F1) in the string and if this returns true my script will move the file into a folder named IT Account Requests.
This all works well until my script finds a file with (F10) in the name, as 'match' will evaluate the string and find a match for F1 also.
How can I use 'match' to return true for an exact string block?
I know this may sound like a fairly basic newbie question to ask, but how do I use -match to tell the different between the two file types?
I've scoured the web looking to learn how to force -match to do what I would like but maybe I need a re-think here and use something other than 'match' to gain the result I need?
I appreciate your time reading this.
Code Example:
$Master_File_name = "Hardware Request (F10).pdf"
if ($Master_File_name -match "(F1)"){Write-Output "yes"}
if ($Master_File_name -match "(F10)"){Write-Output "yes"}
Both if statements return 'yes'
-match does a regular expression based match against your string, meaning that the right-hand side argument is a regex pattern, not a literal string.
In regex, (F1) means "match on F and 1, and capture the substring as a separate group".
To match on the literal string (F1), escape the pattern either manually:
if($Master_File_Name -match '\(F1\)'){Write-Output 'yes'}
or have it done for you automatically using the Regex.Escape() method:
if($Master_File_Name -match [regex]::Escape('(F1)')){Write-Output 'yes'}

Pipes in replace causing line to be duplicated

I have a script that I need to replace a couple of lines in. The first replace is going fine but the second is wiping out my file and duplicating the line multiple times.
My code
(get-content $($sr)) -replace 'remoteapplicationname:s:SHAREDAPP',"remoteapplicationcmdline:s:$($sa)" | Out-File $($sr)
(get-content $($sr)) -replace 'remoteapplicationprogram:s:||SHAREDAPP',"remoteapplicationprogram:s:||$($sa)" | Out-File $($sr)
The first replace works perfectly. The second one is causing this:
remoteapplicationprogram:s:||stagaredrremoteapplicationprogram:s:||stagarederemoteapplicationprogram:s:||stagareddremoteapplicationprogram:s:||stagarediremoteapplicationprogram:s:||stagaredrremoteapplicationprogram:s:||stagarederemoteapplicationprogram:s:||stagaredcremoteapplicationprogram:s:||stagaredtremoteapplicationprogram:s:||stagaredcremoteapplicationprogram:s:||stagaredlremoteapplicationprogram:s:||stagarediremoteapplicationprogram:s:||stagaredpremoteapplicationprogram:s:||stagaredbremoteapplicationprogram:s:||stagaredoremoteapplicationprogram:s:||stagaredaremoteapplicationprogram:s:||stagaredrremoteapplicationprogram:s:||stagareddremoteapplicationprogram:s:||stagared:remoteapplicationprogram:s:||stagarediremoteapplicationprogram:s:||stagared:remoteapplicationprogram:s:||stagared1remoteapplicationprogram:s:||stagared
etc...
Is this because of the ||? If so, how do I get around it?
Thanks!
To begin with, you should be using slightly more meaningful names for your variables. Especially if you want someone else to be reviewing your code.
The gist of your issue is that -replace supports regexes (regular expressions), and you have regex control characters in your pattern string. Consider the following simple example, and notice everywhere the replacement string is found:
PS C:\Users\Matt> "ABCD" -replace "||", "bagel"
bagelAbagelBbagelCbagelDbagel
-replace is also an array operator, so it works on every line of the input file, which is nice. For simplicity's sake, if you are not using a regex, you should just consider using the string method .Replace(), but it is case-sensitive, so that might not be ideal. So let's escape those control characters in the easiest way possible:
$patternOne = [regex]::Escape('remoteapplicationname:s:SHAREDAPP')
$patternTwo = [regex]::Escape('remoteapplicationprogram:s:||SHAREDAPP')
(get-content $sr) -replace $patternOne, "remoteapplicationcmdline:s:$sa" | Out-File $($sr)
(get-content $sr) -replace $patternTwo, "remoteapplicationprogram:s:||$sa" | Out-File $($sr)
Now we get both patterns matched as you have them written. Run $patternTwo on the console to see what has changed to it! $patternOne, as written, has no regex control characters in it, but it does not hurt to use the escape method if you are just expecting simple matching.
Aside from the main issue pointed out, there is also some redundancy and misconception that can be addressed here. I presume you are updating a source file to replace all occurrences of those strings, yes? Well, you don't need to read the file in twice, given that you can chain -replace:
$patternOne = [regex]::Escape('remoteapplicationname:s:SHAREDAPP')
$patternTwo = [regex]::Escape('remoteapplicationprogram:s:||SHAREDAPP')
(get-content $sr) -replace $patternOne, "remoteapplicationcmdline:s:$sa" -replace $patternTwo, "remoteapplicationprogram:s:||$sa" |
Set-Content $sr
Perhaps that will do what you intended.
You might notice that I've removed the subexpressions operators ($(...)) around your variables. While they have their place, they don't need to be used here. They are only needed inside more complicated strings, like when you need to expand object properties or something.

Replacing $_ substring value in powershell

I am trying to make further use of a wonderful piece of code I found when I tried to replace text at a specified line.
However trying to get it to read $_.Substring() and then using $_ -replace is giving me troubles; although I get no error messages the text does not get replaced.
Here is code that does not work:
$content = Get-Content Z:\project\folder\subfolder\newindex2.html
$content |
ForEach-Object {
if ($_.ReadCount -ge 169 -and $_.ReadCount -le 171) {
$a = $_.Substring(40,57)
$linked = '' + $a + ''
$_ -replace $a,$linked
} else {
$_
}
} |
Set-Content Z:\project\folder\subfolder\newindex2.html
The whole point is to make the content of a cell in a html table column link to a file on a webserver with the same name as what's in the cell.
I didn't have any luck trying my hand at regex trying to match the filenames, but since I managed to make it so the text that's to be replaced always ends up at the same position, I figured I'd try positional replacement instead.
The text that is to be replaced is always 57 characters long and always starts at position 40.
I looked at the variables getting set, and everything gets set correctly, except that
$_ -replace $a,$linked
does not replace anything.
Instead, the whole file just gets written anew with nothing changed. Can anyone please point to what I am missing and/or point to how to reach the result more easily? Maybe I'm using Substring wrong and should be using something else?
The first item in the right-hand argument of -replace is a regex pattern, so depending on what the substring contains, some of the characters might be regex control characters.
You can either escape it:
$_ -replace $([regex]::Escape($a)),$linked
Or use the String.Replace() method, which does not use regex:
$_.Replace($a,$linked)
Finally, as #Matt points out, you might want to avoid the find-and-replace approach altogether, since you already know at which character indices you need to insert your new value:
$_.Remove(40,57).Insert(40,$linked)

Powershell -match operator issue

I've written a script that compares two strings, both of which are path names. The first is the full path to a file and the second is a higher level path. I've replaced spaces and backslashes with underscores.
The variables are assigned correctly such as
$full = "__server_department_project_file.txt"
$part = "__server_department_"
The script uses
$testformatch = $full -match $part
In one of my environments this works perfectly (returning TRUE when appropriate). In another completely separate environment this fails constantly (always returns FALSE).
In the failing domain, when I type these things out manually it returns TRUE as expected, but the script always returns FALSE. I've added a testing line that displays the comparisons, copied those results dumped to the screen and manually cut and pasted them into variables in ps command line directly - and those return TRUE.
I'm at a complete loss for what might be causing this. Are there special characters or rules about -match that may be coming into play? Any ideas would be greatly appreciated. Thanks!

handling a CSV with line feed characters in a column in powershell

Currently, I have a system which creates a delimited file like the one below in which I've mocked up the extra line feeds which are within the columns sporadically.
Column1,Column2,Column3,Column4
Text1,Text2[LF],text3[LF],text4[CR][LF]
Text1,Text2[LF][LF],text3,text4[CR][LF]
Text1,Text2,text3[LF][LF],text4[CR][LF]
Text1,Text2,text3[LF],text4[LF][LF][CR][LF]
I've been able to remove the line feeds causing me concern by using Notepad++ using the following REGEX to ignore the valid carriage return/Line feed combinations:
(?<![\r])[\n]
I am unable however to find a solution using powershell, because I think when I get-content for the csv file the line feeds within the text fields are ignored and the value is stored as a separate object in the variable assigned to the get-content action. My question is how can I apply the regex to the csv file using replace if the cmdlet ignores the line feeds when loading the data?
I've also tried the following method below to load the content of my csv which doesn't work either as it just results in one long string, which would be similar to using -join(get-content).
[STRING]$test = [io.file]::ReadAllLines('C:\CONV\DataOutput.csv')
$test.replace("(?<![\r])[\n]","")
$test | out-file .\DataOutput_2.csv
Nearly there, may I suggest just 3 changes:
use ReadAllText(…) instead of ReadAllLines(…)
use -replace … instead of .Replace(…), only then will the first argument be treated as a regex
do something with the replacement result (e.g. assign it back to $test)
Sample code:
[STRING]$test = [io.file]::ReadAllText('C:\CONV\DataOutput.csv')
$test = $test -replace '(?<![\r])[\n]',''
$test | out-file .\DataOutput_2.csv