jshabazz
jshabazz

Reputation: 23

Writing content to files with "foreach" loop in powershell

TASK: Need to update all files in a directory with new information. First we find the content then replace it in all files.

ISSUES: When updating the files, the data from other files is appended to the next file.

EXAMPLE:

Original file content:

file1

net use /persistent:no

net use p: \\houfilesvr01\company

net use s: \\houfilesvr01\shared

file2

net use /persistent:yes

net use T: "\\houfilesvr01\advanced pharmacy"

net use R: "\\houfilesvr01\Advanced Pharmacy\Account MGMT"

net use S: "\\houfilesvr01\Advanced Pharmacy\Implementation"

Post update content:

File1 & file2

net use /persistent:yes

net use T: "\\aps.local\advanced pharmacy"

net use R: "\\aps.local\Advanced Pharmacy\Account MGMT"

net use S: "\\aps.local\Advanced Pharmacy\Implementation"

net use /persistent:no

net use p: \\aps.local\company

net use s: \\aps.local\shared

The desired changes are being made, but the changes are being written to each file. We do not want that!


<# Variable Declaration  
$find - Values to replace
$replace - replacemtn values
$filepath - path of files
$content - content of existing files
$newcontent - updated content to write back to file 
#>
<# Variable Assignment #>
    $find = "houfilesvr01"
    $replace = "aps.local"
    $filepath = "C:\Users\jshabazz\Documents\Area51\logonscripttesting\Testfiles\*.*"
    
<# execution #>
    
    foreach($file in $filepath)
        {
             $content = get-content $file
             $newcontent = $content -replace 'houfilesvr01', 'aps.local'
             set-content -Path $filepath -value $newcontent
             
        }

Upvotes: 1

Views: 1182

Answers (1)

mklement0
mklement0

Reputation: 437198

foreach($file in Get-ChildItem $filepath) {
  $content = get-content $file.FullName
  $newcontent = $content -replace 'houfilesvr01', 'aps.local'
  set-content -Path $file.FullName -value $newcontent           
}

Note: Using the .FullName property is the safe thing to do in Windows PowerShell, where the System.IO.FileInfo instances output by Get-ChildItem situationally stringify to only file names. In PowerShell (Core) v7+ this is no longer necessary, because unconditional full-path stringification is now ensured.


As for what you tried:

  • Since $filepath is just a string, foreach($file in $filepath) doesn't enumerate anything, it essentially just copies that string to variable $file.

  • Both Get-Content and - perhaps more surprisingly - also Set-Content directly accept wildcard paths as their (positionally) implied -Path arguments, in which case they read from / write to all matching files.

Upvotes: 3

Related Questions