简体   繁体   English

如何为CSV文件中的每一行导入前两个值 电源外壳

[英]How to import first two values for each line in CSV file | PowerShell

I have a CSV file that generates everyday, and generates with data such as: 我有一个每天生成的CSV文件,并使用以下数据生成:

windows:NT:v:n:n:d:n:n:n:n:m:n:n

I should also mention that that example is one of 3,900+ lines, and not every line of data has the same number of "columns". 我还应该提一下,该示例是3,900多行之一,并非每行数据都具有相同数量的“列”。 What I'm trying to do is import just the first two "columns" of data into a variable. 我要做的是将数据的前两个“列”导入变量。 For this example, it would be "Windows" and "NT", nothing else. 对于这个例子,它将是“Windows”和“NT”,没有别的。

How would I go about doing this? 我该怎么做呢? I've tried using -delimiter ':', and not much luck. 我尝试过使用-delimiter':',但运气不大。

The number of lines shouldn't matter. 行数无关紧要。

My approach from comment (to your previous question) should work, 我从评论(到你之前的问题)的方法应该有效,
if there is no header and you only want the first two columns, 如果没有标题,你只想要前两列,
just specify Header 1,2 只需指定标题1,2

> import-csv .\strange.csv -delim ':' -Header (1..2) |Where 2 -eq 'NT'

1       2
-       -
windows NT

Example for building the entire array 构建整个数组的示例

$Splitted_List = @()

foreach($Line in Get-Content '.\myfilewithuseragents.txt'){           
    $Splitted = $Line -split ":"
    $Splitted_Object = [PSCustomObject]@{
        $part1 = $splitted[0]
        $part2 = $Splitted[1]        
    }
    $Splitted_List.Add($Splitted_Object) | Out-Null    
}

For every line you'll just read the line and with the string from that line, you're easily able to split it 对于每一行,您只需读取该行以及该行中的字符串,您就可以轻松地将其拆分

$useragent = "windows:NT:v:n:n:d:n:n:n:n:m:n:n"

Then the first part will be referenced to as $useragent.Split(":")[0] , the second as $useragent.Split(":")[1] , etc. 然后第一部分将被引用为$useragent.Split(":")[0] ,第二部分将被引用为$useragent.Split(":")[1]等。


Including the for-loop that would be something like 包括类似的for循环

foreach($useragent in Get-Content '.\myfilewithuseragents.txt') {
  $splitted = $useragent.Split(":")
  $part1 = $splitted[0]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM