5

good afternoon

Recently I've been trying to adapt this powershell script (from "Hey, Scripting Guy! Blog") to modify the file timestamps (CreationTime, LastAccessTime, and LastWriteTime) of a single file instead of the files of a folder. But, I've been having problems on make it work with modifications that I've made.

The original script is as follows:

Set-FileTimeStamps function

Function Set-FileTimeStamps
{
    Param (
        [Parameter(mandatory=$true)]
        [string[]]$path,
        [datetime]$date = (Get-Date))
    Get-ChildItem -Path $path |
    ForEach-Object {
        $_.CreationTime = $date
        $_.LastAccessTime = $date
        $_.LastWriteTime = $date
    }
} #end function Set-FileTimeStamps

And the modified one is this:

Function Set-FileTimeStamps
{
    Param (
        [Parameter(mandatory=$true)]
        [string]$file,
        [datetime]$date = (Get-Date))
    $file.CreationTime = $date
    $file.LastAccessTime = $date
    $file.LastWriteTime = $date
} #end function Set-FileTimeStamps

An when I try to run the script it throws me the following error:

Property 'CreationTime' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Anton\Documents\WindowsPowerShell\Modules\Set-FileTimeStamps\Set-FileTimeStamps.psm1:7 char:11
+ $file. <<<< CreationTime = $date
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

So, it's not clear to me where I'm failing while modifying the original script, and I would be thankful if someone could point me the right direction.

Thanks in advance.

1 Answer 1

5

The type [string] does not have CreationTime, LastAccessTime and LastWriteTime properties just because is a file name... it's always a [string] type. You need to pass a [system.io.fileinfo] type as parameter of your script or cast to this type:

Function Set-FileTimeStamps
{
    Param (
        [Parameter(mandatory=$true)]
        [string]$file,
        [datetime]$date = (Get-Date))

        $file = resolve-path $file     
        ([system.io.fileinfo]$file).CreationTime = $date
        ([system.io.fileinfo]$file).LastAccessTime = $date
        ([system.io.fileinfo]$file).LastWriteTime = $date
    } #end function Set-FileTimeStamps

in the original script the cmdlet Get-ChildItem -Path $path return a [fileinfo] type that's why it works.

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

Comments

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.