Powershell - ускорение записи в файлы

Я написал этот сценарий, чтобы найти все папки в каталоге и для каждой папки проверить внутри общего файла, существуют ли некоторые строки, и если нет, добавить их. Мне нужно было вставить строки в определенных местах. Не зная, как это сделать, я выбрал более простой поиск и замену там, где нужно было вставить строки. В любом случае, для работы с 800 файлами этот скрипт занимает почти час. Я надеюсь, что некоторые опытные участники смогут указать способы ускорить выполнение моей задачи, поскольку я работаю с Powershell всего два дня. Большое спасибо!!!

# 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.

1 ответ

Вы можете попробовать записать в файл поток

$stream = [System.IO.StreamWriter] $File
$stream.WriteLine($content)
$stream.close()
Другие вопросы по тегам