Working with files and folders - PowerShell (2024)

  • Article

Navigating through PowerShell drives and manipulating the items on them is similar to manipulatingfiles and folders on Windows disk drives. This article discusses how to deal with specific file andfolder manipulation tasks using PowerShell.

Listing all files and folders within a folder

You can get all items directly within a folder using Get-ChildItem. Add the optional Forceparameter to display hidden or system items. For example, this command displays the direct contentsof PowerShell Drive C:.

Get-ChildItem -Path C:\ -Force

The command lists only the directly contained items, much like using the dir command in cmd.exeor ls in a UNIX shell. To show items in subfolder, you need to specify the Recurse parameter.The following command lists everything on the C: drive:

Get-ChildItem -Path C:\ -Force -Recurse

Get-ChildItem can filter items with its Path, Filter, Include, and Excludeparameters, but those are typically based only on name. You can perform complex filtering based onother properties of items using Where-Object.

The following command finds all executables within the Program Files folder that were last modifiedafter October 1, 2005 and that are neither smaller than 1 megabyte nor larger than 10 megabytes:

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript { ($_.LastWriteTime -gt '2005-10-01') -and ($_.Length -ge 1mb) -and ($_.Length -le 10mb) }

Copying files and folders

Copying is done with Copy-Item. The following command backs up your PowerShell profile script:

if (Test-Path -Path $PROFILE) { Copy-Item -Path $PROFILE -Destination $($PROFILE -replace 'ps1$', 'bak')}

The Test-Path command checks whether the profile script exists.

If the destination file already exists, the copy attempt fails. To overwrite a pre-existingdestination, use the Force parameter:

if (Test-Path -Path $PROFILE) { Copy-Item -Path $PROFILE -Destination $($PROFILE -replace 'ps1$', 'bak') -Force}

This command works even when the destination is read-only.

Folder copying works the same way. This command copies the folder C:\temp\test1 to the new folderC:\temp\DeleteMe recursively:

Copy-Item C:\temp\test1 -Recurse C:\temp\DeleteMe

You can also copy a selection of items. The following command copies all .txt files containedanywhere in C:\data to C:\temp\text:

Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination C:\temp\text

You can still run native commands like xcopy.exe and robocopy.exe to copy files.

Creating files and folders

Creating new items works the same on all PowerShell providers. If a PowerShell provider has morethan one type of item—for example, the FileSystem PowerShell provider distinguishes betweendirectories and files—you need to specify the item type.

This command creates a new folder C:\temp\New Folder:

New-Item -Path 'C:\temp\New Folder' -ItemType Directory

This command creates a new empty file C:\temp\New Folder\file.txt

New-Item -Path 'C:\temp\New Folder\file.txt' -ItemType File

Important

When using the Force switch with the New-Item command to create a folder, and the folderalready exists, it won't overwrite or replace the folder. It will simply return the existingfolder object. However, if you use New-Item -Force on a file that already exists, the fileis overwritten.

Removing all files and folders within a folder

You can remove contained items using Remove-Item, but you will be prompted to confirm theremoval if the item contains anything else. For example, if you attempt to delete the folderC:\temp\DeleteMe that contains other items, PowerShell prompts you for confirmation beforedeleting the folder:

Remove-Item -Path C:\temp\DeleteMe
ConfirmThe item at C:\temp\DeleteMe has children and the Recurse parameter wasn'tspecified. If you continue, all children will be removed with the item. Are yousure you want to continue?[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help(default is "Y"):

If you don't want to be prompted for each contained item, specify the Recurse parameter:

Remove-Item -Path C:\temp\DeleteMe -Recurse

Mapping a local folder as a drive

You can also map a local folder, using the New-PSDrive command. The following command creates alocal drive P: rooted in the local Program Files directory, visible only from the PowerShellsession:

New-PSDrive -Name P -Root $env:ProgramFiles -PSProvider FileSystem

Just as with network drives, drives mapped within PowerShell are immediately visible to thePowerShell shell. To create a mapped drive visible from File Explorer, use the Persistparameter. However, only remote paths can be used with Persist.

Reading a text file into an array

One of the more common storage formats for text data is in a file with separate lines treated asdistinct data elements. The Get-Content cmdlet can be used to read an entire file in one step,as shown here:

Get-Content -Path $PROFILE# Load modules and change to the PowerShell-Docs repository folderImport-Module posh-gitSet-Location C:\Git\PowerShell-Docs

Get-Content treats the data read from the file as an array, with one element per line of filecontent. You can confirm this by checking the Length of the returned content:

PS> (Get-Content -Path $PROFILE).Length3

This command is most useful for getting lists of information into PowerShell. For example, you mightstore a list of computer names or IP addresses in the file C:\temp\domainMembers.txt, with onename on each line of the file. You can use Get-Content to retrieve the file contents and put themin the variable $Computers:

$Computers = Get-Content -Path C:\temp\DomainMembers.txt

$Computers is now an array containing a computer name in each element.

Working with files and folders - PowerShell (2024)

FAQs

When working with files and folders What is your current working directory? ›

The 'Current Working Directory' is the directory within a file system where the user is currently located and where commands and operations are executed.

What is the PowerShell command to list folders and files? ›

Powershell List Folders and Subfolders. You can use the Get-Childitem PowerShell cmdlet to list files and folders. The Get-Childitem cmdlet is similar to dir but much more Powerful.

How do I get file and folder permissions in PowerShell? ›

The Get-Acl cmdlet in PowerShell's Security module (Microsoft. PowerShell. Security) does a great job of getting file or folder permissions (aka the Access Control List or ACL ).

How do you navigate through folders in PowerShell? ›

Typing CD causes PowerShell to move to the root directory. As you can see, you can use the CD.. or CD command to move to a lower level within the folder hierarchy. You can also use the CD command to enter a folder. Just type CD, followed by the folder name.

What command do you use to list all the files and directories in your current working directory? ›

Use the ls command to display the contents of a directory.

What is the current working directory or current directory? ›

The current working directory is the directory where all the commands are being executed. To know your current directory, you can use the pwd command which stands for Print Working Directory. The name of the current working directory is the last directory in the absolute path.

How do I see what's in a folder in PowerShell? ›

Listing all files and folders within a folder

You can get all items directly within a folder using Get-ChildItem . Add the optional Force parameter to display hidden or system items. For example, this command displays the direct contents of PowerShell Drive C: .

How to run a file with PowerShell? ›

To use the Run with PowerShell feature: In File Explorer (or Windows Explorer), right-click the script filename and then select Run with PowerShell. The Run with PowerShell feature starts a Windows PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

How to check if a file exists in PowerShell? ›

Using Get-Item to check if a file exists — You can use the Get-Item cmdlet in PowerShell to find a file by name. If the specified item path does not exist, the script will throw an error. Below is a PowerShell script that checks whether the file "Payroll 2022 - 2023. xlsx" exists using the Get-Item cmdlet.

How do I access a folder in PowerShell? ›

If you take a folder and drag-and-drop it onto the PowerShell, it will fill the window with the absolute pathname of that folder. Therefore, to quickly move the PowerShell to a a specific folder, do the following: Type cd followed by a space.

How to get all public folders and permissions using PowerShell? ›

Use the Get-PublicFolder cmdlet to retrieve the attributes of a public folder or a set of public folders. For information about the parameter sets in the Syntax section below, see Exchange cmdlet syntax.

How do I list files and folders in PowerShell? ›

You can use the Get-ChildItem cmdlet to retrieve a list of all items within a specified folder, including files. This allows you to get files from a folder in PowerShell. For example, Get-ChildItem -Path C:\YourDirectory -File will return all the files in the specified directory without including subdirectories.

How do I move files and folders in PowerShell? ›

In the PowerShell console, type Move-Item –Path c:testfolder -Destination c:temp and press ENTER. Replace c:testfolder with the full path to the folder you want to move; and c:temp with the full path of the target folder.

How do I give a folder path in PowerShell? ›

PowerShell uses the following character sequences to specify relative paths.
  1. ( . ) - Current location.
  2. ( .. ) - Parent of current location.
  3. ( \ ) - Root of current location.
Sep 5, 2024

How do I find the current working directory of a file? ›

To find the current directory in your terminal or command prompt, you can use the "pwd" command in Unix-based systems or "cd" command without any arguments in Windows. It will display the full path of the directory you are currently in.

What is the current working directory of a process? ›

In computing, the working directory of a process is a directory of a hierarchical file system, if any, dynamically associated with the process. It is sometimes called the current working directory (CWD), e.g. the BSD getcwd function, or just current directory.

What shows your current working directory? ›

To determine the exact location of the current directory at a shell prompt and type the command pwd. This example shows that you are in the user sam's directory, which is in the /home/ directory. The command pwd stands for print working directory.

What do you mean by working directory? ›

A working directory is the directory in which a process can operate and perform tasks. It allows a process to set its location for executing commands and accessing files within that specific directory.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 6071

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.