在 powershell 上使用文件名作为参数 function/script

Using filename as parameter on powershell function/script

下午好

最近我一直在尝试修改this powershell script(来自"Hey, Scripting Guy! Blog")来修改单个文件的文件时间戳(CreationTime、LastAccessTime 和LastWriteTime)而不是文件夹的文件.但是,我一直在使用我所做的修改使其工作时遇到问题。

原脚本如下:

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

修改后的是这样的:

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

当我尝试 运行 脚本时,它抛出以下错误:

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

所以,我不清楚我在修改原始脚本时哪里失败了,如果有人能指出正确的方向,我将不胜感激。

提前致谢。

类型 [string] 没有 CreationTimeLastAccessTimeLastWriteTime 属性只是因为它是文件名...它始终是 [string]类型。 您需要将 [system.io.fileinfo] 类型作为脚本的参数传递或转换为此类型:

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

在原始脚本中,cmdlet Get-ChildItem -Path $path return [fileinfo] 类型,这就是它起作用的原因。