我在下面编写了脚本,以遍历目录中的文件,然后基于哈希表进行替换(哈希表实际上将包含30个键/值,而不是此处所示的4个)。这是一个非常大的目录,文件也有些大,所以我想确保对其进行尽可能的优化,但是我对Powershell的了解不够。是这样还是我需要重构,如果是,我应该怎么做?谢谢。
Get-ChildItem 'C:\temp' -Filter *.txt |
Foreach-Object {
$lookupTable = @{
'a' = '1'
'b' = '2'
'c' = '3'
'd' = '4'
}
$file = $_
Write-Host "$file"
(Get-Content -Path $file -Raw) | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key) {
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $file
}
答案 0 :(得分:2)
以下是一些经过测试的测试用例(
"ano, cosi bude jinak"
,而不是读取每个标量值)
$lookupTable = @{
'a' = '1'
'b' = '2'
'c' = '3'
'd' = '4'
}
'original approach ', ( Measure-Command {
for ( $i = 0; $i -lt 5000; $i++ ) { # get-childitem
$line = "ano, cosi bude jinak" # get-content
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key) {
$line = $line -replace $_.Key, $_.Value
}
}
$line
}
}).TotalSeconds, $line -join " "
'@mhu: without IF ', ( Measure-Command {
for ( $i = 0; $i -lt 5000; $i++ ) {
$line = "ano, cosi bude jinak"
$lookupTable.GetEnumerator() | ForEach-Object {
$line = $line -replace $_.Key, $_.Value
}
$line
}
}).TotalSeconds, $line -join " "
'HashTable -> Array', ( Measure-Command {
$lookupArrayCount = $lookupTable.Count
$lookupArray = New-Object 'array[]' $lookupArrayCount
$j = 0
$lookupTable.GetEnumerator() | ForEach-Object {
$lookupArray[$j] = @( $_.Key, $_.Value )
$j++
}
for ( $i = 0; $i -lt 5000; $i++ ) {
$line = "ano, cosi bude jinak"
for ( $j = 0; $j -lt $lookupArrayCount; $j++ ) {
$line = $line -replace $lookupArray[$j]
}
$line
}
}).TotalSeconds, $line -join " "
输出:
D:\PShell\SO\56587351.ps1
original approach 1,8059152 1no, 3osi 2u4e jin1k @mhu: without IF 1,5973162 1no, 3osi 2u4e jin1k HashTable -> Array 0,3225432 1no, 3osi 2u4e jin1k