Using file name as parameter in powershell / script function

good afternoon

I recently tried to adapt this powershell script (from "Hey, Scripting Guy! Blog") to change the timestamps file (CreationTime, LastAccessTime and LastWriteTime) of one file instead of the files in the folder. But I had problems getting it to work with the changes I made.

The original script looks like this:

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 modified:

 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 

When I try to run the script, it causes 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 is not clear to me where I fail to modify the original script, and I would be grateful if someone could point me in the right direction.

Thanks in advance.

+4
source share
1 answer

The [string] does not have the properties CreationTime , LastAccessTime and LastWriteTime just because it is the name of the file ... it always has the type [string] . You need to pass the type [system.io.fileinfo] as a parameter to your script or apply 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 source script, the Get-ChildItem -Path $path cmdlet returns the type [fileinfo] because of which it works.

+3
source

All Articles