A Beginner’s Guide to Managing Files with PowerShell

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

Windows PowerShell is a powerful tool for managing your computer and data files. In this guide, we’ll explore how to create scripts with the help of Windows PowerShell commands to manage file system permissions and more.

The “sample powershell script file download” is a beginner’s guide to managing files with PowerShell. This article will provide you with the basics of using PowerShell to manage files on your computer.

A Beginner's Guide to Managing Files with PowerShell

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## For December 25th, get the current datetime and convert it to a string that looks like 12252020120000. $RightNow = (Get-Date). ToString(“MMddyyhhmmss”) ## In the C:folder directory, look for all files ending in.file. ## repeat over each one until just the name is returned. Each file’s name is saved in the $fileList variable. (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Fold ## Use a foreach loop to process each file foreach ($file in $filelist) { ## Add the datetime string to the end of the file name. $now + $file = $newname ## Using the datetime string, rename the old file to the new name. $newname -Verbose Rename-Item “C:Folder$file”

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## For December 25th, get the current datetime and convert it to a string that looks like 12252020120000. $RightNow = (Get-Date). ToString(“MMddyyhhmmss”) ## In the C:folder directory, look for all files ending in.file. ## repeat over each one until just the name is returned. Each file’s name is saved in the $fileList variable. (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Fold ## Use a foreach loop to process each file foreach ($file in $filelist) { ## Add the datetime string to the end of the file name. $now + $file = $newname ## Using the datetime string, rename the old file to the new name. $newname -Verbose Rename-Item “C:Folder$file”

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## For December 25th, get the current datetime and convert it to a string that looks like 12252020120000. $RightNow = (Get-Date). ToString(“MMddyyhhmmss”) ## In the C:folder directory, look for all files ending in.file. ## repeat over each one until just the name is returned. Each file’s name is saved in the $fileList variable. (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Begin a foreach loop by reading the C:foldersnumbers.txt file and returning each number. ## Convert the textual representation of the number to an integer for sorting [int] Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) | Out-File -File # Sort the numbers in ascending order and begin processing each one | Sort-Object | ForEach-Object # Pad 16 zeroes in front of each sorted number

Stay tuned for more file examples, including how to use PowerShell to create a file, how to use PowerShell to output to a file, and how to use PowerShell to verify whether a file exists.

In this video, you’ll learn how to get started dealing with files by using an example-based approach to motivate you to acquire the skills you’ll need.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • This lesson works with any version of Windows 10, however we’ll be using Windows 10 Enterprise, build 19043.
  • PowerShell 5.1 or above is required, although PowerShell 7.1 is used in this lesson.
  • An editor with the PowerShell extension, such as PowerShell ISE or Visual Studio Code.

Checking for the Existence of a File

When building an automation script, you’ll sometimes need to wait for files to appear before proceeding. PowerShell’s Test-Path cmdlet comes in handy for this. The Test-Path cmdlet is a built-in cmdlet that determines if a file/directory path exists or not by returning True or False.

How to Use the PowerShell Test-Path Cmdlet Related:How to Use the PowerShell Test-Path Cmdlet

Keeping an eye out for a single file

Assume you want to find out whether a single file exists. If that’s the case, the standard Test-Path PowerShell command will suffice.

Create a file (one.file) in your working directory or choose any other random file to show. Run the command below, changing the location (C:Folder) and file name with your test file’s name (one.file).

If the file (one.file) exists, the Test-Path cmdlet returns a True response. If you don’t, the console will show a False value.

C:Folderone.file is a test path.

A single file path is being tested.A single file path is being tested.

Multiple Files Checking

Despite the fact that the Test-Path cmdlet only tests for the presence of a single file, you may create a script to pass this cmdlet a list of files to verify. This is shown in the video below.

The script below determines whether or not three files in the $files array exist. If this is the case, it will reappear. If none of the files were located, it will return Files are missing.

Copy and paste the script below into a code editor, then save it as file existence.ps1 to see it in action. Make sure the files in the $files array have been generated ahead of time.

## Create an array with the file paths. $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” $files = “C:Folderone.file”, “C:Foldertwo.file”, “C:Folderthree.file” ## Use the Test-Path cmdlet to return an array of True/False results for each file path. Then, if all of the boolean values ## given by Test-Path are true, use the -notcontains operator to return True. -notcontains $filecheck = ($files | Test-Path) $false ## If $fileCheck is a true boolean (all files exist) $filecheck -eq $True) if($filecheck -eq $True) “All files were discovered, hurrah!” Write-Host else ## Write-Host “Files are missing” if $fileCheck is a boolean false (at least one file does not exist).

After you’ve saved the script, use the following command in PowerShell to launch it.

Related:How to Run a PowerShell Script from the Command Line and Other PowerShell Resources

Because all files exist, you’ll get a notice that says “All files discovered, hurrah!” underneath.

Checking the Existence of Multiple FilesChecking the Existence of Multiple Files

Delete files based on their last write time

Instead of only checking for file presence, you may wish to get rid of files that have been in your system for an extended period of time. If that’s the case, the script below will help you clear out your storage.

The script below looks for files with a file extension in all files in the C:folder folder. It then uses the Where-Object cmdlet to limit all of those files to only return those with a LastWriteTime value less than 30 days old. The Remove-Item cmdlet then deletes all of those files.

## Determine the current date and time $Now=Get-Date ## Find any files with a.file extension in the C:folder that have been ## modified in the previous 30 days. Remove them as soon as you find them. Where-Object’$ .LastWriteTime -gt Get-Childitem C:Folder*.file | Get-Childitem C:Folder*.file Remove-Item -Verbose | $Now.AddDays(-30)

Output from the file removal terminal.Output from the file removal terminal.

Using File Hash Attributes to Compare Files

Now that you’ve tried eliminating files, consider comparing files by file hash instead. A file hash is a one-of-a-kind cryptographic value based on the content of a file. When the contents of a file change, the hash value changes as well. This modification is an excellent approach to compare the contents of two files.

For example, suppose you have two files that you want to compare to make sure they’re identical. To do so, you’ll need to locate each file’s hash and then compare the hash values. You may use the sample script below to make this requirement a reality.

The script below uses the Get-FileHash cmdlet to calculate file hashes for one.file **and two.file files on demand, compares the Hash object property returned by the Get-FileHash cmdlet, compares them, and delivers different information depending on the result.

How to Use the Get-FileHash PowerShell Cmdlet in PowerShell

Add the -Algorithm option to the Get-FileHash command cmdlet to calculate the hash result using an alternative algorithm. As an example: SHA512 -Algorithm Get-FileHash “C:Folderone.file”

## Using the default algorithm of SHA256, calculate the file hash for each file. $file1 = Get-FileHash “C:Folderone.file” $file2 = Get-FileHash “C:Foldertwo.file” $file3 = Get-FileHash “C:Folderthree.file” ## Check for equivalence in the Hash object attribute supplied by Get-Filehash. $file1.Hash -eq $file2.Hash if ($file1.Hash -eq $file2.Hash) ## Let us know whether the file hashes match. Write-Host $file1.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match” Write-Host $file2.Hash “File Sizes Match otherwise Write-Host $file2.Hash ## Show the different hashes if the file hashes don’t match. “File Sizes Do Not Match,” Write-Host

The console is produced when the hash values match.The console is produced when the hash values match.

Using an Output File to Save Script Results

Printing a script’s output to the console is useful for a variety of reasons, including development and file comparison. When using scripts in an automated environment, however, you should sometimes record the script results in an output file as well.

The Out-File cmdlet is a wonderful method to send output to a file that would ordinarily be seen in the PowerShell console.

Related:Using the PowerShell Out-File Cmdlet to Redirect Output to a File

Create a file called numbers.txt in your working directory with a set of random eight-digit numbers to illustrate writing script results to an output file. Perhaps you’d want to sort these numbers, add a few zeroes to the front of each one, and save the results in a new file.

Set-Content -Path ‘numbers.txt’ -Value ‘912450033’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘235646123’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ -Value ‘523366623’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘824582456’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt’ Set Set-Content -Path ‘numbers.txt’ -Value ‘119240550’ Set-Content -Path ‘numbers.txt’ Set-Content -Path ‘numbers.txt

Take a look at the following example. This example reads the numbers.txt file, sorts the list of numbers in ascending order, pads each number with 16 zeroes, and saves the sorted and padded numbers to the C:tempsorted.file text file.

## Read the C:foldersnumbers.txt file returning each number and start a ## foreach loop. Get-Content -Path C:Foldernumbers.txt | ForEach-Object -Process { ## Convert the string representation of the number to an integer for sorting [int]$_ # Sort the numbers in ascending order and start processing each number } | Sort-Object | ForEach-Object { # Pad 16 zeroes in front of every sorted number $_.ToString(“0000000000000000”) } | Out-File -FilePath C:tempSorted.file -Verbose ## Write the results to another file

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.ToString(“0000000000000000”) -Verbose path C:tempSorted.file ## Save the findings to a different file.

The output file was successfully produced.The output file was successfully produced.

The sorted numbered list outputted to a text file called Sorted.file is seen below.

Numbers that have been sortedNumbers that have been sorted

Adding a String of Dates to a Filename

You previously changed the contents of a file. But this time, let’s look at how to add a date string to a filename. A date string is an easy technique to enhance your file structure, and descriptive file names help folder scanning and sorting.

Take a look at the following example. This example searches all files with a file extension in the C:folder and renames them all with the current datetime string prefixed.

## Find the current datetime and convert to a string that ## looks like 12252020120000 for December 25th $Now = (Get-Date).ToString(“MMddyyhhmmss”) ## Find all files with a .file extension in the C:folder directory ## iterate over each one to only return the name. Store each file name ## in the $fileList variable $filelist = (Get-ChildItem “C:Folder*.file” | ForEach-Object {$_.name}) ## Process each file in a foreach loop foreach ($file in $filelist) { ## Prepend the datetime string to the file name $newname = $Now + $file ## Rename the old file to the new name with the datetime string Rename-Item “C:Folder$file” $newname -Verbose }

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

.name) $filelist = (Get-ChildItem “C:Fold ## Use a foreach loop to process each file foreach ($file in $filelist) { ## Add the datetime string to the end of the file name. $now + $file = $newname ## Using the datetime string, rename the old file to the new name. $newname -Verbose Rename-Item “C:Folder$file”

Each file name now begins with the date string, as seen below.

Files Have Been RenamedFiles Have Been Renamed

Creating Files & Directories With PowerShell New-Item

The files above were generated via several processes, but what if you just want to create a file or directory? The New-Item command in PowerShell generates both files and folders. Not only that, but you can also make Symbolic Links, Junctions, and Hard Links, but these are seldom utilized.

Two examples of using PowerShell New-Item to create a file and a folder are shown below.

# Creating a Directory using PowerShell New-Item New-Item -Name ‘Folder’ -ItemType ‘Directory’ # Create a file called Testfile.txt in the previously established directory using PowerShell New-Item. ‘New-Item’ -ItemType’File’ -Name’TestFile.txt’ -Path’.Folder’

1647499998_659_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell New-Item Command to Create a File and Folder

Move-Item is a PowerShell command that allows you to move files.

How would you go about relocating a file produced in the Folder directory to the parent directory? The Transfer-Item command in PowerShell not only moves single files or directories, but it also has filtering features to help you move material swiftly from one area to the next.

You’re relocating the previously produced file, TestFile.txt, to the parent directory in the example below. To relocate the file, use the PowerShell move item command, Move-Item, using the syntax.. to indicate the parent directory from the present position.

# To relocate the target file, use the PowerShell Move-Item command. Move-Item -Destination ‘..’ -Path ‘.TestFile.txt’ # Check to see whether the file is still there in the directory. Get-ChildItem # Set the parent directory’s path. Set-Location is a command that allows you to specify a location. # Check to see whether the file is there in the directory. Get-ChildItem

1647499999_849_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellWith the PowerShell move file command, Relocate-Item, you may move a file to its parent directory.

Changing Names Using PowerShell’s Rename-Item Command

Perhaps TestFile.txt isn’t the best name for the file now that it’s been relocated. Naturally, the Renaming-Item PowerShell rename command works to rename things like files and folders. Change the name of TestFile.txt to RenamedFile.txt and the directory Folder to RenamedFolder in the example below.

# To rename a file, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # To rename a folder, use the PowerShell rename command Rename-Item -Path ‘.TestFile.txt’ -NewName ‘RenamedFile.txt’ # Checking that the PowerShell rename command worked as expected Get-ChildItem

1647500000_619_A-Beginner039s-Guide-to-Managing-Files-with-PowerShellUsing the PowerShell rename command, Rename-Item, you may rename a file or folder.

Conclusion

As you can see, PowerShell includes a plethora of cmdlets and techniques for dealing with files. And this lesson merely scratched the surface of the subject!

Take what you’ve learned so far and expand on it. See what you can come up with in terms of scripts to assist you with your everyday activities. What are your plans for the future?

PowerShell is a command-line tool that provides an interface for managing files. This “A Beginner’s Guide to Managing Files with PowerShell” will teach you the basics of the program. Reference: powershell automation scripts.

Frequently Asked Questions

How do I learn PowerShell for beginners?

A: The easiest way to learn PowerShell is by using the online training. Otherwise, you can use a GUI or console-based text editor like Atom or SublimeText (both are free and widely used) to edit files in your filesystem without necessitating any programming knowledge.

Is PowerShell easy to learn?

A: PowerShell is a highly flexible and powerful command line framework. It has been used in many different ways by commercial software companies as well as by IT professionals that require flexibility of usage for their skill set.

What can I use PowerShell for?

A: The PowerShell is a command line tool used to automate system administration and configuration tasks using the .NET Framework. It can also be used for remote computer management, application deployment and scripting on Windows operating systems such as Windows 10/8.1/7 or even Linux

Related Tags

  • powershell commands
  • powershell script example
  • powershell rename file
  • powershell basic commands for beginners
  • powershell get-command

Table of Content