[ character in powershell - scripting

I'm using Powershell for replace a string in a text file.
For replace String 1 to String 2 in file.txt I use
(Get-Content file.ps1) | Foreach-Object { $_ -replace 'String 1', 'String 2'} | Set-Content file.txt
It works pretty well even with for replace characters like - and #
It need to replace a string with the [ character but it doesn't work. I need to replace -state [VMstate]::stopped with -state stopped but it doesn't work with
(Get-Content TEMP_config.ps1) | Foreach-Object { $_ -replace '-state [VMstate]::stopped', '-state stopped'} | Set-Content TEMP_config.ps1
How can i find the [ char?

The replace operator uses regular expressions to match text. One way to search for literal text is to escape the search text:
$search = [regex]::escape('[MyText]')
(Get-Content file.ps1) | Foreach-Object { $_ -replace $search , 'String 2'} | Set-Content file.txt

You just have to escape the [:
$_ -replace '-state \[VMstate]::stopped', '-state stopped'
Or use [Regex]::escape if you are not sure what to escape

You can use "\[" instead of "[" (prefixed with a backslash) to escape the [ character

Related

Script to replace string of text at a end of a line

I would like to modify this script if possible:
((Get-Content -path "C:\Users\User1\OUT\Summary.txt" -Raw) -replace '</ab></cb>','</x>') | Set-Content -Path "C:\Users\User1\OUT\Summary.txt"
I would like a script that will run with Windows OS to search through one file it finds at this path:
C:\Users\User1\File\Summary.txt
And within that file, when it finds data starting with: <a><b>Data
And at the same time ending with: </ab></cb>
It would need to change the ending to: </x>
And it would need to save the file without changing the name of the file.
For instance a line showing this data:
<a><b>Data:</y> 12345678</ab></cb>
Would be changed to:
<a><b>Data:</y> 12345678</x>
The PowerShell script above will find all instances of </ab></cb> and replace it with </x>, which is not what I am hoping to accomplish.
You can use Get-Content to process the file line be line and only do the Replace when you have a Match on <a><b>. Something like this:
$InFile = ".\TestIn.txt"
$OutFile = ".\TestOut.txt"
If (Test-Path -Path $OutFile) {Remove-Item $OutFile}
Get-Content $InFile | ForEach-Object -Process {
$NewLine = $_
If ($_ -Match '<a><b>') {
$NewLine = ($_ -Replace '</ab></cb>','</x>')
}
Add-Content $OutFile $NewLine
}

PowerShell v5 UTF8 format lost after conversion CR LF to LF

I'm using a vba macro to write a PS1 script in order to :
first convert my txt file to UTF8 format
Second, convert CR LF to LF.
But when I do so, i'm loosing the UTF8 format.
Here is my code :
$file = 'C:\Users\c92434\Downloads\run_param_21_04_21\dg_poc_parameter.txt'
(Get-Content $file) | Out-File -Encoding UTF8 $file
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
Best regards,
Jouvzer
You can do this in one go:
$file = 'C:\Users\c92434\Downloads\run_param_21_04_21\dg_poc_parameter.txt'
(Get-Content -Path $file -Raw) -replace '\r?\n', "`n" | Set-Content -Path $file -NoNewline -Encoding UTF8
The -Raw switch on Get-Content reads the file as one single, multilined string.
The -replace '\r?\n', "`n" replaces all CRLF into LF

POWERSHELL: making a literal string out of a expanded string

I have a string that I build from a couple sources to do matching with later, the short of my code so far is:
$temp = "some\good"
if("some text" -match $temp)
My representation of $temp is simple but actually it is built, this is an example of how it can get built, so no, in this case changing " for ' to pass a literal to $temp won't work. If I hard code the if to use a literal string version of $temp, it works so its a matter of converting the value in $temp to a literal string.
I get the following error when I run my code:
parsing "some\good" - Unrecognized escape sequence \g.
At [not important]
+ if($temp2 -match $temp)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
"Converting to literal string" won't help you here. String is a string, it only matters how it's being used, i.e. if the content is being interpreted in some way.
-match operates on regex, and that's it, you can't change that, you'd have to escape every all characters that have a meaning in regex.
But you can use select-string instead, which has a switch for simple matching:
$text = "some text"
$patt = "some\good"
if (($text | Select-String -SimpleMatch -Pattern $patt | Measure-Object).count -gt 0) {
Write-Host "match"
} else {
Write-Host "nomatch"
}

Read var directly from csv

Is it possible to read a variable directly by loading a csv?
My csv looks like this:
Var,Path
$SrcHost,\\computer
Is there a possibility to import-csv and put the path into the var?
import-csv test3.csv | foreach-object {
iex "$($_.var) = ""$($_.path)"""
}
You can also use new-variable (nv):
import-csv csvfile.csv | % { nv -name ($_.var) -value ($_.path) }
However to make this work you have to:
remove the $ from the source csv
or, trim $ as described by the comments below
or, select your variable as ${$srchost}
How bout this:
Get-Content -Path test.csv | Select-Object -Skip 1 | ForEach-Object { $_.Replace(",", "=`"") +
"`"" } | Invoke-Expression

How do I concatenate strings with variables in PowerShell?

I'm trying to build a file path in PowerShell and the string concatenation seems to be a little funky.
I have a list of folders:
c:\code\MyProj1
c:\code\MyProj2
I want to get the path to a DLL file here:
c:\code\MyProj1\bin\debug\MyProj1.dll
c:\code\MyProj2\bin\debug\MyProj2.dll
Here's what I'm trying to do:
$buildconfig = "Debug"
Get-ChildItem c:\code | % {
Write-Host $_.FullName + "\" + $buildconfig + "\" + $_ + ".dll"
}
This doesn't work. How can I fix it?
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config is not a valid variable name.
$.FullName should be $_.FullName
$ should be $_.Name
You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.
Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}
(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
This will get all dll files and filter ones that match a regex of your directory structure.
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'}
If you just want the path, not the object you can add | select fullname to the end like this:
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'} | select fullname