How to replace "\" with "\\" using powershell? - powershell

I am having a string which contains path.
$Paths = "Myfolder\Mysubfolder"
I need to replace them like "Myfolder\Mysubfolder"
But the $Paths -replace "\","\\" fails as regular expression is unable to find and replace "\".
How to replace then?

You can use .Replace() which does not use regular expressions like this:
$Paths = "Myfolder\Mysubfolder"
$Paths.replace('\','\\')
To use -replace you will need to escape the slash, since it is regex, on the match and not the substitution with the exception of $1 and $2 ...etc which are used a substitution groups.
$Paths -replace '\\','\\'
Result from both is:
Myfolder\\Mysubfolder

I'm thinking an = assignment is required?
$Paths = "Myfolder\Mysubfolder"
write-Host "debug ..... : $Paths"
$Paths = $Paths.Replace("\","\\")
write-Host "debug ..... : $Paths"
This gives:
debug ..... : Myfolder\Mysubfolder
debug ..... : Myfolder\\Mysubfolder

Related

Replace string with line break with another string in Powershell

I want to replace
$fieldTool.GetFieldValue($i
tem,"Title")
with
{{(sc_get_field_value i_item 'Title')}}
The original string has a line break and I am using 'n like this $fieldTool.GetFieldValue($i'ntem,"Title")
This is the code
$template = '<div class="tile-inspiration__title field-title">$fieldTool.GetFieldValue($i
tem,"Title")</div>'
$matchString = '$fieldTool.GetFieldValue($i'ntem,"Title")'
$pattern = $([regex]::escape($matchString))
$replaceString = "{{(sc_get_field_value i_item 'Title')}}"
$newtemplate = $template -replace $pattern, $replaceString
Write-Host $newtemplate
The above code is not working. How can I replace the string with line break with another string.
Any suggestion would be appreciated.
Thanks in advance
To replace newlines, you should use regex pattern \r?\n. This will match both *nix as well as Windows newlines.
In your template string however, there are multiple characters that have special meaning in regex, therefore you need to do [regex]::Escape(), but that also would wrongfully escape the characters \r?\n, rendering it as \\r\?\\n, so adding that in the $matchString before escaping it, would be of no use.
You can manually first replace the newline with a character that otherwise is not present in the $matchString and has no special meaning in regex.
$template = '<div class="tile-inspiration__title field-title">$fieldTool.GetFieldValue($i
tem,"Title")</div>'
# for demo, I chose to replace the newline with an underscore
$matchString = '$fieldTool.GetFieldValue($i_tem,"Title")'
# now, escape the string and after that replace the underscore by the wanted \r?\n pattern
$pattern = [regex]::escape($matchString) -replace '_', '\r?\n'
# $pattern is now: \$fieldTool\.GetFieldValue\(\$i\r?\ntem,"Title"\)
$replaceString = "{{(sc_get_field_value i_item 'Title')}}"
# this time, the replacement should work
$newtemplate = $template -replace $pattern, $replaceString
Write-Host $newtemplate # --> <div class="tile-inspiration__title field-title">{{(sc_get_field_value i_item 'Title')}}</div>

How to replace square brackets in powershell *[*

i want to replace a square bracket in powershell, to change the title.
my code:
if($finaltitlewithouterrors -like "*`[*`]") {
$finaltitlewithouterrors=$finaltitlewithouterrors.Replace("[", '')
}
i tried other schemas but none of them work, like
if($finaltitlewithouterrors -like "*`[*") {
$finaltitlewithouterrors=$finaltitlewithouterrors.Replace("`[", '')
}
i also tried it with
*``[*
i found a similar question (https://stackoverflow.com/questions/54094312/how-do-i-use-square-brackets-in-a-wildcard-pattern-in-powershell-get-childitem#:~:text=Square%20brackets%20can%20be%20used%20as%20a%20wildcard,and%20consequently%20the%20support%20in%20Powershell%20is%20spotty.)
but noting of it work.
for example i have a name called:
BatmanTheDarkNight[1].pdf
and the final name should look like:
BatmanTheDarkNight.pdf
or
BatmanTheDarkNight1.pdf
You need to escape the square bracket [ ] characters when using -replace. Here is a rough solution using [regex]::Escape
$fileName = "BatmanTheDarkNight[1].pdf"
$newFileName = $fileName -replace [Regex]::Escape("["), "" `
-replace [Regex]::Escape("]"), ""
$newFileName
BatmanTheDarkNight1.pdf
Note the use of a backtick to chain -replace operations on the next line.
Just use the regex -replace for this:
$finaltitlewithouterrors = 'BatmanTheDarkNight[1].pdf' -replace '[\[\]]'
# --> BatmanTheDarkNight1.pdf
Regex details:
[\[\]] Match a single character present in the list below
A [ character
A ] character

How do I replace the first occurrence of a period in a powershell string?

I have the following PowerShell:
$img="john.smith.jpg"
$img.Replace(".", "")
I'm trying to replace the first occurrence of a a period in the string.
At the moment it replaces all periods and returns: "johnsmithjpg"
The output I'm looking for is: "johnsmith.jpg".
I also tried the following but it doesn't work:
$img="john.smith.jpg"
[regex]$pattern = "."
$img.replace($img, "", 1)
What do I need to do to get it to only replace the first period?
From Replacing only the first occurrence of a word in a string:
$img = "john.smith.jpg"
[regex]$pattern = "\."
$img = $pattern.replace($img, "", 1)
Output:
Note for the pattern, . is treated as a wildcard character in regex, so you need to escape it with \
Other possibility without RegEx
$img="john.smith.jpg"
$img.Remove($img.IndexOf("."),1)
Seems to me that $img contains a filename including the extension. By blindly replacing the first dot, you might end up with unusable (file)names.
For instance, if you have $img = 'johnsmith.jpg' (so the first and only dot there is part of the extension), you may end up with johnsmithjpg..
If $img is obtained via the Name property of a FileInfo object (like Get-Item or Get-ChildItem produces),
change to:
$theFileInfoObject = Get-Item -Path 'Path\To\johnsmith.jpg' # with or without dot in the BaseName
$img = '{0}{1}' -f (($theFileInfoObject.BaseName -split '\.', 2) -join ''), $theFileInfoObject.Extension
# --> 'johnsmith.jpg'
Or use .Net:
$img = "johnsmith.jpg" # with or without dot in the BaseName
$img = '{0}{1}' -f (([IO.Path]::GetFileNameWithoutExtension($img) -split '\.', 2) -join ''), [IO.Path]::GetExtension($img)
# --> 'johnsmith.jpg'

Powershell - using variables in replace

I was using .replace until I discovered it is case sensitive.
So I am rewritng a line of code to use -replace instead.
Here is what is working, but is case sensitive:
$SourcePath = 'c:\scripts\test
$folder = 'c:\testing\test'
$sourceFullPath = 'c:\scripts\test\FolderToTest'
$sourceFileRelativePath = $sourceFullPath.Replace($SourcePath, "")
$destFullFilePath = $folder + $sourceFileRelativePath
Write-output $destFullFilePath
c:\testing\test\FolderToTest
How would I convert this to use -replace or is there a way to use the .net .replace case-insensitive?
Note: This section of code will be in a function so they will not be static. I put in examples for this post but they could be any file path.
Thanks!!
Unlike the Replace method which takes strings, the replace operator takes a regular expression pattern. $SourcePath needs to be escaped as it contains backslashes which are special regex characters.
$sourceFileRelativePath = $sourceFullPath -replace [regex]::escape($SourcePath)
$destFullFilePath = Join-Path $folder $sourceFileRelativePath

replace exception in powershell

I'm a beginner in powershell and know C# pretty well. I have this command http://www.f2ko.de/programs.php?lang=en&pid=cmd that downloads stuff. I'm writing this script to download all the sgf go games from this url http://www.gogameworld.com/gophp/pg_samplegames.php, and was trying to write a powershell script to do it for me. So I wrote a script:
Get-Content test.txt|
ForEach-Object
{
if($_ -eq "=`"javascript:viewdemogame(`'*.sgf`')`" tit")
{
$filename = $_ -replace '=`"javascript:viewdemogame(`''
$filename = $filename -replace '`')`" tit'
&"(Path)/download.exe" ("http://www.gogameworld.com/webclient/qipu/" + $filename)
}
}
However, when I run the script, I keep getting this error:
Unexpected token '`'' in expression or statement.
At (PATH)\test.ps1:7 char:37
+ $filename = $filename -replace '`' <<<< )'
+ CategoryInfo : ParserError: (`':String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I've looked at the script lots of times and still can't figure out whats wrong. Thanks.
Try this, read the content of the file as one string and then use the Regex.Matches to get all occurrences of the text contained in the parenthesis:
$content = Get-Content test.txt | Out-String
$baseUrl = 'http://www.gogameworld.com/webclient/qipu/'
[regex]::matches($content,"javascript:viewdemogame\('([^\']+)'\)") | Foreach-Object{
$url = '{0}{1}' -f $baseUrl,$_.Groups[1].Value
& "(Path)/download.exe" $url
}
here's an explanation of the regex pattern (created with RegexBuddy):
javascript:viewdemogame\('([^\']+)'\)
Match the characters “javascript:viewdemogame” literally «javascript:viewdemogame»
Match the character “(” literally «\(»
Match the character “'” literally «'»
Match the regular expression below and capture its match into backreference number 1 «([^\']+)»
Match any character that is NOT a ' character «[^\']+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “'” literally «'»
Match the character “)” literally «\)»
Match the character “"” literally «"»
'{0}{1}' is used with the -f operator to create a string. {0} maps to the first value on the right hand side of the operator (e.g $baseUrl) and {1} is mapped to the second value. Under the hood, PowerShell is suing the .NET String.Format method. You can read more about it here: http://devcentral.f5.com/weblogs/Joe/archive/2008/12/19/powershell-abcs---f-is-for-format-operator.aspx
'')" tit'
The -replace operator takes 2 arguments, comma separated. The first is a regular expression that matches what you want replaced. The second is the string you want to relace that with. You appear to be missing the second argument.