Powershell - 加快写入文件

时间:2015-02-18 15:55:18

标签: performance powershell replace find

我编写了这个脚本来查找目录和每个文件夹中的所有文件夹,如果存在某些字符串,则检查公共文件内部,如果不添加它们。我需要在特定的地方插入字符串。我不知道如何做到这一点,我选择了更简单的查找和替换需要插入字符串的位置。无论如何,这个脚本花了将近一个小时来处理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 个答案:

答案 0 :(得分:0)

您可以尝试使用流写入文件,例如

$stream = [System.IO.StreamWriter] $File
$stream.WriteLine($content)
$stream.close()