
Every day, system administrators must perform several standard operations on the many files and folders on their servers. Windows. These tasks often involve managing user data on shared resources and ensuring proper backups. To reduce the amount of manual work this represents, you can use PowerShell.
In this article, you will learn how to use PowerShell to:
- Display objects in a directory
- Create files and folders
- Delete files and folders
- Copy files and folders
- Move files or directories
- Rename files
- Change file extensions
- And much more
Before you begin, make sure your system policy allows you to run PowerShell scripts.
Display objects in a directory
To view the contents of a directory on a Windows file server, use the Get-ChildItem cmdlet. To show all hidden files, add the -Force parameter. The following command shows all root objects in the “Shared” folder.
Here you can learn about: Fix: The Update Is Not Applicable To Your Device
- Get-ChildItem -Force \\ fs \ Shared
If you also want to see all subfolders and their contents, add the -Recurse parameter:
- Get-ChildItem -Force \\ fs \ Shared -Recurse
To filter the results, add the parameters Filter, Exclude, Include and Path to the Get-ChildItem cmdletFor advanced object filtering, use the Where-Object cmdlet. The sequence of commands below and find all executable files in the IT archive that have been modified after the 1st of April 2018.
- Get-ChildItem -Path \\ fs \ Shared \ IT -Recurse -Include * .exe | Where-Object -FilterScript {($ _.LastWriteTime -gt '2018-04-01')}
Create files and folders with PowerShell
To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of item you want to create, such as a directory, file, or registry key.
This command, for example, creates a folder:
- New-Item -Path '\\fs\Shared\NewFolder' -ItemType Directory
And this creates an empty file:
- New-Item -Path '\\fs\Shared\NewFolder\newfile.txt' -ItemType File
Create files and write data to them
There are at least two built-in methods for creating a file and writing data to it. The first is to use the Out-File cmdlet:
- $text = 'Hello World!' | Output File $text -FilePath C:\data\text.txt
To overwrite an existing file, use the –Force switch parameter. You can also create files with the Export-Csv cmdlet, which exports the result to a csv file that can be opened in Excel:
- Get-ADuse -Filter * | Export-Csv -Path C:\data\ADusars.csv
Create files after verifying that they do not already exist
The following script Checks if a specific file (pctxt) already exists in a particular folder. If the file does not exist yet, the script generates a list of all AD computers and saves it to a new file called pctxt:
# create a series of text files
$files = Get-ChildItem C:\data\*.txt | select -expand fullname
# check if file exists in array
$ files -match «pc.txt»
# if match returns "True" then exit, if match returns "False" then create a report
if ($files -eq 'False') {
Get-ADComputer -Filter * | Export-Csv -Path C:\data\pc.txt
}
more {exit}
Delete files and folders with PowerShell
To remove objects, use the Remove-Item cmdlet. Note that you will be prompted for confirmation at runtime if the object is not empty. The following example shows how to delete the IT folder, all its subfolders, and the files it contains:
Delete-item-Path '\\fs\shared\it\'
RSVP
The item at \\pdc\shared\ has children and the Recurse parameter was not specified. If you continue, all children will be deleted with the item.
Are you sure you want to continue?
[Y] Yes [A] Yes to all [N] No [L] Not to all [S] Suspend [?] Help
(default is “Y”):
If you have already verified that all objects in a folder need to be deleted, you can use the Recurse switch to skip the confirmation step:
- Delete-item -Path '\\fs\shared\it\' -Recurse
Delete files and folders older than X days
Sometimes it is necessary to clean up old files from a particular directory. Here is how to accomplish this task:
$Folder = "C:\Backups"
#remove files older than 30 days
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {! $_. PsIsContainer -and $_. LastWriteTime -lt (Get-Date).AddDays (-30)} |
ForEach-Object {
$_ | del -Force
$_. FullName | Output file C:\log\deletedbackups.txt -Append
}
Delete files after verifying they exist
Here's how to verify that a file exists and delete it if it does:
$FileName = 'C:\data\log.txt'
If (Test-Path $FileName) {
Delete item $FileName
}
Delete files on multiple computers with a single script
To delete files on remote computers, you must have security permissions to access them. Make sure to use UNC paths so that the script can correctly determine the location of the files.
$filelist = @("\c$\Temp", "\c$\Backups") # variable to delete files and folders
$ computerlist = Get-Content C:\data\pc.txt # get the list of remote computers
foreach ($computer in $computer list) {
foreach ($file in $filelist) {
$ filepath = Join-Path «\\$computer\» «$filelist» # generate unc paths to files and folders
if (test path $ file path)
{
Delete item $filepath -force -recurse -ErrorAction Continue}}}
Copy files and folders with PowerShell
El Copy-Item cmdlet allows you to copy objects from one path to another. The following command creates a backup by copying the usars.xlsx file from a remote computer (fs) and saving it to another (fs2) over the network:
- Copy item -Path\\ fs\Shared\it\usas.xlsx -Destination\\ fs2\Backups\it\usas.xlsx
If the destination file already exists, the copy attempt will fail. To overwrite the existing file, even if it is read-only, use the -Force parameter.
- Copy Item -Path\\ fs\Shared\it\usas.xlsx -Destination\\ fs2\Backups\it\usas.xlsx -Force
Copy files with PowerShell to or from a remote computer
If you are copying files to or from remote computers, be sure to use UNC paths.
E.g., use this command to copy files from a remote file server to the local C: directory:
- Copy element \\ fs \ c $ \ temp -Recurse C: \ data \
To copy files from your local directory to the remote folder, simply reverse the source and destination locations:
- Copy item C:\data\-Recurse\\fs\c$\temp
Copy multiple files from one server to another over the network using a script
You can also copy files from one remote server to another. The following script recursively copies the folder \\ fs \ Shared \ temp in \\ fs \ Shared \ test:
- Copy element \\ fs \ Shared \ temp -Recurse \\ fs \ Shared \ test
Copy only certain types of files
To copy only certain files from the source to the destination, use the -Filter parameter. For example, the following command copies only txt files from one folder to another:
- Copy element -Filter *.txt -Path \\ fs \ Shared \ it -Recurse -Destination \\ fs2 \ Shared \ text
Copy files using XCOPY and ROBOCOPY commands or COM objects
You can also run the XCOPY and ROBOCOPY commands to copy files or use COM objects, as in the following example:
- (New-Object -ComObject Scripting.FileSystemObject).CopyFile('\\fs\Shared', 'fs2\Backup')
Move files and directories with PowerShell
El Move-Item cmdlet moves an item, along with its properties, contents, and children, from one location to another. You can also move a file or subdirectory from one directory to another location.
The following command moves a specific backup file from one location to another:
- Move-Item -Path \\ fs \ Shared \ Backups \ 1.bak -Destination \\ fs2 \ Backups \ archive \ 1.bak
This script moves the entire Backups folder and its contents to another location:
- Move-Item -Path \\ fs \ Shared \ Backups -Destination \\ fs2 \ Backups \ archive
The Backups directory and all its files and subfolders will appear in the archive directory.
Rename files with Powershell
El Rename-Item cmdlet allows you to rename an object without touching its contents. It is not possible to move items using the Rename Item command. To do this, you need to use the Move-Item cmdlet, as explained above.
The following command renames a file:
- Rename Item -Path «\\fs\Shared\temp.txt» -NewName «new_temp.txt»
Rename multiple files
To rename multiple files at once, use a script like this:
$files = Get-ChildItem -Path C:\Temp #create list of files
foreach ($file in $files)
{
$newFileName = $file.Name.Replace("A", "B") #replace "A" with "B"
Rename item $file$newFileName
}
Edit file extensions with PowerShell
You can also use Rename-Item to change file extensions. If you want to change the extensions of multiple files at the same time, use the Rename-Item cmdlet with the Get-ChildItem cmdlet.
The following script changes all file extensions from “txt” to “bak”. The wildcard character (*) is used to include all text files:
- Get-ChildItem \\ fs \ Shared \ Logs \*.txt | Rename Item -New Name {$_.name -Replace '\.txt$', '.bak'}
Get-Content: How to read the contents of a file in PowerShell?
The Get-Content cmdlet is one of the must-have commands when analyzing PowerShell scripts. It will allow you to read the contents of a file in PowerShell , which is a very common action. In addition to reading the data, we can import the data into a variable to use in the PowerShell script. You can use Get-Content to retrieve the contents of a log file, for example.
We will see that Get-Content is a powerful cmdlet which is capable of doing more than just retrieving the contents of a file in its entirety, hence the interest in dedicating a full article to it. This cmdlet works in Windows Powershell 5.1 and PowerShell, including the latest version to date: PowerShell 7.1.1.
II. Simply read the contents of a file
To start with, simply We will read the contents of a text file which will contain a list of values. To follow this part of the tutorial, we invite you to create a file called » Paystxt » and store it in » C:\TEMP«. This file must have the following content:
- France
- Costa Rica
- Belgium
- Swiss
- Spain
- Colombia
- Canada
- Brazil
- Iceland
- Nicaragua
Steps to read content in Powershell
- Step 1:: To read and display the contents of this file on the console, the command is super simple as you just need to specify the file name (or the full path if it is not in the current directory):
- Step 2:: You get the content «C:\TEMP\Pays txt»
- Step 3:: The parameter -Path will be used implicitly for this value. If we type the command below, it is the same.
- Get-Content -Path «C:\TEMP\Pays txt»
NOTE: : Displaying content in the console is not of much use. It is more interesting when we are going to store the content of the file in a variable in order to be able to exploit it. All you have to do is create a variable, for example $ Country , and give it the contents of the file as a value:
- $Country = Get-Content «C:\TEMP\Pays txt»
Out of curiosity, we can look at the type of the variable $ Country after having assigned a value to it:
- $Country.GetType()
We can see that we get two parts relevant information: » Object [] " Y " System. Array «. We are dealing with an object in the form of an array of values; it is interesting!
To count the number of items in this text file, we can do it in two different ways:
- $ Pays.Count
- ($Country | MeasureObject).Count
We have 10 elements, since it is an array the first value corresponds to index 0 and the last to index 9 (since we only have 10 elements). Therefore, the value of index 0 will be "France" and the value of index 9 will be Nicaragua.
If you want to check the value that is at index 0, that is, the first value, it is very simple:
- $ Country [0]
Or if you prefer, it comes down to doing:
- (Get content «C:\TEMP\Pays txt») [0]
Along the same lines, to retrieve the last value without knowing the exact index number, there is a trick! Just use “-1” as the number for the index:
- (Get content «C:\TEMP\Pays txt») [ -1 ]
Instead of retrieving the file content as an array, we can retrieve it as a single string. Simply add the parameter -Raw to command:
- Get-Content -path «C:\TEMP\Pays txt» -raw
Let's continue with some practical examples.
III. The tail of Linux in PowerShell style
En Linux, it is very common to use the command tail to display the last lines of a file. I often use it to query a log file, especially since the output is dynamic: if lines are added to the file, they will be displayed in the console as it progresses.
It is very practical and it is possible to do the same in PowerShell, using Get-Content and an option called… -Tail and a second option -Wait ! ?
Without the -Wait option, we can recover the last X lines of a file using -Tail alone. For example, to retrieve the last 5 lines of our Pays txt file:
- Get-Content «C:\TEMP\Pays txt» -Tail 5
Now, if we want to display the last 5 lines and wait to retrieve future lines added to the file, we will use this syntax:
- Get-Content «C:\TEMP\Pays txt» -Tail 5 -wait
To test, run the above command and then modify the file » Pays txt » to add a line: You will see that it is displayed almost in real time in the PowerShell console where the command is run.
In fact, with the command -wait , Get-Content keeps the file open and checks every second for new content. To end the execution of the command, it is very simple, just do a "CTRL + CLOSE«.
You should keep in mind that it may use the -Wait option only- In this case, the entire file will be displayed in the console and then remain pending.
- Get-Content «C:\TEMP\Pays txt» -Wait
IV. Get the first X lines of a file
In the same spirit, we can retrieve the first few lines of a file. In this case, we will not use -Tail but -TotalCount en su place. Here again, you need to specify the number of lines to display.
- Get-Content «C:\TEMP\Pays txt» -TotalCount 5
On the other hand, and it is logical, the -Wait option is not useful with the -TotalCount option.
V. NTFS: See a sequence secret in a file
The file NTFS The system has the distinction of having different » flows » in which to store data. When data is written to a file, are stored in the $DATA stream. So when we query the file, we will read the contents of this data stream.
Also, we can see that our file » Pays txt » has this flow thanks to the Get-Item command:
- Get item "C:\TEMP\Pays txt" -Stream *
We also notice that the console only returns this data stream.
The good thing is that you can create your own transmission to hide the data inside! ?
All you have to do is add data to our file » Pays txt ", specifying the sequence in which to send the data. For example, let's create the flow » Creds » with the value » Password".
- Add-Content -Path «C:\TEMP\Pays txt» -Stream Creds -Value «Password»
Now, if we show the list of transmissions in our file again, we get a new entry:
If we have fun displaying the contents of our file, we'll notice that the "Password" value I just added to the file is not displayed.
- Get content «C:\TEMP\Pays txt»
Additionally, to query the default stream, you can specify its name after the parameter -Stream from Get-Content (pay attention to the syntax):
- Get-Content «C:\TEMP\Pays txt» -Stream ':$DATA'
If you want to display the content of the transmission «Creds» that we have created previously, just say that:
- Get content «C:\TEMP\Pays txt» -Stream Creds
The command will return a single value: Password
The proof in the image below:
It's good to know, but we shouldn't tell ourselves that it's the miracle solution to hide passwords or sensitive data. In fact, one can scan the system with specific tools or Get-ChildItem looking for files that have a flow additional than the default $DATA.
This is a bit off topic, but to perform this analysis from a running folder as a starting point:
- Get-ChildItem -Recurse | ForEach{Get-Item$_. FullName -Stream *} | Where -ne' is transmitted: $Data'
This command will bring our Pays txt file and will transmit «Creds?». It is quite possible that Office documents are also highlighted by the command output with a sequence called » Zone.Identifier «. Contains an ID that allows the system to know the zone to which this file belongs (intranet, internet, etc., vis-à-vis IE zones).
You may be interested in reading about: How to Fix Searchindexer.exe High CPU Usage
Conclusion
As you can see, this is how you can manage your files with Powershell. By using the instructions in this article, you can automate a variety of simple operations related to file management on your operating systems. storage files and save time that you can spend on more important tasks. We hope we have helped you with this information.
My name is Javier Chirinos and I am passionate about technology. Ever since I can remember, I have been interested in computers and video games, and that passion has turned into a job.
I have been publishing about technology and gadgets on the Internet for over 15 years, especially in mundobytes.com
I am also an expert in online marketing and communication and have knowledge in WordPress development.