Forum Discussion

lionheart1981's avatar
lionheart1981
Copper Contributor
Oct 05, 2019

Assistant creating array?

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

 

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?

 

Cheers!

  • BrettMiller's avatar
    BrettMiller
    Copper Contributor

    lionheart1981 

    Looking at this it could be much simpler but without seeing the content of the logs it's difficult to say for sure.

    It looks like you just want the count of each of the matched patterns and add the relevant property as per the match. You can grossly simplify this using Group-Object

    Get-Content .\testfile.txt | Where-Object { $_ -match 'weapon_(sks|rpk)' } |
        Group-Object |
            Select-Object Count, Name, @{name='Weapon';expression={$_.name -replace '.+_'}}


    This will give the following output

    Count Name         Weapon
    ----- ----           ------
       18 weapon_rpk   rpk
       11 weapon_sks   sks

     

Resources