logo

PowerShell File Management

Every day, sysadmins perform a variety of standard operations on their Windows servers, including creating, deleting and moving files and folders. By getting fluent with the core set of Active Directory (AD) PowerShell commands provided here, you can dramatically reduce the amount of manual work involved.

Before you start, make sure your system policy allows running PowerShell scripts, as described in “Windows PowerShell Scripting Tutorial for Beginners.”

View the objects in a directory

To view the contents of a directory on a Windows file server, including all files and subdirectories, use the Get-ChildItem cmdlet. The output includes the name, size and last-modified date for each item. It is similar to the dir or ls command in Windows.

Show hidden objects

The command below shows all root objects, including hidden ones, in the fsShared folder:

Get-ChildItem -Force \fsShared

Show all subfolders and their content

The following command uses the -Recurse parameter to extend the output to include all subfolders and their content. Each subfolder will be displayed separately.

Get-ChildItem -Force \fsShared -Recurse

Filter the output

You can filter the output by using the -Filter, -Exclude, -Include and -Path parameters.

For advanced object filtering, use the pipe operator (|) to pass data from the Get ChildItem cmdlet to the Where-Object cmdlet. For instance, the script below searches for all executable files in the fsShared folder and subfolder that were modified after 18 January, 2023.

Get-ChildItem -Path \fsShared -Recurse -Include *.csv | Where-Object -FilterScript {($_.LastWriteTime -gt '2023-01-18')}

Create files and folders

Use the PowerShell cmdlet New-Item to create an object, such as a directory, file or registry key. The -Path parameter specifies the location where the new item will be created, and the -ItemType parameter specifies the type of item to create. Additional parameters, such as -Name and -Value, can be used to specify the name of the new item and its content.

Create a folder

Create a file

New-Item -Path '\fsSharedNewFolder\newfile.txt' -ItemType File

Create a file and write data to it

One way to create a file and write data to it is to use the Out-File cmdlet, as shown below.

Get-Process -Name * | Out-File -FilePath c:\fsShared\processes.txt

Another option is to pipe the output from a cmdlet, such as Get -ADuser, to Export-Csv, which creates a file that can be opened in Excel:

Get-ADuser -Filter * | Export-Csv -Path C:\dataADusers.csv

Check whether an item with the desired name already exists before creating a new item

If you attempt to create an item that already exists, you will get an error message and the cmdlet will fail. To avoid this, you can use a script like the one below — it checks whether a specific file (pc.csv) already exists in a particular folder and, if not, generates a list of all AD computers and saves it to a new file named pc.csv.

$fileExists = [System.IO.File]::Exists("C:\pc.csv")

if ($fileExists) {

Write-Host "The file already exists."

} else {

Get-ADComputer -Filter * | Export-Csv -Path C:\pc.csv

Write-Host "The file was not found, and a new file has been created."}

Delete files and folders

To delete a file, directory or other object, use the Remove-Item PowerShell cmdlet.

Delete a folder

For example, the following command will delete the specified folder and all the subfolders and files inside it. Notice that because the folder is not empty, you are prompted to confirm the operation.

Remove-Item -Path '\fssharednewfolder'

If you have already made sure that every object inside the folder should be deleted, you can use the -Recurse switch to skip the confirmation step:

Remove-Item -Path '\fssharedit' -Recurse

Delete a file

The following command will delete the file named newfile.txt from the folder fsSharedIT:

Remove-Item -Path '\fssharedit\newfile.txt'

Delete files older than x days

To clean up old files from a directory, use a script like this:

Get-ChildItem -Path "C:\fsSharedNewFolder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item

Delete empty folders

The following script will identify empty folders and delete them without prompting for confirmation:

$Folder = "C:\fsSharedNewFolder"

#Delete empty folders and subfolders

Get-ChildItem $Folder -Recurse -Force -ea 0 |

? {$_.PsIsContainer -eq $True} |

? {$_.getfiles().count -eq 0} |

ForEach-Object {

    $_ | del -Force -Recurse

    $_.FullName | Out-File C:\deletedfolders.txt -Append

}

Delete files after checking they exist

Here’s how to check whether a file called datalog.txt exists and delete it if it does:

$FileName = 'C:\datalog.txt'

If (Test-Path $FileName){

   Remove-Item $FileName

}

Delete files from multiple computers in one script

To delete files from remote PCs, you must have the appropriate security permissions to access them. Be sure to use UNC paths so the script will correctly resolve the file locations.

$file_list = @("c$\Temp\*", "c$\Temp2\*") #variable to delete files and folder

$computer_list = Get-Content C:\datapc.txt #get list of remote pc's

    foreach ($computer in $computer_list){

        foreach ($file in $file_list){

            $file_path= Join-Path "\\$computer\" "$file" #generate unc paths to files or folders

            if (Test-Path $file_path)

            {

            Remove-Item $file_path -force -recurse -ErrorAction Continue}}}

Copy files and folders

Use the Copy-Item PowerShell cmdlet to copy items, such as files and directories, from one location to another. It is similar to issuing the copy command from the Windows command prompt.

To copy a file between two folders on the same computer, use this command:

Copy-Item -Path '\Shared\ITUsers.txt' -Destination '\Backup'

Overwrite a target file with the same name

If the target file already exists, the copy attempt will fail. To overwrite the existing file, even if it is Read?Only, use the -Force parameter:

Copy-Item -Path '\Shared\ITUsers.txt' -Destination '\Backup' -Force

Copy files to or from a remote computer

If you’re copying files to or from remote computers, be sure to use UNC paths.

This command will copy all the files inside the Shared folder:

Copy-Item \\Server01\c$\Shared\* -Recurse C:\data

This cmdlet will copy a folder from a remote location to the data folder in your C drive:

Copy-Item \\Server01\c$\Shared -Recurse C:\data

To copy files from your local directory to a remote folder, simply reverse the source and destination locations:

Copy-Item C:\data\* -Recurse \\Server01\c$\Shared

This command will copy a folder from one server to another:

Copy-Item \\Server01\Shared -Recurse \\Server02\Backup

Copy only certain types of files

To copy only certain files from the source to the destination, use the -Filter parameter. For instance, the following command copies only text files from one folder to another:

Copy-Item -Filter *.txt -Path \Shared\* -Recurse -Destination \Backup

Move files and folders

The Move-Item cmdlet moves a file or folder from one location to another. It is similar to issuing the move command from the Windows command prompt. The -Path parameter specifies the location of the item to be moved, and the -Destination parameter specifies the location where the item will be moved to (the item destination).

The following command moves a backup file from one location to another:

Move-Item -Path \Shared\Backups1.bak -Destination \Backup

To move the folder named Shared and its contents to the Backup folder, use this cmdlet:

Move-Item -Path \Shared -Destination \Backup

To move a directory and all its subdirectories and files, use the -Recurse parameter:

Move-Item -Path \Shared -Destination \Backup -Recurse

Rename a file or folder

The Rename-Item cmdlet enables you to change the name of an object, such as a file or directory, while leaving its contents intact. It is similar to the Windows command ren.

The -Path parameter specifies the location of the file or directory, and the –NewName parameter provides the new name of the file or folder.

For example, the following command renames a text file to a similar name with an underscore character added:

Rename-Item -Path "\Shared\ITUsers.txt" -NewName "IT_Users.txt"

Rename multiple files

To rename multiple files at once, use a script like this:

$files = Get-ChildItem -Path C:\Shared #create list of files

foreach ($file in $files)

{

    $newFileName=$file.Name.Replace("A","B")  #replace "A" with "B"

    Rename-Item -Path $file.FullName $newFileName

}

Change file extensions

You can also use Rename-Item to change file extensions.

If you want to change the extensions of multiple files at once, use a script like the following, which will change all txt file extensions to bak. The wildcard character (*) ensures that all text files are included.

Get-ChildItem \Shared\*.txt | Rename-Item -NewName { $_.name -Replace '.txt','.bak' }

FAQ

How can I create a file using PowerShell?

You can use the New-Item cmdlet to create a file. The following command will create a text file in the Shared folder:

New-Item -Path '\Shared\newfile.txt' -ItemType File

You can also use the New-Item cmdlet to create folders, directories and registry keys.

To avoid an error message, you might want to first check whether the item already exists.

How do I create a directory using PowerShell?

To create a new directory with PowerShell, use the New-Item cmdlet:

New-Item -Path '\fsSharedNewFolder' -ItemType Directory

How do I delete a file using PowerShell?

To delete a file, use the Remove-Item cmdlet:

Remove-Item -Path '\fsSharedNewFolder\newfile.txt'

If the file is not empty, you will be prompted to confirm the deletion.

You can also use PowerShell to remove files older than X days or delete files from multiple computers.

How do I force-delete a file using PowerShell?

If you want to delete a file or folder that is read?only or hidden, use the -Force parameter:

Remove-Item -Path '\fsSharedNewFolder\newfile.txt' -Force

How do I copy a file using PowerShell?

Use the Copy-Item cmdlet to copy objects from one location to another:

Copy-Item -Path '\Shared\ITUsers.txt' -Destination '\Backup'

Note that if the target file already exists, the copy attempt will fail. Learn how to overwrite the target files during a copy operation.

How do I move a file using PowerShell?

To moves an item and its child items (files and folders) from one location to another, use the Move-Item cmdlet:

Move-Item -Path \Shared\Backups1.bak -Destination \Backup

You can also move an entire folder with PowerShell.

How do I rename a file using PowerShell?

To rename a single file using PowerShell, use the following command:

Rename-Item -Path "\Shared\ITUsers.txt" -NewName "IT_Users.txt"

You can also rename multiple files at once using PowerShell.

Kevin Horvatin is a Lead Software Architect at Netwrix and responsible for Netwrix Privilege Secure. A software developer for over 20 years, he has worked with PowerShell and C# since they were introduced.