2013-03-28 61 views
0

我有一個Powershell腳本,在其中放棄了一些C#代碼。該代碼執行文件的正則表達式搜索,如果它找到匹配項,則將其寫入到返回給Powershell進行進一步處理的數據表中。一切工作正常,直到我添加了StreamWriter writeline。一旦我這麼做,劇本就會徹底炸燬。這是代碼片段。我已經標出了打破劇本的路線。任何想法爲什麼這可能發生在這裏?如果我註釋掉該行,該腳本可以正常工作。PowerShell StreamWriter中的C#

Regex reg = new Regex(regex); 
using (StreamReader r = new StreamReader(SFile)) 
{ 
    string revisedfile = FileName.txt 
    string line;     
    while ((line = r.ReadLine()) != null) 
    { 
     using (StreamWriter writer = new StreamWriter(revisedfile, true)) 
     {       
      // Try to match each line against the Regex. 
      Match m = reg.Match(line); 
      if (m.Success) 
      { 
       DateTime result; 
       if (!(DateTime.TryParse(m.Groups[0].Value, out result))) 
       { 
        // add it to the DT        
        MatchTable.Rows.Add(x, m.Groups[0].Value, line); 

        // write it to the "revised" file 
        writer.WriteLine(reg.Replace(line, match => DateTime.Now.ToString("MM-dd-yyyy"))); // this is the line that blows it up 
       } 
+1

你能定義「炸彈」嗎?是否顯示特定的錯誤消息? – Icemanind

+0

如果我在Visual Studio中運行代碼,代碼運行時沒有任何錯誤。如果我在Powershell中運行代碼,則什麼都不會發生。 ISE立即返回「完成」並且不生成輸出日誌文件。 – mack

回答

1

今天遇到同樣的問題。 。StreamWriter的不使用PowerShell是在當前目錄默認情況下,StreamWriter的創建在該命令返回的目錄中的文件:

[IO.Directory]::GetCurrentDirectory() 

這將返回目錄的PowerShell被打開了,而不是目錄該腳本正在運行。最好的辦法得到這個工作,我所用的方法,就是把這個作爲腳本的第一行:

[IO.Directory]::SetCurrentDirectory($pwd) 

這將直接StreamWriter的文件輸出到當前工作目錄。您可以將$ pwd替換爲您希望的任何其他目錄,但請記住,如果它是相對目錄,則該文件將被放置在與getcurrentdirectory返回的目錄相關的目錄中。

PHEW!