PowerShell使用DataSet替换文件文本
我正在尝试在PowerShell中进行一些值替换。我有一个包含一般查询的文本文件,即PowerShell使用DataSet替换文件文本,powershell,powershell-3.0,Powershell,Powershell 3.0,我正在尝试在PowerShell中进行一些值替换。我有一个包含一般查询的文本文件,即 -- query.sql SELECT 'varTableName' AS myTableName , COUNT(DISTINCT parmColumnName) AS myDistinctCount , SUM(parmColumnName2) AS mySum FROM varDatabaseName.varSchemaName.varTableName WITH (NOLOCK
-- 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
}
}
$query = Get-Content query.sql
$MyDataRow | % {
$query = $query -replace "varDatabaseName", $_.DatabaseName `
-replace "varSchemaName", $_.SchemaName `
-replace "varTableName", $_.TableName
}
$MyOtherDataRow | % {
$query = $query -replace $_.SearchString, $_.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
欢迎任何意见。:) 我可能会这样做:
# 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
}
}
$query = Get-Content query.sql
$MyDataRow | % {
$query = $query -replace "varDatabaseName", $_.DatabaseName `
-replace "varSchemaName", $_.SchemaName `
-replace "varTableName", $_.TableName
}
$MyOtherDataRow | % {
$query = $query -replace $_.SearchString, $_.ReplaceString
}
谢谢你,安斯加!我感谢你的答复