Powershell导入csv$变量正确为空

Powershell导入csv$变量正确为空,powershell,batch-file,powershell-2.0,powershell-3.0,Powershell,Batch File,Powershell 2.0,Powershell 3.0,我对Powershell 2.0版有一个奇怪的问题 以下内容适用于较新的版本,但在此版本上无法按预期工作。感谢您的帮助 $DB = Import-Csv -Path "$($path)\DBExtrat.csv" 这很好。 dbextart.csv中的标题(“主机名”、“主机IP”、“名称”、“类型”) 所有4个标题都将重新组织,并在运行时显示 $DB 但是如果我尝试 $DB.name或$DB.hostname返回noting。我需要能够这样调用它,因为我的整个逻辑都与那

我对Powershell 2.0版有一个奇怪的问题

以下内容适用于较新的版本,但在此版本上无法按预期工作。感谢您的帮助

$DB = Import-Csv -Path "$($path)\DBExtrat.csv"
这很好。 dbextart.csv中的标题(
“主机名”、“主机IP”、“名称”、“类型”
) 所有4个标题都将重新组织,并在运行时显示

$DB
但是如果我尝试
$DB.name
$DB.hostname
返回noting。我需要能够这样调用它,因为我的整个逻辑都与那些特定的变量名相关联

我已经尝试添加
-标题
选项:

$DB = Import-Csv -Path "$($path)\DBExtrat.csv" -Header 'hostname','hostip','name','type'

但是它不起作用,而且还会创建不必要的额外行和标题数据。

使用诸如
$DB.name
之类的表达式,您试图通过对整个集合执行属性访问来获取集合
$DB
的所有元素的
名称
属性值

此功能称为,它仅在PowerShell v3+中可用

PowerShell v2等效版本要求使用或:


我建议使用@mklement0-answer;简明扼要。或者,离开您在评论中提出的问题,您可以尝试使用自定义对象,看看下面的方法是否有效

$import = Import-Csv -Path "$($path)\DBExtrat.csv"
$Object = New-Object psobject -Property @{
    'hostname' = $import | Select-Object -ExpandProperty hostname
    'hostip'   = $import | Select-Object -ExpandProperty hostip
    'name'     = $import | Select-Object -ExpandProperty name
    'type'     = $import | Select-Object -ExpandProperty type   
}
    "$Object.hostname - $Object.hostip"

您能否运行
$DB | Get Member
并查看它为您的列名返回的NoteProperty?TypeName:System.Management.Automation.PSCustomObject Name MemberType定义--------------------------Equals方法bool Equals(System.Object obj)GetHashCode方法int GetHashCode()GetType方法类型GetType()ToString方法字符串ToString()方法类型hostip NoteProperty System.String hostip=1.1.1.1 hostname NoteProperty System.String hostname=bla.bla name NoteProperty System.String name=Default type NoteProperty System.String type=i这有什么区别吗?
|选择对象名称
您好,感谢您的帮助|选择-对象名或任何其他标题值。我不明白为什么。您认为有办法使它仍然与$DB.name一起工作吗?谢谢again@Evo您正在使用PowerShell 2.0吗?升级。属性枚举是在3.0或4.0中引入的
$import = Import-Csv -Path "$($path)\DBExtrat.csv"
$Object = New-Object psobject -Property @{
    'hostname' = $import | Select-Object -ExpandProperty hostname
    'hostip'   = $import | Select-Object -ExpandProperty hostip
    'name'     = $import | Select-Object -ExpandProperty name
    'type'     = $import | Select-Object -ExpandProperty type   
}
    "$Object.hostname - $Object.hostip"