replace string in multiple files within a folder.

Welcome Forums General PowerShell Q&A replace string in multiple files within a folder.

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
1 year, 11 months ago.

  • Author
    Posts
  • #56762

    Participant
    Points: 0
    Rank: Member

    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 ?

    EDIT:
    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

    Participant
    Points: 0
    Rank: Member

    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

      Participant
      Points: 0
      Rank: Member

      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

    Participant
    Points: 0
    Rank: Member

    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
    

The topic ‘replace string in multiple files within a folder.’ is closed to new replies.