如何在CSV中获取标题的值 [英] How To Get The Value Of Header In CSV
问题描述
在PowerShell中,我要将CSV文件中的标头名称传递给PowerShell脚本中的另一个函数.
In PowerShell I want to pass the name of a header in a CSV file into another function in the PowerShell script.
如何将标头名称的值文本检索到CSV变量中?
How can I retrieve the value-text of a header name into a variable in CSV?
例如如果我有以下CSV数据:
e.g. if I have the following CSV data:
ID Name Country
-- ---- -------
1 John United States
2 Beatrice Germany
3 Jouni Finland
4 Marcel France
在上面的示例中,如何在脚本中将国家/地区"列值文本作为国家/地区"文本检索到变量中?
In the above example how can I retrieve the Country column value text as "Country" text into a variable in my script?
(注意:我熟悉$ _.Country表示法,通过在Powershell中导入CSV从一行中检索德国"的值)
(Note: I am familiar with the notation $_.Country to retrieve the value of, for example, "Germany" from a row by importing the CSV in Powershell)
我的特定问题是,当前我的脚本中具有以下功能:
My specific issue is that currently I have the following function in my script:
function GetItemIdFromTitle([string]$LookupTitle, [ref]$LookupId)
{
$LookupField = $LookupList.Fields["DEPTCATEGORY"]
$LookupItem = $LookupList.Items | where {$_['DEPTCATEGORY'] -like "*$LookupTitle*"}
$LookupId.Value = $LookupItem.ID
}
当前,它使用字符串值-> $ LookupTitle,并使用该值在SharePoint列表中查找项目.正如您在脚本中看到的那样,我将列名硬编码为"DEPTCATEGORY".这是将在SharePoint列表中查找的列名.
This currently takes a string value -> $LookupTitle and uses that to find an item in a SharePoint list. As you can see in the script I am hard-coding in the column name as "DEPTCATEGORY". This is the column name that will be looked up to in the SharePoint list.
我不想对列名进行硬编码,而是要为相应的$ LookupTitle值传递列名,并替换为硬编码的"DEPTCATEGORY".
Instead of hard-coding the column name I want to pass in the name of the column for the corresponding $LookupTitle value and replace the hard-coded "DEPTCATEGORY".
我正在调用上述函数,如下所示:
I am calling the above function as follows:
#GET THE LOOKUP COLUMN ID
GetItemIdFromTitle $_.DEPTCAT ([ref]$LookupIdValue)
($ _.DEPTCAT是CSV列中的行中的值.)
( $_.DEPTCAT is the value from the row in the CSV column. )
我可以做类似的事情
$myCountryColumnName = $_.Country.Property.Title
或
$myCategoryColumnName = $_.DEPTCAT.Property.Name
要从CSV获取列名吗?
to get the column name from the CSV?
推荐答案
如果$ obj中有一个对象,则可以列出所有属性标头,如下所示:
If you have an object in $obj, you could list all the property headers like this:
$obj | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'
这是一个数组,因此您可以像这样分别引用它们:
This is an array, so you can reference them individually like this:
($obj | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name')[0]
这只会为您提供第一个属性的名称.
This would just give you the name of the first property for instance.
这篇关于如何在CSV中获取标题的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!