Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell Read File, search $$I and Replace, write file?

cane someone Help me a bit.
I want to read a Text file, Search for $$I and replace it with the current Dir Name, Then write the file again.
Well something does not work 🙁

$content = [IO.File]::ReadAllText("CC.comp")
$content = $content -replace '$$I','Split-Path -Path (Get-Location) -Leaf'
Print $content
pause

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-replace uses regex and $ is a special regex character which needs to be escaped with \ if you want to match it literally:

'$$I' -replace '$$I', 'test'    # Nothing is replaced
'$$I' -replace '\$\$I', 'test'  # Outputs 'test'

However, much easier is to use the .Replace method for literal replacement, no escaping is needed:

(Get-Content CC.comp -Raw).Replace('$$I', (Split-Path $pwd -Leaf)) |
    Set-Content CC.comp
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading