locked
ForEach-Object lines in a text file Split compare and delete RRS feed

  • Question

  • Hi,

    Im working on a Powershell script that can put lines from a text file into a list box, but only lines that start with a date ../../....

    The add list box part is working. But id like to delete older lines from the text file first.

    I tried this but it not correct. Can anyone help me code this correctly.

    The lines in the text file look like this 12/12/2018,9AM,44567,Brent,brent@outlook.com

    $CurrentDate = "$(Get-Date -format "dd/MM/yyyy")";
        #Delete older Shifts
        Get-Content $RosterPath | select-string -Pattern '../../...' | ForEach-Object {
          $ObjDate,$ObjTime,$ObjNumber,$ObjName,$ObjEmail = $_.split(",");
          if ($CurrentDate -gt $ObjDate) {
          ((Get-Content -path $RosterPath) -replace $_,"") | Set-Content -Path $RosterPath;
          };
        }
    #Add Listbox
        $ShiftsListBox = New-Object System.Windows.Forms.ListBox
        $ShiftsListBox.Location = New-Object System.Drawing.Size(400,40)
        $ShiftsListBox.Size = New-Object System.Drawing.Size(360,20)
        $ShiftsListBox.Height = 160
        Get-Content $RosterPath | select-string -Pattern '../../...' | ForEach-Object {[void] $ShiftsListBox.Items.Add($_)}
        $FormCreateNewShift.Controls.Add($ShiftsListBox)

    Thanks


    • Edited by KrtNthny Monday, December 31, 2018 10:56 PM
    Monday, December 31, 2018 10:54 PM

All replies

  • You cannot compare a string to a date or string dates.  They must all be date objects to compare.

     

    \_(ツ)_/

    Monday, December 31, 2018 11:41 PM
  • \_(ツ)_/
    Monday, December 31, 2018 11:49 PM
  • 1) Remove the 1st line of your script or, if you want to keep it, change it to "$CurrentDate = Get-Date".

    2) Change the "if ($CurrentDate -gt $ObjDate)" to "if (Get-Date -gt [datetime]$ObjDate)" or "if ($CurrentDate -gt [datetime]$ObjDate)" if you keep that 1st line of the script.

    3) Your "-Pattern" is missing the 4th "." where the 'year' should be -- it should be "../../…." or, better yet, "\d\d/\d\d/\d\d\d\d"


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)


    Tuesday, January 1, 2019 4:31 PM