在Powershell中Export-Csv中使用和不使用管道之间的区别 [英] Difference between using and not using pipe in Export-Csv in Powershell
问题描述
这可能更像是"PowerShell如何处理变量和管道"而不是特定的编程问题,但是由于(对我而言)这似乎是奇怪的行为,所以我想将其发布在这里.
This is probably more of a 'how does PowerShell handle variables and piping' rather than a specific programmatical question, but since it seems like strange behaviour (to me) I thought I'd post it here.
我在使用PowerShell将变量导出到CSV时遇到了一些困难,发现堆栈问题对我很有帮助.但是,在摆弄输出时,根据我如何调用 Export-CSV
函数
I just had some difficulties exporting a variable to a CSV using PowerShell and found this Stack question that helped me a lot. However, when fiddling around with the output I got two different results depending on how I called the Export-CSV
function.
我有一个大致如下所示的自定义PS对象:
I have a custom PS object that looks roughly like this:
Account Partner ProjectName ProjectPhase
1 A Test Start
2 B Test2 Start
3 A Test4 End
4 C Test3 Middle
....
当我使用以下行时,它会正确输出CSV文件:
When I use the following line it correctly outputs the CSV file:
$csvBody | Export-Csv -Path "$targetPath\$fileName" -Encoding Unicode -NoTypeInformation
但是,当我使用以下行时,它不会:
However, when I use the following line it doesn't:
Export-Csv -InputObject $csvBody -Path "$targetPath\$fileName" -Encoding Unicode -NoTypeInformation
在这种情况下,输出如下所示:计数,长度",长度",等级","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized"263,"263","263","1","System.Object []","False","True","False"
In this case, the output looks like this: Count,"Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized" 263,"263","263","1","System.Object[]","False","True","False"
我从其他Stack帖子了解到,输出变为$ csvBody的属性,它是一个数组.我的问题是,为什么当我不使用管道将对象传输到Export-CSV时会发生这种情况,而当我 am 使用管道时却不会发生这种情况?
I understand from this other Stack post that the output becomes the property of the $csvBody, which is an array. My question is why does this happen when I'm not piping the object to Export-CSV, but it doesn't happen when I am using the pipe?
推荐答案
在这里一切都按设计运行且写得不错:
Here everything works as design and not badly written :
第二种方式,输入对象是 #TYPE System.Object []
,如您所见,是否保留TypeInformation.
In the second way, the inputobject is a #TYPE System.Object[]
as you can see if you keep TypeInformation.
使用管道调用Export-Csv时,集合的每个对象都会发送到Cmdlet的进程部分.
When you call Export-Csv using the pipe, each object of the collection is sent to the process part of the Cmdlet.
获取整数集合:
$a = 1..4
然后尝试:
$a | Get-Member
它给出了: System.Int32
然后尝试:
Get-Member -InputObject $a
它给出: System.Object []
因此,在您的情况下,导出的对象是数组,也是很有用的.
So in your case the object exported is the array wich can be useful too.
这篇关于在Powershell中Export-Csv中使用和不使用管道之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!