我正在尝试导入CSV文件。它的顶部有一些随机数据,由于不确定随机数据的结束位置,因此我无法跳过这些行。将有2个空行,然后是标题和所需的数据。
可以说随机数据看起来像这样 “广告组”,“用户ID”,“属性”, “ NTDOMAIN \ Docss”,“ sattar”“已启用” “ NTDOMAIN \ Docs”,“ shayla”,“已禁用” “ NTDOMAIn \ Nurses”,“ mjane”,“ Enabled”
“ AD Group”,“ GivenName”,“ ObjectClass”,“ SURname”,“ Name” ... morecolumns
“ NTDOMAIN \ Users”,“ user1”,“ user”,“ User”,“ 1”
“ NTDOMAIN \ Users2”,“ User1”,“ User”,“ User1_1”,“ 2”
如何导入标题(GivenName,SURname,Name)下的数据。我也只想选择一些列?
答案 0 :(得分:2)
提供的标题行是固定的,可以用作分隔符,
我会使用带有positive lookahead的RegEx:
$Header = "Name,Phone_Number,City"
$CsvData = (Get-Content '.\inputfile.csv' -raw) -Replace "(?s).*?(?=$Header)" | ConvertFrom-Csv
$CsvData
基于上述数据的示例输出(假设使用 comma
分隔的文件):
Name Phone_Number City
---- ------------ ----
Nick 800-524-8763 NewYork
Mike 112-223-2222 Richmond
答案 1 :(得分:0)
## Read the file into an array, line-terminated
$f = [System.Io.File]::GetAllLines('path-to-csv')
## Stage the array to receive the filtered results
$clean = @()
## Loop through each entry in the file
for ($i = 0; $i -lt $f.count; $i++) {
## When the CSV header is found, filter the results and exit
if ($f[$i] -eq "Name Phone_Number City") {
$clean = $f[($i..($f.count - 1))]
break
}
}
## Turn the string array[] into and object that can be used in PowerShellese
$clean = $clean | convertfrom-csv
答案 2 :(得分:0)
您可以使用here strings
(而不是大文件)作为输入来测试这种模式。与来自thepip3r的答案非常相似。另外,您的输入似乎没有使用Comma
作为分隔符,因此指定为Space
。
$csvtext = @"
A B C
w DD q
u o p
p u o
Name Phone_Number City
Nick 800-524-8763 NewYork
Mike 112-223-2222 Richmond
"@
# replace with Get-Content of your file...
# $data = Get-Content ...
$data = $csvtext -split "`r`n"
$i = 0;
foreach($line in $data)
{
if ($line.StartsWith("Name Phone_Number City")) { break; }
$i++
}
$subdata = $data[$i..($data.Count-1)]
$csv = $subdata | ConvertFrom-Csv -Delimiter ' '
$csv