2010-11-01 251 views
1

作爲一個巨大的重構的一部分,我刪除了一些重複的類和枚舉。我移動了命名空間並重構了一切,以便將來更容易維護。如何在使用PowerShell的文件中的特定行之後插入文本?

除了一件事情之外,所有更改都已經腳本化了。如果尚未插入數據協定名稱空間,則需要在每個使用其他名稱空間的文件中插入數據協定名稱空間。

我現在的代碼不起作用,但是我想我需要的就是這樣。

function Insert-Usings{ 
    trap { 
     Write-Host ("ERROR: " + $_) -ForegroundColor Red 
     return $false 
    } 
    (Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % { 
    $fileName = $_.FullName 
    (Get-Content $fileName) | 
     Foreach-Object 
     { 
      $_ 
      if ($_ -cmatch "using Company.Shared;") { 
        $_ -creplace "using Company.Shared;", "using Company.Common;" 
      } 
      elseif ($_ -cmatch "using Company") { 
       #Add Lines after the selected pattern 
       "using Company.Services.Contracts;" 
      } 
      else{ 
       $_ 
      } 
     } 
    } | Set-Content $fileName 
} 

編輯:的代碼往往輸出(覆蓋整個文件與 - ) 「使用Company.Services.Contracts」 語句。

+0

它失敗了嗎?什麼是錯誤信息?還是它做了與你想要的不同的東西? – 2010-11-01 08:09:25

+0

對不起原來的問題不夠清楚。我會更新一些更多的信息。 – mhenrixon 2010-11-01 08:11:14

回答

3

這是不是很清楚你究竟得到什麼,但我會嘗試猜測,看看我的代碼中的評論。我認爲原始代碼包含一些錯誤,其中一個是嚴重錯誤:Set-Content用於錯誤的管道/循環中。這是更正的代碼。

function Insert-Usings 
{ 
    trap { 
     Write-Host ("ERROR: " + $_) -ForegroundColor Red 
     return $false 
    } 
    (Get-ChildItem $base_dir -Include *.asmx,*.ascx,*.cs,*.aspx -Force -Recurse -ErrorAction:SilentlyContinue) | % { 
     $fileName = $_.FullName 
     (Get-Content $fileName) | % { 
      if ($_ -cmatch "using Company\.Shared;") { 
       # just replace 
       $_ -creplace "using Company\.Shared;", "using Company.Common;" 
      } 
      elseif ($_ -cmatch "using Company") { 
       # write the original line 
       $_ 
       # and add this after 
       "using Company.Services.Contracts;" 
      } 
      else{ 
       # write the original line 
       $_ 
      } 
     } | 
     Set-Content $fileName 
    } 
} 

例如,它取代了這一點:

xxx 

using Company.Shared; 

using Company; 

ttt 

與此:

xxx 

using Company.Common; 

using Company; 
using Company.Services.Contracts; 

ttt 

注:想必你應該將這個代碼並不適用於源不止一次,代碼不是爲此設計的。

+0

工程就像一個魅力!你能否詳細說明不是爲此設計的腳註。我可以做些什麼來使它更安全?該代碼不打算運行多次。這將是部署例程的一個步驟,每個客戶只能運行一次,但您是否看到了可以改進上述代碼的方法? – mhenrixon 2010-11-01 09:10:41

+1

如果您第二次運行此代碼,它將在使用公司後的*每行之後添加一些代碼。這將是錯誤的,因爲它已經在第一次運行中完成了。只是不要運行兩次 - 我認爲這是最簡單的解決方案。如果某些運行在中間失敗,然後丟棄/終止所有部分更改的源,則取原始文件,解決問題後再運行。 – 2010-11-01 09:20:28

+0

希望我可以給你更多積分以獲得有用的答案;) – mhenrixon 2010-11-01 09:26:58

相關問題