powershell - 用于获取自上次写入文件以来的分钟数的 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 位)。我不知道在函数中调用什么。
目标是将值包含在变量中。
解决方案
将一组语句变成一个函数就像将它们包含在其中{}
并在其前面加上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
帮助文件。
推荐阅读
- ios - 如何在与默认目标中的数据不同的数据/应用程序(SQLite db,UserDefaults)上运行 Xcode 测试?
- r - R:子集基因模型
- php - 如何在循环中添加具有相同月份的数组?
- angular - nginx 总是显示默认的欢迎页面
- r - 如何使用 Rstudio(Windows)从 hotmail 到 hotmail 发送电子邮件?
- pandas - Panads:试图操纵数据
- linux - “systemctl suspend”命令所需的根权限
- charts - 在 Chart.js 中将单个分组条拆分为多个条
- python - 使用 .isin() 过滤数据仅适用于 1 列
- python - 泛型类型提示 python