replace string in multiple files within a folder.

This topic contains 3 replies, has 3 voices, and was last updated by  random commandline 1 year, 8 months ago.

  • Author
  • #56762

    André Lange

    hi, im new to powershell, but i wanna create a program that can replace a string with what a user will input within multiple different files.

    this is my code:

    $NewString = Read-Host -Prompt 'Input New Name Please'
    $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
    $InputFiles = Get-Item "$scriptPath\*.md"
    $OldString  = 'SolutionName'
    $InputFiles | ForEach {
        (Get-Content -Path $_.FullName).Replace($OldString,$NewString) | Set-Content -Path $_.FullName
    echo 'Complete'

    but it will only change a certain file, how do i make it look through all files in the folder it is in, and change the oldstring with the newstring ?

    This was my solution

    # Path of the current folder
    $path = split-path -parent $MyInvocation.MyCommand.Definition
    #input from user, to replace with.
    $NewString = Read-Host -Prompt 'Input New Name Please'
    #What to replace
    $OldString  = '%SolutionName%'
    #find all items, go through them and make the changes.
    Get-ChildItem -Path $path  | where {!$_.PsIsContainer} | foreach { (Get-Content $_).Replace($OldString,$NewString) | Set-Content -Path $_.FullName }
    echo 'Action is complete '
  • #56773

    Rob Simmers

    Try using Get-ChildItem versus Get-Item. Get-Item is a single item versus Get-ChildItem is a collection of items matching a search. If you need to search subfolders, you can use the -Recurse switch

    • #56774

      André Lange

      i have got it to loop through all files in the folder with forexample .md as file extension, but it ignores all the other files...

      will this do that ?

  • #56801

    random commandline

    Use -Whatif to display results without changing names.

    Get-ChildItem -Path \\path\to\folder -Filter *.md -Recurse | 
    Rename-Item -NewName {$_.Name -replace "$old","$new"} -WhatIf

You must be logged in to reply to this topic.