andrelange91
andrelange91

Reputation: 1168

Loop through all files in folder with different file extensions

i am trying to loop through all files no matter the type, in a folder, and change a string with one that is input by the user..

i can do this now, with the code below, but only with one type of file extension..

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'

How do i loop through the files, no matter the extension ? so no matter if it is a md, txt or cshtml or some other, it will replace the string as instructed.

Upvotes: 2

Views: 502

Answers (1)

kim
kim

Reputation: 3421

To get all the files in a folder you can get use Get-ChildItem. Add the -Recurse switch to also include files inside of sub-folders.

E.g. you could rewrite your script like this

$path = 'c:\tmp\test'
$NewString = Read-Host -Prompt 'Input New Name Please'
$OldString  = 'SolutionName'

Get-ChildItem -Path $path  | where {!$_.PsIsContainer} | foreach { (Get-Content $_).Replace($OldString,$NewString) | Set-Content -Path $_.FullName }

this will first get all the files from inside the folder defined in $path, then replace the value given in $OldString with what the user entered in when prompted and finally save the files.

Note: the scripts doesn't make any difference regarding if the content of the files changed or not. This will cause all files modified date to get updated. If this information is important to you then you need to add a check to see if the files contains the $OldString before changing them and saving.

Upvotes: 2

Related Questions