Reputation: 49
I'm looking to convert the following powershell code into a function.
Id like to be able to specify a path ($filePath) and receive the number of minutes since it was last written to. The below works perfectly well, but id like it as a function as it needs to be repeated multiple times.
$file = get-item $filePath
$date = Get-Date
$fileDate = $file.LastWriteTime
$duration = ($date - $fileDate)
$mins = $duration.TotalMinutes
$RoundedMinsSinceLastWritten = [math]::Round($mins,2)
When i call $RoundedMinsSinceLastWritten, I get the value that I need (the number of minutes to 2 decimal places). I don't know what to call when this is in a function.
The goal is to have the value inside a variable.
Upvotes: 0
Views: 399
Reputation: 174515
Turning a group of statements into a function is as easy as enclosing them in {}
and prefix it with the function
keyword and a function name:
function Get-FileAge {
# code goes here...
}
Id like to be able to specify a path ($filePath)
So we'll need to declare a $FilePath
parameter:
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)
}
See the about_Functions_Advanced_Parameters
help file for more details on parameter declarations in PowerShell functions.
Upvotes: 2