Working with Files and Folders

PowerShell – Working with Files and Folders

PowerShell provides various cmdlets for working with files and folders, making it easy to perform common tasks like creating, reading, updating, and deleting files and folders. Here are some common cmdlets and their usage:

Creating a folder:

To create a new folder, you can use the New-Item cmdlet with the -ItemType parameter set to "Directory".

New-Item -Path "C:\path\to\new\folder" -ItemType Directory

Creating a file:

To create a new file, use the New-Item cmdlet with the -ItemType parameter set to "File".

New-Item -Path "C:\path\to\new\file.txt" -ItemType File

Listing files and folders:

To list files and folders in a directory, use the Get-ChildItem cmdlet.

Get-ChildItem -Path "C:\path\to\folder"

Reading a file:

To read the content of a file, use the Get-Content cmdlet.

Get-Content -Path "C:\path\to\file.txt"

Writing to a file:

To write content to a file, you can use the Set-Content cmdlet. This will overwrite the file if it already exists.

Set-Content -Path "C:\path\to\file.txt" -Value "This is the new content."

Appending to a file:

To append content to a file, use the Add-Content cmdlet.

Add-Content -Path "C:\path\to\file.txt" -Value "This content will be appended."

Renaming a file or folder:

To rename a file or folder, use the Rename-Item cmdlet.

Rename-Item -Path "C:\path\to\old\file.txt" -NewName "new_file.txt"

Moving a file or folder:

To move a file or folder, use the Move-Item cmdlet.

Move-Item -Path "C:\path\to\old\location\file.txt" -Destination "C:\path\to\new\location\file.txt"

Copying a file or folder:

To copy a file or folder, use the Copy-Item cmdlet.

Copy-Item -Path "C:\path\to\source\file.txt" -Destination "C:\path\to\target\file.txt"

Deleting a file or folder:

To delete a file, use the Remove-Item cmdlet. To delete a folder and its contents, use the -Recurse parameter.

Remove-Item -Path "C:\path\to\file.txt"
Remove-Item -Path "C:\path\to\folder" -Recurse