2009-10-27 68 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