2009-10-27 88 views
2

我想檢索文件的內容,過濾並修改它們並將結果寫回文件。我這樣做:Powershell:將對象[]輸出到文件

PS C:\code> "test1" >> test.txt 
PS C:\code> "test2" >> test.txt 
PS C:\code> $testContents = Get-Content test.txt 
PS C:\code> $newTestContents = $testContents | Select-Object {"abc -" + $_} 
PS C:\code> $newTestContents >> output.txt 

output.txt中包含

"abc -" + $_                           
------------                           
abc -test1                            
abc -test2    

與第一行是怎麼回事?這幾乎就像foreach返回一個IEnumerable - 但是$ newTestContents.GetType()顯示它是一個對象數組。那麼是什麼給了?如何在沒有奇怪標題的情況下正常輸出數組。如果

而且獎勵積分,你能告訴我爲什麼$ newTestContents [0]的ToString()是一個空字符串

回答

2

使用的ForEach,而不是選擇-對象

+0

究竟如何將我使用的foreach創建轉換? – 2009-10-27 19:37:52

+0

George,..使用相同的代碼..但用ForEach替換Select-Object。它應該沒有任何其他修改。 – Nestor 2009-10-27 19:44:45

+0

啊,好的,謝謝。我想從C#LINQ的角度來看,ForEach是一個無效的返回 – 2009-10-27 19:56:26

3

而且獎勵積分,如果你能告訴我爲什麼$ newTestContents [0]的ToString()是一個空字符串

如果你看一下它的類型,它是一個PSCustomObject如

PS> $newTestContents[0].GetType().FullName 
System.Management.Automation.PSCustomObject 

如果你看看PSCustomObject的ToString()的反射IMPL你看到這一點:

public override string ToString() 
{ 
    return ""; 
} 

爲什麼這樣做,我不知道。但是,它可能是更好的使用字符串類型強制在PowerShell中如:

PS> [string]$newTestContents[0] 
@{"abc -" + $_=abc -test1} 

也許你正在尋找這樣的結果雖然:

PS> $newTestContents | %{$_.{"abc -" + $_}} 
abc -test1 
abc -test2 

這表明,當你使用選擇,對象用一個簡單的腳本塊中該腳本塊的內容形成創建的PSCustomObject上的新屬性名稱。在一般情況下,內斯特的做法是去,但在未來,如果你需要synthensize這樣的屬性,然後使用一個哈希表,像這樣的方式:

PS> $newTestContents = $testContents | Select @{n='MyName';e={"abc -" + $_}} 
PS> $newTestContents 

MyName 
------ 
abc -test1 
abc -test2 


PS> $newTestContents[0].MyName 
abc -test1