在ps1文件中搜索并删除一些行

时间:2013-09-23 11:30:39

标签: powershell

我正在从共享中复制一个文件,我正在尝试搜索一行代码,然后删除一些代码行&然后使用相同的名称再次保存文件。

假设我在myconfig.ps1文件中有以下内容

WriteHost("My operations");
WriteHost("My Object Creation");
$mytmp.NewObjectCreation($myobj1);
$mytmp2.NewObjectCreation($myobj2);
WriteHost("My Object Creationcompleted");
WriteHost("My operations completed");

输出文件应与原始文件i,e,myconfig.ps1和内容同名,如下所示

WriteHost("My operations");
WriteHost("My Object Creation");
WriteHost("My Object Creationcompleted");
WriteHost("My operations completed");

我在下面尝试过一个声明,它不起作用:

$s1 = [regex]::escape("$mytmp.NewObjectCreation($myobj1);")
$c1 = [regex]::escape("#$mytmp.NewObjectCreation($myobj1);")


Get-Content $originalbuildspecfile | ForEach-Object {
    $_ - $s1, $c1 
    } | Set-Content ($originalbuildspecfile )

1 个答案:

答案 0 :(得分:3)

您可以使用get-content来阅读文件的内容,在某些情况下将每行传送到where-object,然后使用set-content再次保存。 如果您要写入正在读取的同一文件,则必须将内容保存在变量中,否则您将收到错误消息,指出该文件已被使用。

例如:

PS> $file = "c:\temp\myconfig.ps1"
PS> $content = get-content $file | where {-not $_.StartsWith('$') }
PS> set-content $file -Value $content

此示例将检查“myconfig.ps1”中的每一行,并仅在变量$content中放入不以“$”开头的行。 第三行将获取存储在$content中的值,并将其放入'myconfig.ps1'。

请注意,如果源文件位置与目标文件位置不同,则可以在一行中执行此操作,如下所示:

PS> get-content "c:\temp\myconfig.ps1" | where {-not $_.StartsWith('$') } | set-content "c:\other_location\myconfig.ps1"

希望这有帮助。