Lets start simply by creating a text file in our current directory. Here is what that would look like:
New-Item -Name “TestFile.txt”
Pretty simple right?
Similarly you can create other types of files as well simply by changing the extension at the end of the name of your file.
Lets create a PowerShell script for example. PowerShell scripts use the .ps1 extension. So all we have to do is change the value of the name parameter from the example above. Here is what that would look like.
New-Item -Name “My Script.ps1”
Awesome! You now have a new script in your current directory. Similarly, you can create other types of scripts as well such as batch (.bat) or python (.py) simply by using the appropriate extension.
Easy as pie!
Shortcuts (Symbolic links):
Lets try something a little more complicated now, such as creating shortcuts.
Shortcuts cannot be created directly from the PowerShell console, not easily at least, however we can create something called a symbolic link which is essentially the same thing.
Without further a do, here is the command we are going to use:
New-Item -Name “My Shortcut” -Path C:\Users\Julian\Desktop -Target C:\Users\\Documents\File.txt -ItemType SymbolicLink
This might look a bit complicated, so lets break it down:
- Just like before -Name specifies the name of our shortcut in this case it will be “My Shortcut”
- -Path specifies the location in which we want our shortcut to be created at. In case you want to create your shortcut to be created in your current directory you don’t have to use this parameter at all.
- -Target specifies the location of our original file. In this example a file named File.txt that is located in out documents directory. Replace with your computers username to make this command work for you.
- Finally the -ItemType parameter lets the New-Item type cmdlet know that we want to create a symbolic link (Shortcut).
That wasn’t hard at all!
Overwriting an existing file:
Previously we use the Test-Path cmdlet to check whether a file already exists before we create it. In some cases however you might want to purposefully overwrite an existing file.
Doing so its quite easy all we have to do is include the -Force parameter in our command as well. Here is what that would look like:
New-Item -Name “TestFile.txt” -Force
Our text file should now be overwritten. Awesome!
Just like before, we can create any type of file in a directory other than our current one simply by using the -path parameter to specify the target directory.
To minimize typing, once again, I will include the name and extension of our file into our path. In this case the -name parameter is not necessary.
New-Item -Path “C:\Users\\Desktop\TestFile.txt”
The above command will create a file named “Testfile.txt” in our desktop directory.
To make it work for you, replace with your computer’s username.