In the last tutorial with the subject of "Touch utility to change timestamps", we have created a PowerShell script to update the creation time, last write time, last access time of files. In this tutorial, we will continue working on that script and convert it into a PowerShell function.
A function is a block of code grouped together for reusability. Grouping together can also be described as compartmentalize or build modular code. The main benefit is the ability to avoid duplication if you need to call the same block of code again and again. Since this is easy to understand, I won't spend too much time on convincing you to use function.
Instead, this tutorial is all about how to write a function to compartmentalize the touch utility script we wrote last time.
(demo starts)
Before getting started, you can take advantage of PowerShell's built-in help system by quickly reading through the information about function.
In PowerShell console, type: get-help function to find out the help files you are interested in. Here we want to read "about_function". You can type: Get-Help about_Functions -ShowWindow.
You may also want to look at advanced function help file, like this:
Get-Help about_Functions_Advanced -ShowWindow
(demo ends)
Here are the commands used.
From the help files on functions, we find out that there are two kinds of syntax to create a function.
The basic syntax is similar to the conventional functions found in C++ or C#, using parentheses after the function name.
Anything inside square brackets is optional. Anything inside angle brackets is value. The curly brackets and round brackets are part of the code.
The advanced syntax, also called modern form, is to use param keyword to define parameters.
To write advanced function, we need to use advanced syntax. What is an advanced function? It is a function can act similar to a cmdlet, for example, accepting pipeline input. We will see how it works in the following demo.
This is the touch utility script we wrote last time:
cls
$path = 'c:\tutorial'
foreach ($file in ls $path -Recurse)
{
$file.CreationTime = [datetime]'2001-01-01 13:01:01'
$file.LastWriteTime = [datetime]'2002-02-02 14:02:02'
$file.LastAccessTime = [datetime]'2003-03-03 15:03:03'
$file | select fullname, `
creationtime, `
lastwritetime, `
lastaccesstime
}
(demo starts)
Now we will turn it into a function, better to be an advanced PowerShell function, which acts like a cmdlet that can accept pipeline input. Save this file with a new name, like touch-02.ps1.
We start with keyword "function", followed by function name in verb-noun pair: Set-FileTimestamp. For a basic function, we don't need to follow verb-noun convention, but for advanced function, we should follow the cmdlet naming requirements.
To decide which verb to use, use get-verb help cmdlet. You can use Ctrl + R shortcut to switch back and forth between Console and Script pane.
Define parameters with "param" keyword. Add [CmdletBinding()] attribute to make it act like a cmdlet. Add one parameter $file with type: System.IO.FileInfo, since we will update the timestamp of files only. Also add another attribute: ValueFromPipeLine.
Put the code inside the process block, which is necessary to accept all kinds of pipeline input. The reset of the code is similar to the code we wrote last time, except now we decide to update to current time, using get-date cmdlet.
(demo ends)
Here is the first part of the code that defines the function: Set-FileTimestamp
cls
function Set-FileTimestamp
{
[CmdletBinding()]
param
(
[Parameter(ValueFromPipeline)]
[System.IO.FileInfo]$file
)
process
{
$file.CreationTime = Get-Date
$file.LastWriteTime = Get-Date
$file.LastAccessTime = Get-Date
}
}
This is the second part of the code that tests the function.
ls 'c:\tutorial' -File | Set-FileTimestamp
ls 'c:\tutorial' -File | Format-Table -AutoSize -Property `
@{n = 'name'; e = {$_.Name}}, `
@{n = 'creation'; e = {$_.CreationTime}}, `
@{n = 'write'; e = {$_.LastWriteTime}}, `
@{n = 'access'; e = {$_.LastAccessTime}}
There are lots of details on how to create and use basic and advanced PowerShell functions. Please refer to the help documents or online resources when there is a practical need. I hope this tutorial will help you get started exploring PowerShell functions.
Thanks for watching!
Nesta página do site você pode assistir ao vídeo on-line PowerShell 07: Turn touch utility into a function duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário LiLeoWang 19 Julho 2019, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 176 vezes e gostou 5 espectadores. Boa visualização!