Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Powershell script to find file in most recent directory

$
0
0

I am trying to write down a script which can help me to get the lines from a file with previous date and to send those lines with a file via email. The trick is that i have to search in the latest created directory as there are many sub directories in root directory.

I have a root dir `C:\Orders`, and in `Orders` directory i have many sub-dirs named `Orders 2014.01.02`, `Orders 2014.01.04`, `Orders 2014.01.06` etc, in which folders i have thousands of txt. files and in one particular `orders.txt` i have lines like this:

    20140102 Shipping order cost ....
    20140102 Order by phone
    20140103 Prepaid ..
    etc ..

so i have to have a script that will goes to the directory Orders with latest day, lets say `Orders 2014.01.06` and will copy all the lines that begins with previous day's date and send it to me.

I have managed to make a script to get the lines from file in the latest directory  and to sand it to me via mail with attachment using that simple line:

    Get-Content "C:\Orders\Orders 2014.01.06\orders.txt" | Where-Object {$_.StartsWith((Get-Date).AddDays(-1).ToString("yyyyMMdd"))} | Out-File "C:\Orders\Result_orders.txt"

the part for email is not included here.

The thing is that this is not so flexible as i have to change manually latest subfolder in the line  every time there is a new folder.

I have another line of code that shows me the latest sub-folder in a root folder:

    gci C:\Orders | where-object { $_.PSIsContainer} | sort CreatiionTime -desc | select -f 1

This line shows me the folder with the latest  date from which i want to get results.
The problem is that i cannot make both line to work in a script. I have tried to combine them, but could not do it. I have tried to make a second command as a variable like:

    $since_folder = gci C:\Orders\ | where-object { $_.PSIsContainer} | sort CreatiionTime -desc | select -f 1

and then call it from the first line of script that i have like:

    Get-Content "$since_folder\orders.txt" | Where-Object {$_.StartsWith((Get-Date).AddDays(-1).ToString("yyyyMMdd"))} | Out-File "C:\Orders\Result_orders.txt"

but it does not seem right and it does not work, actually i am getting an email after i run the last script but i don't get the attachment, as i have it if i run only

    Get-Content "C:\Orders\Orders 2014.01.06\orders.txt" | Where-Object {$_.StartsWith((Get-Date).AddDays(-1).ToString("yyyyMMdd"))} | Out-File "C:\Orders\Result_orders.txt"

Can anyone help me with that script, it is probably very simple but i am hitting the wall here


Viewing all articles
Browse latest Browse all 6937

Trending Articles