RollTide
RollTide

Reputation: 302

Powershell and last modified date

I am working in a windows environment.

I have a project that requires a short script to determine if a file with a modified date of today exists in a folder. If the file exists, it should copy it, if a file does not exist, it should return an error code.

I prefer to not use 3rd party apps. I am considering powershell.

I can pull a list to visually determine if the file exists, but I am having trouble batching to return an error if the count is zero.

Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  { $_.lastwritetime.month -eq 3 -AND $_.lastwritetime.year -eq 2013  -AND $_.lastwritetime.day -eq 21}

Any help is greatly appreciated!

Upvotes: 2

Views: 69863

Answers (4)

E.V.I.L.
E.V.I.L.

Reputation: 2166

Get-ChildItem $path -r | % {if((!($_.psiscontianer))-and(Get-Date $_.LastWriteTime -Uformat %D)-eq(Get-Date -UFormat %D)){$_.FullName}else{Write-Warning 'No from Today'}}

F.Y.I. when doing large jobs, like if you'll be going through TB of files, use a foreach-object. It's faster then Where-Object. This method processes the objects collected in the array directly when available and doesn't wait until all objects are collected.

In summary, there always a lot of different ways to achieve the same result in PowerShell. I advocate using what is easiest for you to remember. At the same time, PowerShell can provide some big performance differences between the approaches – and it pays to know more!

You can still make the line a little more efficient by calculating the date

$date = (Get-Date -UFormat %D)
Get-ChildItem $path -r | % {if((!($_.psiscontianer))-and(Get-Date $_.LastWriteTime -Uformat %D)-eq$date){$_.FullName}else{Write-Warning 'No from Today'}}

Upvotes: 1

sblandin
sblandin

Reputation: 964

To test if there are no files:

$out = Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  {  
   $_.LastWriteTime.ToShortDateString() -eq (Get-Date).ToShortDateString() 
};
if ($out.Count -gt 0)
//do something with your output
else
//sorry no file

Upvotes: 0

RollTide
RollTide

Reputation: 302

I was able to use the following script:

$Date = Get-Date
$Date = $Date.adddays(-1)
$Date2Str = $Date.ToString("yyyMMdd")
$Files = gci "C:\\Temp\\FTP\\Archive"

ForEach ($File in $Files){
    $FileDate = $File.LastWriteTime
    $CTDate2Str = $FileDate.ToString("yyyyMMdd")
    if ($CTDate2Str -eq $Date2Str) {Copy-Item $File.Fullname "C:\\Temp\\FTP"; exit}
}
Throw "No file was found to process"

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126722

You can compare the current date against the date part only of each file LastWriteTime short date:

Get-ChildItem -Path C:\temp\ftp\archive -Recurse | Where-Object  {
   $_.LastWriteTime.ToShortDateString() -eq (Get-Date).ToShortDateString() 
}

Upvotes: 2

Related Questions