Creating new file with touch command in PowerShell error message

If you're using Windows Powershell, the equivalent command to Mac/Unix's touch is: New-Item textfile.txt -type file.


For single file creation in power shell : ni textfile.txt

For multiple files creation at a same time: touch a.txt,b.html,x.js is the linux command
ni a.txt,b.html,x.js is the windows power shell command


If you need a command touch in PowerShell you could define a function that does The Right Thing™:

function touch {
  Param(
    [Parameter(Mandatory=$true)]
    [string]$Path
  )

  if (Test-Path -LiteralPath $Path) {
    (Get-Item -Path $Path).LastWriteTime = Get-Date
  } else {
    New-Item -Type File -Path $Path
  }
}

Put the function in your profile so that it's available whenever you launch PowerShell.

Defining touch as an alias (New-Alias -Name touch -Value New-Item) won't work here, because New-Item has a mandatory parameter -Type and you can't include parameters in PowerShell alias definitions.


As Etan Reisner pointed out, touch is not a command in Windows nor in PowerShell.

If you want to just create a new file quickly (it looks like you're not interested in the use case where you just update the date of an existing file), you can use these:

$null > textfile.txt
$null | sc textfile.txt

Note that the first one will default to Unicode, so your file won't be empty; it will contain 2 bytes, the Unicode BOM.

The second one uses sc (an alias for Set-Content), which defaults to the system's active ANSI code page when used on the FileSystem, which uses no BOM and therefore truly creates an empty file.

If you use an empty string ('' or "" or [String]::Empty) instead of $null you'll end up with a line break also.

Tags:

Git

Powershell