0

How to compare the current month with file modified in current month using power shell script. My code is working file but it is reading all the csv file in the given directory. I just wanted to read current month file i.e. modified in October 2018.

Please help me out , I have total 6 files in my directory. 3 files having date modified in October 2018 and remaining 3 files are modified in September 2018. I want my script to check the current month then read all csv of current month i.e. October 2018

Code:

$files = Get-ChildItem 'C:\Users\212515181\Desktop\Logsheet\*.csv'
$targetPath = 'C:\Users\212515181\Desktop\Logsheet'
$result = "$targetPath\Final.csv"
$curr_month = (Get-Date).Month
$curr_year = (Get-Date).Year

# Adding header to output file 
[System.IO.File]::WriteAllLines($result,[System.IO.File]::ReadAllLines($files[1])[1])


foreach ($file in $files)    
{
    $month = $file.LastWriteTime.ToString()
    $curr_month=(Get-Date).Month

    if ($month= $curr_month)
    {
        $firstLine = [System.IO.File]::ReadAllLines($file) | Select-Object -first 1 
        [System.IO.File]::AppendAllText($result, ($firstLine | Out-String))
        $lines = [System.IO.File]::ReadAllLines($file)
        [System.IO.File]::AppendAllText($result, ($lines[2..$lines.Length] | Out-String))
    }
}

# Change output file name to reflect month and year in MMYYYY format

Rename-Item $result "Final_$curr_month$curr_year.csv"
0

1 Answer 1

1

Your comparison is wrong. And will return $true causing all files to be read
It should be

 if ($month -eq $curr_month)

Also I would remove the second

$curr_month = (get-date).month

it's adding overhead to your script as you set it before the loop

Sign up to request clarification or add additional context in comments.

1 Comment

Hey you're welcome. The = vs -eq is a common mistake I often make when typing code quickly. Since it's setting the month variable the system will return a $true exit code causing all to be true. Also, good job on correcting the code format. It was tough to read. 🤣 Have a good one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.