2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i get an error when it tries to mess with the folder, i have.. it shouldn't touch any folders. and should only touch files within the folder the powershell file is in.
I updated the script to make sure there are only files (no folder) among the returned result.
Awesome! Happy to be helpful :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.