首页 > 解决方案 > 用于获取自上次写入文件以来的分钟数的 Powershell 函数

问题描述

我正在寻找将以下 powershell 代码转换为函数。

我希望能够指定一个路径($filePath)并接收自上次写入以来的分钟数。下面的工作非常好,但我喜欢它作为一个函数,因为它需要重复多次。

  $file = get-item $filePath
  $date = Get-Date
  $fileDate = $file.LastWriteTime
  $duration = ($date - $fileDate)
  $mins = $duration.TotalMinutes
  $RoundedMinsSinceLastWritten = [math]::Round($mins,2)

当我调用 $RoundedMinsSinceLastWritten 时,我得到了我需要的值(分钟数到小数点后 2 位)。我不知道在函数中调用什么。

目标是将值包含在变量中。

标签: powershell

解决方案


将一组语句变成一个函数就像将它们包含在其中{}并在其前面加上function关键字和函数名一样简单:

function Get-FileAge {
  # code goes here...
}

我希望能够指定一个路径($filePath)

所以我们需要声明一个$FilePath参数:

function Get-FileAge {
  param(
    [Parameter(Mandatory = $true)]
    [string]$FilePath
  )

  $file = Get-Item $filePath
  $date = Get-Date
  $fileDate = $file.LastWriteTime
  $duration = ($date - $fileDate)
  $mins = $duration.TotalMinutes
  return [math]::Round($mins,2)
}

有关 PowerShell 函数中参数声明的更多详细信息,请参阅about_Functions_Advanced_Parameters帮助文件


推荐阅读