replace string in multiple files within a folder.

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of random commandline random commandline 1 month ago.

  • Author
    Posts
  • #56762
    Profile photo of André Lange
    André Lange
    Participant

    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
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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
      Profile photo of André Lange
      André Lange
      Participant

      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
    Profile photo of random commandline
    random commandline
    Participant

    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.