Skip to content

Instantly share code, notes, and snippets.

@philipmat
Last active August 21, 2017 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipmat/1841540bd05ebb98bec402e6b387ff56 to your computer and use it in GitHub Desktop.
Save philipmat/1841540bd05ebb98bec402e6b387ff56 to your computer and use it in GitHub Desktop.
Unix `touch` in Powershell
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
@philipmat
Copy link
Author

@philipmat
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment