Это должно работать лучше для вас:
$filePath = '<YOUR PATH HERE>'
$annotation = "[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"
Get-ChildItem -Path $filePath -Filter *.cs | ForEach-Object {
$file = $_.FullName
(Get-Content $file) | ForEach-Object {
# test all strings in $file
if ($_ -match "StartDateTime") {
# emit the annotation followed by the string itself
"`r`n`t`t$annotation`r`n" + $_
}
else {
# just output the line as-is
$_
}
} | Set-Content -Path $file -Force
}
В пределах Foreach-Object
я собираю $_.FullName
для последующего использования, а также чтобы не путать его с $_
, который вы используете позжекак строка в файле.Затем, если строка соответствует if
, выведите замененную строку, но если она не (в else
), вы должны вывести строку без изменений.Затем Set-Content
всегда выводит каждую строку, замененную или нет.
Поскольку вы фактически не заменяете что-либо внутри строки, а вместо этого добавляете к ней префикс с аннотацией, это можно немного упростить так:
$annotation = "[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"
Get-ChildItem -Path 'D:\' -Filter *.cs | ForEach-Object {
$file = $_.FullName
(Get-Content $file) | ForEach-Object {
# test all strings in $file
if ($_ -match "StartDateTime") {
# emit the annotation
"`r`n`t`t$annotation"
}
# output the line as-is
$_
} | Set-Content -Path $file -Force
}