如何读取列中的csv内容

时间:2014-09-04 16:02:59

标签: powershell

您如何使用get-content读取csv列?

1 个答案:

答案 0 :(得分:0)

在过去的一周里,我需要读取csv文件中的列并遇到一些麻烦。然后我发现了读取行头的import-csv。所以我创建了一个脚本,并希望给别人以便他们也可以使用它。

此脚本读取包含“IP”,“可利用性”,“操作系统”和“严重性”的csv文件的行,然后使用Where-Object方法解析文件,如下所示:

Where-Object {$_.Severity -eq 5 -or $_.Severity -eq 4 -and $_.OS -like "Windows*" } 

这是脚本修改,请享受:

#load assembly for file dialog box
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null;


#File dialog box to browse to file.
function diagbx()
{
     $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
     $OpenFileDialog.initialDirectory = $initialDirectory
     $OpenFileDialog.filter = "Comma Separated Value (*.csv)|*.csv
     $OpenFileDialog.ShowDialog()
     $OpenFileDialog.filename
}

#get the results of the function
$file = diagbx;

#Check to see if diag was cancled.
if ($file[0] -eq "Ok")
{
    #get the content of the file
    $content = Import-Csv $file[1]

    #create empty array variable to be accessed outside of conditional statement.
    $ip = @()

    #loop content and build into array
    for ($i = 0; $i -lt $content.Count; $i++)
    { 
        #Get data with only specified elements
        $list = $content[$i] | Select-Object IP, Exploitability , OS , Severity | Where-Object {$_.Severity -eq 5 -or $_.Severity -eq 4 -and $_.OS -like "Windows*" }  

        #Check to see if the variable is not empty.
        if ($list)
        {
            #Look up the IP Address and set in the array variable 
            $ip += [System.Net.Dns]::GetHostByAddress($list.ip).HostName.ToString()
        }
    }

    #clean duplicate entries
    $ip = $ip | select -Unique

    #output to a txt file.
    $ip | Out-File c:\List.txt -Append
}

#if cancled, notify the user and wait for a key press
Else
{
    #write a notification to a user
    Write-Host "You have cancled the request.`n `nPress any key to continue...";

    #hold for a key press
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}