我正在尝试在PowerShell中进行一些值替换。我有一个包含通用查询的文本文件,即
-- query.sql
SELECT
'varTableName' AS myTableName
, COUNT(DISTINCT parmColumnName) AS myDistinctCount
, SUM(parmColumnName2) AS mySum
FROM varDatabaseName.varSchemaName.varTableName WITH (NOLOCK);
我正在尝试替换“var”和“parm”值。我有两个不同的数据行。在我的脚本中,我遍历第一个数据行并使用焦点行进行替换。这非常有效。我的问题是下一部分。然后,我需要遍历包含多行的第二个数据行,并对匹配的任何值执行替换。
我尝试做了类似的事情,但未成功:
# myScript.ps1 -- does not work
# ...
# Code here to populate $MyDataRow
ForEach ($MyRow In $MyDataRow) {
[string]$Query = Get-Content query.sql | ForEach-Object {
$_ -replace "varTableName", $Table `
-replace "varDatabaseName", $MyRow.DatabaseName `
-replace "varSchemaName", $MyRow.SchemaName `
-replace "varTableName", $MyRow.TableName
-replace $MyOtherDataRow.SearchString, $MyOtherDataRow.ReplaceString
}
}
然而,这有效:
# myScript.ps1 -- works
# ...
# Code here to populate $MyDataRow
ForEach ($MyRow In $MyDataRow) {
[string]$Query = Get-Content query.sql | ForEach-Object {
$_ -replace "varTableName", $Table `
-replace "varDatabaseName", $MyRow.DatabaseName `
-replace "varSchemaName", $MyRow.SchemaName `
-replace "varTableName", $MyRow.TableName
}
ForEach($MyOtherRow In $MyOtherDataRow) {
$Query = $Query | ForEach-Object {
$_ -replace $MyOtherRow.SearchString, $MyOtherRow.ReplaceString
}
}
}
我只是学习PowerShell,所以我不知道这是否是最有效的处理方法。我想知道我是否能够以某种方式将第二个ForEach替换为第一个结果?什么是最好的方法?
哦,如果相关,我正在使用PowerShell 3.0。
任何输入都表示赞赏。 :)
答案 0 :(得分:1)
我可能会这样做:
$query = Get-Content query.sql
$MyDataRow | % {
$query = $query -replace "varDatabaseName", $_.DatabaseName `
-replace "varSchemaName", $_.SchemaName `
-replace "varTableName", $_.TableName
}
$MyOtherDataRow | % {
$query = $query -replace $_.SearchString, $_.ReplaceString
}