PowerShell Navigation and File Manipulation
Navigation
pwd
Present working directory, tells you where in the file structure path you are.
Sample Output:
cd
Allows you to move between directories.
Starting at C:\Users\<enter your user name>\
type:
Now run:
New Output:
New-Item
Used to create new items. files, folders, registry keys, or other objects in a specified location. What types of items can you create?
- File – to create a file.
- Directory – to create a folder (or directory).
- SymbolicLink – to create a symbolic link (shortcut).
- HardLink – to create a hard link.
- Junction – to create a directory junction (similar to a symbolic link but for directories).
Let’s start off with a simple task, creating a new file:
Output:
Creating Directories
What if you wanted to create a new directory? You have options!
Use New-Item
The md
can be used but the command syntax changes.
The Linux command mkdir
command is also an option.
Listing Items in Directories
While Powershell has the command Get-ChildItem,
the ls
command is set as an alias, and because Powershell is “fun,” dir
is also an alias for Get-ChildItem.
You could run:
or
or
The output would remain the same:
Output:
Copying Items
There are several options to copy files in PowerShell
Example:
The Linux Command cp is available but does not offer all the features you might need, especially when handling many files or directories.
Alternative Commands:
- xcopy: A more powerful command for copying directories, subdirectories, and files, including hidden ones. It is more feature-rich than copy.
/s
copies directories and subdirectories, except empty ones./e
copies directories and subdirectories, including empty ones.robocopy: Recommended for copying large numbers of files or directories.
Removing Items
In creating this guide, I’ve made more example directories and files than I need. Time to remove a few.
Current status:
Removing a File
Remove-Item -Path "C:\path\to\file.txt"
Removing a Directory
- Remove an empty directory
Remove-Item -Path "C:\path\to\directory"
I also created files inside of subdir2
- Remove a directory and its contents
Remove-Item -Path "C:\path\to\directory" -Recurse