Searching for backslash in a string with Powershell - powershell

I need to search for the amount of backslashes in a string to determine some file path parameters. I have not worked out a way to seach for a backslash without Powershell thinking it is an escapee character.
([regex]::Matches($FilePath, "\" )).count
Or
$a -match "\"
These both come up with an error "Illegal \ at end of pattern"
Thanks!

You can escape a backslash with a backslash:
[Regex]::Matches($FilePath, "\\").Count

Related

How to fix Folder Path error in PowerShell

I have this folder in my OneDrive and Just wondering how should I pass the path. Right now I'm getting "Folder not Found" when I try to do it like this.
$ServerRelativeUrl= "Documents/PC-OFFBOARD_USMPGWNCAT15C61-GZJY8T-01-Dec-0257/C$/'$Windows.~WS'"
With double-quoted " strings, you must escape characters with special meanings if you want them to be processed literally. PowerShell's escape character is the backtick `. The dollar-symbol $ must be prefixed with a backtick like this to be part of a literal file path:
"Documents/PC-OFFBOARD_USMPGWNCAT15C61-GZJY8T-01-Dec-0257/C`$/'`$Windows.~WS'"
Alternatively, you can use a single-quoted ' string instead, making sure to escape the literal single-quotes with two single-quotes '' (backticks won't escape in a literal string):
'Documents/PC-OFFBOARD_USMPGWNCAT15C61-GZJY8T-01-Dec-0257/C$/''$Windows.~WS'''
This loses your ability to insert actual intended variables though. You can however rely on the format operator in this case. To insert the literal string '$Windows.~WS' into the path, for example:
$folderName = '''$Windows.~WS'''
$fullPath = 'Documents/PC-OFFBOARD_USMPGWNCAT15C61-GZJY8T-01-Dec-0257/C$/{0}' -f $folderName

Replace special character with double double quotes

I have a text file with the some special character $, which needs to be replaced by double double quotes. I am using a bat file in which I invoke powershell.exe and write the replace command. Below is the command:
powershell "gc C:\Temp\Test.csv| foreach-object {$_ -replace '$','""""""'}|sc C:\Temp\Test_Replace.csv"
I know that double quotes are escaped by a double quote so """"" is equivalent to "". But as seen in the above code I need to write 6 double quotes to get the equivalent 2 quotes. I cannot figure out the reason for this.
Can Someone please illustrate the point I am missing.
As I said in comments, I think it is a but in PowerShell.exe command line parser. When it see "" inside quoted context, it not only produce literal " but also close quoted context:
CMD> powershell '"1 2""3 4"'
1 2"3 4
As you can see, there is only one space between 3 in 4 in printed string. You need to put extra double quote to reopen quoted context:
CMD> powershell '"1 2"""3 4"'
1 2"3 4
So, in fact, you have to triplicate double quote to produce just one literal double quote character.
You just need to escape the nested double quote properly. Also, the ForEach-Object isn't required. Put the Get-Content in an expression (i.e. in parentheses) and you can use the -replace operator directly.
powershell -Command "(gc C:\Temp\in.csv) -replace '$','\"\"'|sc C:\Temp\out.csv"
If you want to replace literal $ characters instead of adding double quotes to the end of each line you need to escape the $ as well, as Mathias pointed out:
powershell -Command "(gc C:\Temp\in.csv) -replace '\$','\"\"'|sc C:\Temp\out.csv"

Powershell escape character ` (backtick) not escaping string

I'm having trouble adding a new line into a string in powershell:
Get-ChildItem "C:\Users\matt\Desktop\CShell Install" |foreach {'<Component Id="'+$_.name+'" Guid="' +[guid]::NewGuid() + '">`r`n<File Id="'+$_.name+'" Source="$(var.CShell.TargetPath)"></File></Component>'}
As you can see I want a newline to occur at
``r`n
instead they are printed literally.
Any pointers?
Do not use Single Quote, where you want PowerShell to honor backticks (or any other characters that you need PowerShell to interpret).
"FirstLine`r`nSecondLine" prints
FirstLine
SecondLine
'"FirstLine`r`nSecondLine"' prints
"FirstLine`r`nSecondLine"

Perl q function or single quote doesn't return the string literal of UNC path correctly

Perl's q function or single quote is supposed to return the string literal as typed (except \'). But it doesn't work as expected for the following scenario.
I want to print the following UNC path
\\dir1\dir2\dir3
So I have used
my $path = q(\\dir1\dir2\dir3);
OR
my $path = '\\dir1\dir2\dir3';
But this skips one backslash at the front.
So if I print it i.e. print $path; it prints
\dir1\dir2\dir3
I want to know why? I have to type 3 or 4 backslashes at the beginning of the UNC path to make it work as expected. What am I missing?
From perldoc perlop:
q/STRING/
'STRING'
A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.
Change:
my $path = q(\\dir1\dir2\dir3);
to:
my $path = q(\\\dir1\dir2\dir3);
As for why, it's because Perl lets you include the quote delimiter in your string by escaping it with a backslash:
my $single_quote = 'This is a single quote: \'';
But if a backslash before the delimiter always escaped the delimiter, there would be no way to end a string with a backslash:
my $backslash = 'This is a backslash: \'; # nope
Allowing backslashes to be escaped too takes care of that:
my $backslash = 'This is a backslash: \\';
Interestingly enough, there is only one way to type in double backslashes in a perl string without it being interpolated as a single backslash.
As all the other answers showed, any of the quote operators treat backslashes as a backslash unless there is another one following it directly.
The only way to get the double backslashes to display exactly as you have typed them is to use a single quote here-doc.
my $path = <<'VISTA';
\\dir1\dir2\dir3
VISTA
chomp $path;
print $path."\n";
Would print it exactly as you've typed it in.

Find and replace not working on values containing a quotation mark in Powershell

I have a text file containing lines similar to:
"This is a test \" sentence"
I'm trying to remove all occurrences of \" and replace them with nothing using this find and replace:
$fixedline = $line -replace '\"',''
The result I want is this:
"This is a test sentence"
but instead I get:
This is a test \ sentence
What is the correct syntax for this? I've tried multiple combinations of quotes and double quotes but still no luck.
I've also tried setting the \" value to a variable and calling the variable instead with the same result.
EDIT Solution found, the escape character for \ is a double backslash so the correct syntax would be '\"'
I tried this and it worked:
$fixedLine = $line -replace '\\"', ''