Replace string in multiple files in powershell

Hi Team,

I have a requirement to replace a string in multiple files in a directory and also I would like to capture the file names that have been modified only but not all the file names in a directory.

Appreciate your support.

@Navya_Budagam

Welcome to forums

You want to make this using Powershell? Or using UiPath

Also please clarify which type of file you are dealing

It’s better if you share some sample files and required output

This will understand your issue and give correct solution

Thanks,
Srini

@Navya_Budagam

Welcome to the community

When you say modified how do you know a file si modifed? do you have any item that you can check?

because you can get modified time…from file and one method is to check if creation time and lastwritetime is same then file is ideally not modified…but again if the file is modifed again we cannot find using this

Directory.Getfile(“Folderpath”) will give yout he list of files in a folder

Hope this helps

cheers

Hi Srini, I want to replace a string in .txt file

Hi Anil, Attached script replaces string in multiple files but at the same time it is updating timestamp for all the files. So it is difficult to capture file names based on last timestamp.

This is by using powershell.

@Navya_Budagam

Is it ok if we do the same with UiPath then we can store the files as well which are modified…because in power shell you are not storing them…or either store all those files names as well where it is modified

For each file in folder

  1. Read Text file
    2 . If condition to check
  2. Replace on then side and save fielname
  3. On Else side do nothing

This way you can replace and also save the files which are modified

Hope this helps

cheers

If possible, could you please share the sample script to replace string values in powershell?

@Navya_Budagam

In your powershell ypu already have relace…what you need is getting to save the filenames

Better convert to UiPath…it wuld be more readable…if using UiPath no point going with powershell for this

Cheers

Thank you Anil, but at this moment I’m looking for the solution in powershell.

Hi

Welcome to UiPath community

Hope this script would help you

$directory = “C:\path\to\directory”
$searchPattern = “.”
$oldString = “oldString”
$newString = “newString”

$modifiedFiles = @()

Get-ChildItem -Path $directory -Include $searchPattern -Recurse |
ForEach-Object {
if ($_ -is [System.IO.FileInfo]) {
$content = Get-Content $.FullName
if ($content -match $oldString) {
$modifiedContent = $content -replace $oldString, $newString
Set-Content $
.FullName $modifiedContent
$modifiedFiles += $_.FullName
}
}
}

$modifiedFiles | Out-String -Stream

In UiPath, you can use the Invoke PowerShell activity to execute this script. The modified file names will be stored in the modifiedFiles variable, which you can access later in your workflow.

Cheers @Navya_Budagam

Thank you @Palaniyappan

I ran the attached script, but it is not replacing anything. Do you see any issues with the script?

Can u paste the script here so that I can try it out

@Navya_Budagam

Thank you @Palaniyappan

Here is the script…

$directory=“C:\Users\Desktop\powershell”

$searchpattern=“.”

$oldstring= “India”

$newstring= “America”

$modifiedfiles= @()

get-childitem -path $directory -Include $seachpattern -Recurse | Foreaxh-object {

If($_ -is [System.IO.Fileinfo]) {

$content=get-content $.Full Name if($content -match $oldstring) {

$modifiedcontent=$content -replace $oldstring,$newstring

Set-content $.FullName $modifiedcontent

$modifiedfiles +=$_.FullName

}}}

$modifiedfiles | out-string -stream

@Navya_Budagam

Can you please try this

$directory = "C:\Users\Desktop\powershell"
$searchpattern = "*.*"
$oldstring = "India"
$newstring = "America"
$modifiedfiles = @()

Get-ChildItem -Path $directory -Include $searchpattern -Recurse | ForEach-Object {
    if($_.GetType().Name -eq "FileInfo") {
        $content = Get-Content $_.FullName
        if($content -match $oldstring) {
            $modifiedcontent = $content -replace $oldstring, $newstring
            Set-Content $_.FullName $modifiedcontent
            $modifiedfiles += $_.FullName
        }
    }
}

$modifiedfiles | Out-String -Stream

Cheers

Hi @Navya_Budagam

Try these steps-

  1. Use Directory.GetFiles activity in UiPath to get a list of all the files in the directory that you want to search and replace the string in.
  2. Loop through the array of files using a For Each loop activity in UiPath.
  3. Inside the loop, use the Read Text File activity in UiPath to read the contents of the current file.
  4. Use the Replace method in UiPath to replace the desired string with the new string in the contents of the file. Store the modified contents in the same string variable.
  5. Use the Write Text File activity in UiPath to write the modified contents back to the same file. Provide the file path and the modified contents as inputs to the activity.
  6. Add a condition to check if the contents of the file were actually modified. You can use the String.Equals method in UiPath to compare the contents of the file before and after the replacement. If they are not equal, then the file was modified.
  7. If the file was modified, add the file name to a list or any other data structure to capture the file names that have been modified.
  8. Continue the loop until all the files in the directory have been processed.
  9. After the loop, you can access the list of modified file names and use it for further processing as needed.

Thanks!!

1 Like

Excellent @Anil_G
Now I’m able to capture the file names that have been modified. Appreciate your support.

I have found an issue while running this script on a number files in windows file system.
For ex: I have a file name called utility+team+[old±+retired+7%2f15%2f2016] and looks like script is not able to recognize these kind file names and getting below error. I believe file name is a valid one otherwise Windows would have thrown an error while creating the file.

Any thoughts?

Get-Content : An object at the specified path
"C:\Users\Desktop\powershell\replace\utility+team+[old±+retired+7%2f15%2f2016].txt does not exist, or has been filtered
by the -Include or -Exclude parameter.
At line:11 char:20

  •     $content = Get-Content $_.FullName
    
  •                ~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (System.String:String) [Get-Content], Exception
    • FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand
1 Like

Thank you @Nitya1 for responding to this post. The solution shared by @Anil_G is working fine.

Appreciate your support.

1 Like

@Navya_Budagam

Can you try this…I changed path to literalpath which would try for special characters as well

$directory = "C:\Users\Desktop\powershell"
$searchpattern = "*.*"
$oldstring = "India"
$newstring = "America"
$modifiedfiles = @()

Get-ChildItem -LiteralPath $directory -Include $searchpattern -Recurse | ForEach-Object {
    if($_.GetType().Name -eq "FileInfo") {
        $content = Get-Content -LiteralPath $_.FullName
        if($content -match $oldstring) {
            $modifiedcontent = $content -replace $oldstring, $newstring
            Set-Content -LiteralPath $_.FullName $modifiedcontent
            $modifiedfiles += $_.FullName
        }
    }
}

$modifiedfiles | Out-String -Stream

Hope this helps

Cheers

Hi @Anil_G

Much appreciated your continuous support.

Could you please assist on the below issues?

Scenario-1: -LiteralPath is accepting files having special characters in the name, but it introduced another bug

Currently “PowerShell” directory contains 3 files .txt, .xml and .atr
I have modified the script to exclude .atr files, So I have updated below 2 lines in the script…

$searchpattern = “*.atr”
and
Get-ChildItem -LiteralPath $directory -Exclude $searchpattern -Recurse | ForEach-Object {

Before placing -LiteralPath parameter, the script was excluding .atr files but after placing -LiteralPath it is not excluding .atr files and replacing the text if a match found in .atr files.

$directory = “C:\Users\Desktop\PowerShell”
$searchpattern = “*.atr”
$oldstring = “India”
$newstring = “America”
$modifiedfiles = @()

Get-ChildItem -LiteralPath $directory -Exclude $searchpattern -Recurse | ForEach-Object {
if($.GetType().Name -eq “FileInfo”) {
$content = Get-Content -LiteralPath $
.FullName
if($content -match $oldstring) {
$modifiedcontent = $content -replace $oldstring, $newstring
Set-Content -LiteralPath $.FullName $modifiedcontent
$modifiedfiles += $
.FullName
}
}
}

$modifiedfiles | Out-String -Stream

Scenario-2: How can we replace multiple string values with in the file. for example,

runAs=“India” → runAs=“America”
and
runAsGuid=“India” → runAsGuid=“America”