title: Powershell - Speeding up writing to files
body: <p>I wrote this script to find all of the folders in a directory and for each folder, check inside a common file if some strings exist and if not add them. I needed to insert strings in particular places. Not really knowing how to do this, I opted for simpler find and replace where the strings needed to be inserted. Anyway this script takes almost an hour to work through 800 files. I'm hoping some experienced members can point out ways to make my task quicker as I have only been working with Powershell for two days. Many Thanks!!!</p>
  
  <pre><code># First find and replace items. 
  $FindOne = 
  $ReplaceOneA = 
  $ReplaceOneB = 
  $ReplaceOneC = 
  
  # Second find and replace items. 
  $FindTwo =
  $ReplaceTwo =
  
  # Strings to test if exist.
  # To avoid duplicate entries.
  $PatternOne = 
  $PatternTwo = 
  $PatternThree = 
  $PatternFour = 
  
  # Gets window folder names.
  $FilePath = "$ProjectPath\$Station\WINDOW"
  $Folders = Get-ChildItem $FilePath | Where-Object {$_.mode -match "d"}
  
  # Adds folder names to an array.
  $FolderName = @()
  $Folders | ForEach-Object { $FolderName += $_.name }
  
  # Adds code to each builder file.
  ForEach ($Name in $FolderName) {
  
  $File = "$FilePath\$Name\main.xaml"
  $Test = Test-Path $File
  
  # First tests if file exists. If not, no action.
  If ($Test -eq $True) {
  
  $StringOne = Select-String  -pattern $PatternOne -path $File 
  $StringTwo = Select-String  -pattern $PatternTwo -path $File 
  $StringThree = Select-String  -pattern $PatternThree -path $File 
  $StringFour = Select-String  -pattern $PatternFour -path $File
  
  $Content = Get-Content $File
  
  # If namespaces or object don't exist, add them.
  If ($StringOne -eq $null) {
  
  $Content = $Content -Replace $FindOne, $ReplaceOneA
  }
  
  If ($StringTwo -eq $null) {
  
  $Content = $Content -Replace $FindOne, $ReplaceOneB
  }
  
  If ($StringThree -eq $null) {
  
  $Content = $Content -Replace $FindOne, $ReplaceOneC
  }
  
  If ($StringFour -eq $null) {
  
  $Content = $Content -Replace $FindTwo, $ReplaceTwo
  }
  
  $Content | Set-Content $File
  
  }
  
  }
  
  # End of program.
  </code></pre>