Last active
August 21, 2017 13:30
-
-
Save philipmat/1841540bd05ebb98bec402e6b387ff56 to your computer and use it in GitHub Desktop.
Unix `touch` in Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Improved version, with comments and everything: https://www.reddit.com/r/PowerShell/comments/6uxuk2/replicating_the_unix_touch_command/dlwwjwq/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit to: https://superuser.com/a/571154