Touch Command in PowerShell
The two simplest use cases for the touch
command are to:
- Create one or more files, if they don’t exist;
- Update the access date or modification date of files without changing their content.
To replicate these two cases in PowerShell, we make use of
the LastWriteTime
property of a FileSystemInfo
object, as well as creating an empty file if
one does not exist at the specified path.
You can add the following code to the Microsoft.PowerShell_profile.ps1
file in
your <Users>\Documents\WindowsPowerShell\
folder:
Function Update-File | |
{ | |
$Usage = "Usage: Update-File [file1 ... fileN]"; | |
# if no arguments, display an error | |
if ($args.Count -eq 0) { | |
throw $Usage; | |
} | |
# see if any arguments match -h[elp] or --h[elp] | |
foreach($file in $args) { | |
if ($file -ilike "-h*" -or $file -ilike "--h*") { | |
echo $Usage; | |
return; | |
} | |
} | |
foreach($file in $args) { | |
if(Test-Path -LiteralPath $file) | |
{ | |
# file exists, update last write time to now | |
@setProps = @{ | |
LiteralPath = $file | |
Name = 'LastWriteTime' | |
Value = (Get-Data) | |
} | |
Set-ItemProperty @setProps | |
} | |
else | |
{ | |
# create new file. | |
# don't use `echo $null > $file` because it creates an UTF-16 (LE) | |
# and a lot of tools have issues with that | |
echo $null | Out-File -Encoding ascii -LiteralPath $file | |
# alternative | |
# New-Item -Path $file -ItemType File | Out-Null | |
} | |
} | |
} | |
New-Alias -Name touch -Value Update-File |
You can now call it with either: Update-File file1.txt file2.txt
or
touch file1.txt file2.txt
.
Couple of Points Worth Making
We name the function Update-File
following the PowerShell pattern or verb-noun pair for commands
and the Data Verbs section of
Approved Verbs for Windows PowerShell Commands.
We set pass the -Encoding ascii
to the Out-File
command
as the default encoding for Out-File
is UTF-16
and some *nix transplant tools have troubles handling UTF-16 files
because of the two byte-markers at the beginning of the file
(for example webpack when bundling files).
Finally, credit goes to this answer on StackExchange’s superuser.