-2

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

$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
4

1 回答 1

3

由于您没有指定问题所在,因此我只是快速浏览了所有内容。这是未经测试的,但我相信它应该有效。

首先,当您可以组合所有命令时,您正在执行多次读取和写入replaceGet-Content和中使用的路径Set-Content应该是字符串,所以引用它们。只要文件很小,您应该在编辑和保存之前将内容存储在变量中。这是一种避免尝试写入仍在使用中的文件(您正在阅读它)的简单方法。最后,-replace使用正则表达式,因此您需要转义\inC:\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.
于 2013-05-07T22:08:03.360 回答