Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Open all .txt filres in a directory, edit them, and save a new copy....All works but the save :(

$
0
0

I have a bunch of text files I need to edit and add a line of text to the middle of. I have been able to work out opening and editing the file however I am falling short on saving it with the correct name. Foreach and arrays are not something I have had to deal with a ton yet so any help is appreciated.

What happens when I run this is File1.txt is opened, edited and saved as File3.txt, File2.txt is saved as File1.txt, and File3.txt is saved as File1.txt. I imagine my problem has to do with how the foreach cmdltes are handing off the array, but I am unsure of how to fix it.

 

*Edit, found I copied an older version originally that didn't have the $outpath and $outfilename variables correctly defined.

 

$ContentDir = "C:\PSWorking\ldap"
$files = Get-ChildItem $ContentDir\*.txt

ForEach($file in $files){
$outpath = ($file.DirectoryName + "\new\")
$outfilename = ($outpath + $file.name)
$newcontent = Get-Content $file |
 
    ForEach-Object{
        if($_ -match ('^' + [regex]::Escape('FullName:')))
        {
             $_
                
            'AuthMethod:    ldap'
        }
        else
        {
            $_
        }
    $newcontent | Out-File -FilePath $outfilename
    }
}


Viewing all articles
Browse latest Browse all 6937

Trending Articles