Creation time of file is less than 24 hours - powershell

Hi,

I am trying to find out if a file is less than 24 hrs old, within in an if conditional, however this doesn't work, please help:

if ( $((Get-ChildItem .\test.txt).CreationTime)) -lt (Get-Date).AddHours(-24) )

Open in new window


Thank you in advance,
Kelly GarciaSenior Systems AdministratorAsked:
Who is Participating?
 
oBdAConnect With a Mentor Commented:
You want to access the CreationTime property of the object of the Get-Item returns, so you need to wrap the complete command in quotes:
(Get-Item -Path CGGLASWEB01D:\donotshutdown.txt).CreationTime

Open in new window

0
 
oBdACommented:
If you want to check whether the file is less than 24 hours old, then you need to check if its time is greater than 24 hours ago.
You don't need a subexpression around that, and if you only want a single file anyway, use Get-Item, not Get-ChildItem.
if ((Get-Item .\test.txt).CreationTime -gt (Get-Date).AddHours(-24)) {'Hello World'}

Open in new window

1
 
oBdACommented:
On a side note: you're aware that CreationTime is the time the file was actually created on the drive? That means that when a file is copied, the new file's CreationTime will (usually) be that of the time it was copied. So if a file that was last written to 10 years ago is copied today to a new location, the copy will have today's CreationTime (but still a LastWriteTime of 10 years ago).
You're usually better off with LastWriteTime, which is the time the file was last written to.
1
 
Kelly GarciaSenior Systems AdministratorAuthor Commented:
I've tried the code below however it fails:

read-host -assecurestring | convertfrom-securestring | out-file C:\cred.txt

$remotemachinepassword = get-content C:\cred.txt | convertto-securestring

$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "CGLASWEB01D\infras",$remotemachinepassword

New-PSDrive -Name CGGLASWEB01D  -PSProvider FileSystem -Root "\\CGLASWEB01D\c$" -Credential $Credentials

Get-Item (CGGLASWEB01D:\donotshutdown.txt).creationtime

Open in new window


it says:

Get-Item : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:10
+ Get-Item (CGGLASWEB01D:\donotshutdown.txt).creationtime
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetItemComm
   and
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.