查找和替换powershell

时间:2013-05-07 20:36:04

标签: powershell

我无法弄清楚我做错了什么。我希望它读取web.config文件find(< serverName>,ServerName或localhost)并替换为computername,然后再次保存该文件。我还想将驱动程序字母更改为脚本所在的当前驱动器。我知道我的代码很乱,但我根本没有脚本编写技巧。所以,如果你有任何关于清理它的建议,那会有所帮助。

$env:CD = (get-location).drive.root;
$env:CL = get-location

Get-Content ($env:cl\wwwroot\GBMain\Web.config) | ForEach-Object { $_ -replace "<serverName>", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBMain\Web.config)
Get-Content ($env:cl\wwwroot\GBMain\Web.config) | ForEach-Object { $_ -replace "ServerName", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBMain\Web.config)
Get-Content ($env:cl\wwwroot\GBMain\Web.config) | ForEach-Object { $_ -replace "localhost", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBMain\Web.config)
Get-Content ($env:cl\wwwroot\GBMain\Web.config) | ForEach-Object { $_ -replace "D:\", "$env:cd" } | Set-Content ($env:cl\wwwroot\GBMain\Web.config)
Get-Content ($env:cl\wwwroot\GBMain\Web.config) | ForEach-Object { $_ -replace "C:\", "$env:cd" } | Set-Content ($env:cl\wwwroot\GBMain\Web.config)

Get-Content ($env:cl\wwwroot\GBReporting\Web.config) | ForEach-Object { $_ -replace "<serverName>", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBReporting\Web.config)
Get-Content ($env:cl\wwwroot\GBReporting\Web.config) | ForEach-Object { $_ -replace "ServerName", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBReporting\Web.config)
Get-Content ($env:cl\wwwroot\GBReporting\Web.config) | ForEach-Object { $_ -replace "localhost", "$env:COMPUTERNAME" } | Set-Content ($env:cl\wwwroot\GBReporting\Web.config)
Get-Content ($env:cl\wwwroot\GBReporting\Web.config) | ForEach-Object { $_ -replace "D:\", "$env:cd" } | Set-Content ($env:cl\wwwroot\GBReporting\Web.config)
Get-Content ($env:cl\wwwroot\GBReporting\Web.config) | ForEach-Object { $_ -replace "C:\", "$env:cd" } | Set-Content ($env:cl\wwwroot\GBReporting\Web.config)

Exit

1 个答案:

答案 0 :(得分:3)

由于你没有说明错误,我只是快速浏览了一下。这是未经测试的,但我相信它应该有效。

首先,当您可以组合所有replace - 命令时,您正在执行多次读写操作。 Get-ContentSet-Content中使用的路径应该是字符串,因此请引用它们。只要文件很小,就应该在编辑和保存之前将内容存储在变量中。这是一种避免尝试写入仍在使用的文件(您正在阅读它)的简单方法。最后,-replace使用正则表达式,因此您需要转义\C:\中的D:\

$env:CD = (get-location).drive.root;
$env:CL = get-location

$cont = Get-Content "$env:cl\wwwroot\GBMain\Web.config" 
$cont | ForEach-Object { 
    $_ -replace "<serverName>", "$env:COMPUTERNAME" -replace "ServerName", "$env:COMPUTERNAME" -replace "localhost", "$env:COMPUTERNAME" -replace "C:\\", "$env:cd" -replace "D:\\", "$env:cd" } |
Set-Content "$env:cl\wwwroot\GBMain\Web.config"

$cont = Get-Content "$env:cl\wwwroot\GBReporting\Web.config"
$cont | ForEach-Object { 
    $_ -replace "<serverName>", "$env:COMPUTERNAME" -replace "ServerName", "$env:COMPUTERNAME" -replace "localhost", "$env:COMPUTERNAME" -replace "C:\\", "$env:cd" -replace "D:\\", "$env:cd" } |
Set-Content "$env:cl\wwwroot\GBReporting\Web.config"


#Exit is unnecessary. A PowerShell script exists when it's done.