powershell - 使用 select-object @{name="Name"; 时出现问题 表达式=$变量}
问题描述
我试过这样的东西,但它从来没有给出值,我的 ifile.csv 包含两列显示名称,grpmail
Import-Csv "E:\ifile.csv" | foreach {get-distributionGroupMember -Identity $_.displayname | select-Object @{Name= GroupName; Expression = {$_.grpmail}}, Recipienttype, Primarysmtpaddress} | Export-csv -no typeinformation "E:\Ofile.csv"
谁能告诉我我做错了什么我期待ofile.csv有3列作为GroupName,Recipienttype,Primarysmtpaddress
我得到 Recipienttype、Primarysmtpaddress 列的值,但 GroupName 列始终为空。
解决方案
这是因为您$_
的管道已更改为您的结果,get-distributiongroupmember
不再是您的 CSV 文件输入。
试试这个:
Import-Csv "E:\ifile.csv" | foreach {
$gname = $_.grpmail
Get-distributionGroupMember -Identity $_.displayname | Select @{Name= GroupName; Expression = {$gname}}, Recipienttype, Primarysmtpaddress} | Export-csv -no typeinformation "E:\Ofile.csv"
我刚刚将第 2 行和第 3 行分开以使其更易于阅读 - 如果您愿意,可以在后面加上分号$gname = $_.grpmail
。
作为一般说明,我喜欢为管道对象分配特定的变量名称,以查看我实际使用的内容,特别是如果它们正在被转换。另外,我喜欢使用多行来更好地了解正在发生的事情
foreach ($g in (Import-Csv "E:\ifile.csv")) {
Get-distributionGroupMember -Identity $g.displayname |
Select @{Name= GroupName; Expression = {$g.grpmail}},Recipienttype,Primarysmtpaddress
} | Export-csv -notypeinformation "E:\Ofile.csv"