My Technical Notes

Monday, 16 February 2015

PowerShell Equivalent of Touch

The `touch` command in Unix, given a file path, will either create a zero-length file if the file does not exist, or it will update the file's timestamp if it does. The following code defines a `Touch` CmdLet:


Function Touch
{
    $file = $args[0]
    if($file -eq $null) {
        throw "No filename supplied"
    }

    if(Test-Path $file)
    {
        (Get-ChildItem $file).LastWriteTime = Get-Date
    }
    else
    {
        echo $null > $file
    }
}

No comments: