bashpowershellshellcommand

What is the equivalent of "touch" on windows PowerShell?


I'm trying to create a JavaScript .js file via the PowerShell Command-line, however, when I tried echo the file just disappears right after I create it. Is there an equal to the BASH command $ touch in PowerShell?

I have tried the below commands but they don't work

echo file.txt
(ERROR)
echo. file.txt
(ERROR)
echo.>> file.txt
(ERROR)

Solution

  • It looks like your in PowerShell, which is slightly different than the Windows CMD-Prompt.



    PowerShell Equivalent to the Linux Command $> touch


    In PowerShell they the Command, a Cmdlet, and unlike BASH there is a specific Cmdlet for creating new files & directories (among other entities as well).


    The PowerShell Cmdlet: $> New-Item


    You can (for the most part) replace the BASH $> touch command with the PowerShell CmdLet $> New-item when creating files in a shell-environment.

    Creating new items works a bit differently in PowerShell& than in Linux Shells (I am specifically referring to Bash in this answer). For example, Windows PowerShell's CmdLet $> New-item can create more than one type of item — for example, PowerShell create both directories, and files — therefore; in PowerShell, you need to specify the item type. To specify an item-type you will use the ItemType flag -ItemType <argument>. The pseudo-argument was a place holder I added in. Actual -ItemType arguments would be File &/or Directory.




    EXAMPLE | New File:


    Here is the Cmdlet format thats considered the standard for creating new files:
    
        New-Item -Path 'A:\testing\one\two\three.txt' -ItemType File
    
    
    

    Creates the file, three.txt in the directory two, and the file's full pathname would be, A:\testing\one\two\three.txt



    EXAMPLE | New Directory:


    The $> New-item CmdLet is specific for creating files & directories. This is somewhat unique, as the Linux Shell BASH implements the $> mkdir command, but it only makes directories, not files. BASH demonstrates that a SHELL doesn't have to have a command thats specificly for file creation, however; that's not to say that having a file-creation command doesn't have any benifits. But, in Windows, you can, and you should, use the New-Item CmdLet for creating directories.

    Here is how to create a directory when using PowerShell:
    
    New-Item -Path 'Z:\sum-directory' -ItemType Directory
    
    

    This command creates a new directory named sum-directory. The directory is located in the drive-letter Z:\, and the directory's full pathname would be Z:\sum-directory



    FOR MORE INFORMATION ABOUT THIS TOPIC, PLEASE VISIT:

    https://learn.microsoft.com/en-us/powershell/scripting/samples/working-with-files-and-folders?view=powershell-7.1#creating-files-and-folders