Powershell 带有content.replace的嵌套foreach()循环未按预期设置内容(或添加内容)

Powershell 带有content.replace的嵌套foreach()循环未按预期设置内容(或添加内容),powershell,Powershell,我有下面的Powershell脚本,其中包含两个嵌套的foreach循环。 脚本应该从一个简单的SQL文件中获取内容,为表名添加前缀,并根据前缀/学生名写出新的SQL文件 $content = Get-Content "[PATH_FILE].sql" $students = @('18adadam','18bebert','18dadavi') # $students = Get-Content "[PATH_FILE].txt" $tables = @('image','post','use

我有下面的Powershell脚本,其中包含两个嵌套的foreach循环。 脚本应该从一个简单的SQL文件中获取内容,为表名添加前缀,并根据前缀/学生名写出新的SQL文件

$content = Get-Content "[PATH_FILE].sql"
$students = @('18adadam','18bebert','18dadavi')
# $students = Get-Content "[PATH_FILE].txt"
$tables = @('image','post','user')

foreach ($student in $students) {
  foreach ($table in $tables) {
    $tablename = $student + '_' + $table
    'Table name: ' + $tablename
    $content = $content.Replace("TABLE ``$table``","TABLE ``$tablename``") 
  } 
  $content | Set-Content ("$student.sql")
  'Content: '+ $content
}
文件按预期创建:

  • 18adadam.sql
  • 18bebert.sql
  • 18dadavi.sql
内部循环中变量$tablename的输出正常:

表名:18adadam_图像

表名:18adadam_邮政

表名:18adadam_用户

表名:18bebert_图像

表名:18bebert_邮政

表名:18bebert_用户

表名:18dadavi_图像

表名:18dadavi_邮政

表名:18dadavi_用户

但是写入文件(和控制台)的内容只包含第一个学生(18adadam)的更正表:

最初,行内容替换行如下所示:

$content = $content.Replace("TABLE ``$table``","TABLE ``$student" + "_" + "$table``")
我担心连接会在某种程度上破坏内容的编写,所以我将其更改为表名的单个变量

$tablename = $student + '_' + $table
$content = $content.Replace("TABLE ``$table``","TABLE ``$tablename``") 
我添加了

'Table name: ' + $tablename

作为简单的调试行,以查看脚本中每个点的情况

我还试着看看如下将输出更改为单个文件是否会改变任何内容:

  $content | Add-Content ("[PATH_FILE]_2.sql")

正如预期的那样,它所做的只是用正确的sql为18adam创建了一个文件,重复了三次。

第二次
$content.Replace(
将找不到原始值,因为它在$content中更改了。
将更改保存到其他变量

## Q:\Test\2018\10\11\SO_52758908.ps1
$content = Get-Content ".\template.sql"
$students = @('18adadam','18bebert','18dadavi')
# $students = Get-Content "[PATH_FILE].txt"
$tables = @('image','post','user')

foreach ($student in $students) {
  $Newcontent = $content
  foreach ($table in $tables) {
    $tablename = "{0}_{1}" -f $student,$table
    'Table name: ' + $tablename
    $Newcontent = $Newcontent.Replace("TABLE ``$table``","TABLE ``$tablename``")
  }
  $Newcontent | Set-Content ("$student.sql")
  'Content: '
  $Newcontent
}

Doh!谢谢你!我以为这是类似的事情。但我无法准确地指出我到底出了什么问题。
  $content | Add-Content ("[PATH_FILE]_2.sql")
## Q:\Test\2018\10\11\SO_52758908.ps1
$content = Get-Content ".\template.sql"
$students = @('18adadam','18bebert','18dadavi')
# $students = Get-Content "[PATH_FILE].txt"
$tables = @('image','post','user')

foreach ($student in $students) {
  $Newcontent = $content
  foreach ($table in $tables) {
    $tablename = "{0}_{1}" -f $student,$table
    'Table name: ' + $tablename
    $Newcontent = $Newcontent.Replace("TABLE ``$table``","TABLE ``$tablename``")
  }
  $Newcontent | Set-Content ("$student.sql")
  'Content: '
  $Newcontent
}