Assistance with Array

Welcome Forums General PowerShell Q&A Assistance with Array

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
2 weeks ago.

  • Author
    Posts
  • #181133

    Participant
    Topics: 1
    Replies: 0
    Points: 11
    Rank: Member

    Hi,

    I'm a Powershell Amateur! I've written some code to import data from logfile.txt and export the results with export-csv to a weapons_date. I'm replicating each line but I'm sure I might be able to do this better, perhaps with an array or loop or something?

    I did some basic research but don't fully understand arrays

    test

    Clear-Host $TestPath = $null $sourcefile = "logfile.txt" $dest = "weapons_" $date = (Get-Date -Format "%d%M%y-%H%m%s") $target = $dest+$date+".csv"
    
    if (Test-Path $destinationfile) {Remove-Item $destinationfile}
    
    Get-Content $sourcefile | Select-String -Pattern "weapon_sks" | Measure-Object -Line | Add-Member -MemberType NoteProperty -Name Weapon -Value SKS -PassThru | Export-Csv -Path $target -NoTypeInformation
    
    Get-Content $sourcefile | Select-String -Pattern "weapon_rpk" | Measure-Object -Line | Add-Member -MemberType NoteProperty -Name Weapon -Value RPK -PassThru | Export-Csv -Path $target -NoTypeInformation -Append [System.Windows.MessageBox]::Show('Parsing Log File complete','Logfile Outcome','OK')
    

    Hoping to build array to make file much shorter so I can perhaps just read from a string or csv with list of names?

  • #181257

    Participant
    Topics: 2
    Replies: 497
    Points: 1,230
    Helping Hand
    Rank: Community Hero

    Hard to say what you're trying to do here and what you want the end result as. However, in terms of making this a bit easier to do in the current way you're doing it, you can just have Select-String pick both patterns at once.

    Clear-Host
    $TestPath = $null
    $sourcefile = "logfile.txt"
    $dest = "weapons_"
    $date = Get-Date -Format "%d%M%y-%H%m%s"
    $target = "${dest}${date}.csv"
    
    if (Test-Path $destinationfile) {
        Remove-Item $destinationfile
    }
    
    Get-Content $sourcefile |
        Select-String -Pattern "weapon_sks|weapon_rpk" |
        Measure-Object -Line |
        Add-Member -MemberType NoteProperty -Name Weapon -Value SKS -PassThru |
        Export-Csv -Path $target -NoTypeInformation

You must be logged in to reply to this topic.