简体   繁体   中英

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:

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". 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.

How would I go about doing this? I've tried using -delimiter ':', and not much luck.

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

> 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.


Including the for-loop that would be something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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