This article is written by Brenton J.W. Blawat, the author of Mastering Windows PowerShell Scripting.
When you are automating tasks on servers and workstations, you will frequently run into situations where you need to manage files, folders, and registry items. PowerShell provides a wide variety of cmdlets that enable you to create, view, modify, and delete items on a system.
(For more resources related to this topic, see here.)
In this article, you will learn many techniques to interact with files, folders, and registry items. These techniques and items include:
Registry provider
Creating files, folders, registry keys, and registry named values
Adding named values to registry keys
Verifying the existence of item files, folders, and registry keys
Renaming files, folders, registry keys, and named values
Copying and moving files and folders
Deleting files, folders, registry keys, and named values
To properly follow the examples in this article, you will need to sequentially execute the examples. Each example builds on the previous examples, and some of these examples may not function properly if you do not execute the previous steps.
Registry provider
When you're working with the registry, PowerShell interprets the registry in the same way it does files and folders. In fact, the cmdlets that you use for files and folders are the same that you would use for registry items. The only difference with the registry is the way in which you call the registry path locations. When you want to reference the registry in PowerShell, you use the [RegistryLocation]:Path syntax. This is made available through the PowerShell Windows Registry Provider.
While referencing [RegistryLocation]:Path, PowerShell provides you with the ability to use registry abbreviations pertaining to registry path locations. Instead of referencing the full path of HKEY_LOCAL_MACHINE, you can use the abbreviation of HKLM. Some other abbreviations include:
HKLM: Abbreviation for HKEY_LOCAL_MACHINE hive
HKCU: Abbreviation for HKEY_CURRENT_USER hive
HKU: Abbreviation for HKEY_USERS hive
HKCR: Abbreviation for HKEY_CLASSES_ROOT hive
HKCC: Abbreviation for HKEY_CURRENT_CONFIG hive
For example, if you wanted to reference the named values in the Run registry key for programs that start up on boot, the command line syntax would look like this:
HKLM:SoftwareMicrosoftWindowsCurrentVersionRun
While it is recommended that you don't use cmdlet aliases in your scripts, it is recommended, and a common practice, to use registry abbreviations in your code. This not only reduces the amount of effort to create the scripts but also makes it easier for others to read the registry locations.
Creating files, folders, and registry items with PowerShell
When you want to create a new file, folder, or registry key, you will need to leverage the new-item cmdlet. The syntax of this command is new-item, calling the –path argument to specify the location, calling the -name argument to provide a name for the item, and the -ItemType argument to designate whether you want a file or a directory (folder). When you are creating a file, it has an additional argument of –value, which allows you to prepopulate data into the file after creation. When you are creating a new registry key in PowerShell, you can omit the –ItemType argument as it is not needed for registry key creation. PowerShell assumes that when you are interacting with the registry using new-item, you are creating registry keys. The new-item command accepts the -force argument in the instance that the file, folder, or key is being created in a space that is restricted by User Account Control (UAC).
To create a new folder and registry item, do the following action:
New-item –path "c:Program Files" -name MyCustomSoftware –ItemType Directory
New-item –path HKCU:SoftwareMyCustomSoftware -force
The output of this is shown in the following screenshot:
The preceding example shows how you can create folders and registry keys for a custom application. You first create a new folder in c:Program Files named MyCustomSoftware. You then create a new registry key in HKEY_CURRENT_USER:Software named MyCustomSoftware.
You start by issuing the new-item cmdlet followed by the –path argument to designate that the new folder should be placed in c:Program Files. You then call the –name argument to specify the name of MyCustomSoftware. Finally, you tell the cmdlet that the -ItemType argument is Directory. After executing this command you will see a new folder in c:Progam Files named MyCustomSoftware.
You then create the new registry key by calling the new-item cmdlet and issuing the –path argument and then specifying the HKCU:SoftwareMyCustomSoftware key location, and you complete it with the –force argument to force the creation of the key. After executing this command, you will see a new registry key in HKEY_CURRENT_USER:Software named MyCustomSoftware.
One of the main benefits of PowerShell breaking apart the -path, -name, and -values arguments is that you have the ability to customize each of the values before you use them with the new-item cmdlet. For example, if you want to name a log file with the date stamp, add that parameter into a string and set the –name value to a string.
To create a log file with a date included in the filename, do the following action:
$logpath = "c:Program FilesMyCustomSoftwareLogs"
New-item –path $logpath –ItemType Directory | out-null
$itemname = (get-date –format "yyyyMMddmmss") + "MyLogFile.txt"
$itemvalue = "Starting Logging at: " + " " + (get-date)
New-item –path $logpath -name $itemname –ItemType File –value $itemvalue
$logfile = $logpath + $itemname
$logfile
The output of this is shown in the following screenshot:
The content of the log file is shown in the following screenshot:
The preceding example displays how you can properly create a new log file with a date time path included in the log file name. It also shows how to create a new directory for the logs. It then displays how to include text inside the log file, designating the start of a new log file. Finally, this example displays how you can save the log file name and path in a variable to use later in your scripts.
You first start by declaring the path of c:Program FilesMyCustomSoftwareLogs in the $logpath variable. You then use the new-item cmdlet to create a new folder in c:Program FilesMyCustomSoftware named Logs. By piping the command to out-null, the default output of the directory creation is silenced. You then declare the name that you want the file to be by using the get-date cmdlet, with the –format argument set to yyyyMMddmmss, and by adding mylogfile.txt. This will generate a date time stamp in the format of 4 digits including year, month, day, minutes, seconds, and mylogfile.txt. You then set the name of the file to the $itemname variable. Finally, you declare the $itemvalue variable which contains Starting Log at: and the standard PowerShell date time information. After the variables are populated, you issue the new-item command, the –path argument referencing the $logpath variable, the –name argument referencing the $itemname variable, the –ItemType referencing File, and the –value argument referencing the $itemvalue variable. At the end of the script, you will take the $logpath and $itemname variables to create a new variable of $logfile, which contains the location of the log file. As you will see from this example, after you execute the script the log file is populated with the value of Starting Logging at: 03/16/2015 14:38:24.
Adding named values to registry keys
When you are interacting with the registry, you typically view and edit named values or properties that are contained with in the keys and sub-keys. PowerShell uses several cmdlets to interact with named values. The first is the get-itemproperty cmdlet which allows you to retrieve the properties of a named value. The proper syntax for this cmdlet is to specify get-itemproperty to use the –path argument to specify the location in the registry, and to use the –name argument to specify the named value.
The second cmdlet is new-itemproperty, which allows you to create new named values. The proper syntax for this cmdlet is specifying new-itemproperty, followed by the –path argument and the location where you want to create the new named value. You then specify the –name argument and the name you want to call the named value with. Finally, you use the –PropertyType argument which allows you to specify what kind of registry named value you want to create. The PropertyType argument can be set to Binary, DWord, ExpandString, MultiString, String, and Qword, depending on what your need for the registry value is. Finally, you specifythe –value argument which enables you to place a value into that named value. You may also use the –force overload to force the creation of the key in the instance that the key may be restricted by UAC.
To create a named value in the registry, do the following action:
$regpath = "HKCU:SoftwareMyCustomSoftware"
$regname = "BuildTime"
$regvalue = "Build Started At: " + " " + (get-date)
New-itemproperty –path $regpath –name $regname –PropertyType String –value $regvalue
$verifyValue = Get-itemproperty –path $regpath –name $regname
Write-Host "The $regName named value is set to: " $verifyValue.$regname
The output of this is shown in the following screenshot:
After executing the script, the registry will look like the following screenshot:
This script displays how you can create a registry named value in a specific location. It also displays how you can retrieve a value and display it in the console. You first start by defining several variables. The first variable $regpath defines where you want to create the new named value which is in the HKCU:SoftwareMyCustomSoftware registry key. The second variable $regname defines what you want the new named value to be named, which is BuildTime. The third variable defines what you want the value of the named value to be, which is Build Started At: with the current date and time. The next step in the script is to create the new value. You first call the new-itemproperty cmdlet with the –path argument and specify the $regpath variable. You then use the –name argument and specify $regname. This is followed by specifying the –PropertyType argument and by specifying the string PropertyType. Finally, you specify the –value argument and use the $regvalue variable to fill the named value with data.
Proceeding forward in the script, you verify that the named value has proper data by leveraging the get-itemproperty cmdlet. You first define the $verifyvalue variable that captures the data from the cmdlet. You then issue get-itemproperty with the –path argument of $regpath and the –name argument of $regname. You then write to the console that the $regname named value is set to $verifyvalue.$regname. When you are done with script execution, you should have a new registry named value of BuildTime in the HKEY_CURRENT_USER:SoftwareMyCustomSoftware key with a value similar to Build Started At: 03/16/2015 14:49:22.
Verifying files, folders, and registry items
When you are creating and modifying objects, it's important to make sure that the file, folder, and registry items don't exist prior to creating and modifying them. The test-path cmdlet allows you to test to see if a file, folder, or registry item exists prior to working with it. The proper syntax for this is first calling test-path and then specifying a file, folder, or registry location. The result of the test-path command is True if the object exists or False if the object doesn't exist.
To verify if files, folders, and registry entries exist, do the following action:
$testfolder = test-path "c:Program FilesMyCustomSoftwareLogs"
#Update The Following Line with the Date/Timestamp of your file
$testfile = test-path "c:Program FilesMyCustomSoftwareLogs201503163824MyLogFile.txt"
$testreg = test-path "HKCU:SoftwareMyCustomSoftware"
If ($testfolder) { write-host "Folder Found!" }
If ($testfile) { write-host "File Found!" }
If ($testreg) { write-host "Registry Key Found!" }
The output is shown in the following screenshot:
This example displays how to verify if a file, folder, and registry item exists. You first start by declaring a variable to catch the output from the test-path cmdlet. You then specify test-path, followed by a file, folder, or registry item whose existence you want to verify.
In this example, you start by using the test-path cmdlet to verify if the Logs folder is located in the c:Program FilesMyCustomSoftware directory. You then store the result in the $testfolder variable. You then use the test-path cmdlet to check if the file located at c:Program FilesMyCustomSoftwareLogs201503163824MyLogFile.txt exists. You then store the result in the $testfile variable. Finally, you use the test-path cmdlet to see if the registry key of HKCU:SoftwareMyCustomSoftware exists. You then store the result in the $testreg variable. To evaluate the variables, you create IF statements to check whether the variables are True and write to the console if the items are found. After executing the script, the console will output the messages Folder Found!, File Found!, and Registry Key Found!.
Copying and moving files and folders
When you are working in the operating system, there may be instances where you need to copy or move files and folders around on the operating system. PowerShell provides two cmdlets to copy and move files. The copy-item cmdlet allows you to copy a file or a folder from one location to another. The proper syntax of this cmdlet is calling copy-item, followed by –path argument for the source you want to copy and the –destination argument for the destination of the file or folder. The copy-item cmdlet also has the –force argument to write over a read-only or hidden file. There are instances when read-only files cannot be overwritten, such as a lack of user permissions, which will require additional code to change the file attributes before copying over files or folders. The copy-item cmdlet also has a –recurse argument, which allows you to recursively copy the files in a folder and its subdirectories.
A common trick to use with the copy-item cmdlet is to rename during the copy operation. To do this, you change the destination to the desired name you want the file or folder to be. After executing the command, the file or folder will have a new name in its destination. This reduces the number of steps required to copy and rename a file or folder.
The move-item cmdlet allows you to move files from one location to another. The move-item cmdlet has the same syntax as the copy-item cmdlet. The proper syntax of this cmdlet is calling move-item, followed by the –path argument for the source you want to move and the –destination argument for the destination of the file or folder. The move-item cmdlet also has the –force overload to write over a read-only or hidden file. There are also instances when read-only files cannot be overwritten, such as a lack of user permissions, which will require additional code to change the file attributes before moving files or folders. The move-item cmdlet does not, however, have a -recurse argument. Also, it's important to remember that the move-item cmdlet requires the destination to be created prior to the move. If the destination folder is not available, it will throw an exception. It's recommended to use the test-path cmdlet in conjunction with the move-item cmdlet to verify that the destination exists prior to the move operation.
PowerShell has the same file and folder limitations as the core operating system it is being run on. This means that file paths that are longer than 256 characters in length will receive an error message during the copy process. For paths that are over 256 characters in length, you need to leverage robocopy.exe or a similar file copy program to copy or move files.
All move-item operations are recursive by default. You do not have to specify the –recurse argument to recursively move files. To copy files recursively, you need to specify the –recurse argument.
To copy and move files and folders, do the following action:
New-item –path "c:Program FilesMyCustomSoftwareAppTesting" –ItemType Directory | Out-null
New-item –path "c:Program FilesMyCustomSoftwareAppTestingHelp" -ItemType Directory | Out-null
New-item –path "c:Program FilesMyCustomSoftwareAppTesting" –name AppTest.txt –ItemType File | out-null
New-item –path "c:Program FilesMyCustomSoftwareAppTestingHelp" –name HelpInformation.txt –ItemType File | out-null
New-item –path "c:Program FilesMyCustomSoftware" -name ConfigFile.txt –ItemType File | out-null
move-item –path "c:Program FilesMyCustomSoftwareAppTesting" –destination "c:Program FilesMyCustomSoftwareArchive" –force
copy-item –path "c:Program FilesMyCustomSoftwareConfigFile.txt" "c:Program FilesMyCustomSoftwareArchiveArchived_ConfigFile.txt" –force
The output of this is shown in the following screenshot:
This example displays how to properly use the copy-item and move-item cmdlets. You first start by using the new-item cmdlet with the –path argument set to c:Program FilesMyCustomSoftwareAppTesting and the –ItemType argument set to Directory. You then pipe the command to out-null to suppress the default output. This creates the AppTesting sub directory in the c:Program FilesMyCustomSoftware directory. You then create a second folder using the new-item cmdlet with the –path argument set to c:Program FilesMyCustomSoftwareAppTestingHelp and the –ItemType argument set to Directory. You then pipe the command to out-null. This creates the Help sub directory in the c:Program FilesMyCustomSoftwareAppTesting directory.
After creating the directories, you create a new file using the new-item cmdlet with the path of c:Program FilesMyCustomSoftwareAppTesting, the -name argument set to AppTest.txt, the -ItemType argument set to File; you then pipe it to out-null. You create a second file by using the new-item cmdlet with the path of c:Program FilesMyCustomSoftwareAppTestingHelp, the -name argument set to HelpInformation.txt and the -ItemType argument set to File, and then piping it to out-null. Finally, you create a third file using the new-item cmdlet with the path of c:Program FilesMyCustomSoftware, the -name argument set to ConfigFile.txt and the -ItemType argument set to File, and then pipe it to out-null.
After creating the files, you are ready to start copying and moving files.
You first move the AppTesting directory to the Archive directory by using the move-item cmdlet and then specifying the –path argument with the value of c:Program FilesMyCustomSoftwareAppTesting as the source, the –destination argument with the value of c:Program FilesMyCustomSoftwareArchive as the destination, and the –force argument to force the move if the directory is hidden. You then copy a configuration file by using the copy-item cmdlet, using the –path argument with c:Program FilesMyCustomSoftwareConfigFile.txt as the source, and then specifying the –destination argument with c:Program FilesMyCustomSoftwareArchiveArchived_ConfigFile.txt as the new destination with a new filename;, you then leverage the –force argument to force the copy if the file is hidden.
This follow screenshot displays the file folder hierarchy after executing this script:
After executing this script, the file folder hierarchy should be as displayed in the preceding screenshot. This also displays that when you move the AppTesting directory to the Archive folder, it automatically performs the move recursively, keeping the file and folder structure intact.
Renaming files, folders, registry keys, and named values
When you are working with PowerShell scripts, you may have instances where you need to rename files, folders, and registry keys. The rename-item cmdlet can be used to perform renaming operations on a system. The syntax for this cmdlet is rename-item and specifying the –path argument with path to the original object, and then you call the –newname argument with a full path to what you want the item to be renamed to. The rename-item has a –force argument to force the rename in instances where the file or folder is hidden or restricted by UAC or to avoid prompting for the rename action.
To copy and rename files and folders, do the following action:
New-item –path "c:Program FilesMyCustomSoftwareOldConfigFiles" –ItemType Directory | out-null
Rename-item –path "c:Program FilesMyCustomSoftwareOldConfigFiles" –newname "c:Program FilesMyCustomSoftwareConfigArchive" -force
copy-item –path "c:Program FilesMyCustomSoftwareConfigFile.txt" "c:Program FilesMyCustomSoftwareConfigArchiveConfigFile.txt" –force
Rename-item –path "c:Program FilesMyCustomSoftwareConfigArchiveConfigFile.txt" –newname "c:Program FilesMyCustomSoftwareConfigArchiveOld_ConfigFile.txt" –force
The output of this is shown in the following screenshot:
In this example, you create a script that creates a new folder and a new file, and then renames the file and the folder. To start, you leverage the new-item cmdlet which creates a new folder in c:Program FilesMyCustomSoftware named OldConfigFiles. You then pipe that command to Out-Null, which silences the standard console output of the folder creation. You proceed to rename the folder c:Program FilesMyCustomSoftwareOldConfigFiles with the rename-item cmdlet using the –newname argument to c:Program FilesMyCustomSoftwareConfigArchive. You follow the command with the –force argument to force the renaming of the folder.
You leverage the copy-item cmdlet to copy the ConfigFile.txt into the ConfigArchive directory. You first start by specifying the copy-item cmdlet with the –path argument set to c:Program FilesMyCustomSoftwareConfigFile.txt and the destination set to c:Program FilesMyCustomSoftwareConfigArchiveConfigFile.txt. You include the –Force argument to force the copy.
After moving the file, leverage the rename-item cmdlet with the -path argument to rename c:Program FilesMyCustomSoftwareConfigArchiveConfigFile.txt using the –newname argument to c:Program FilesMyCustomSoftwareConfigArchiveOld_ConfigFile.txt. You follow this command with the –force argument to force the renaming of the file. At the end of this script, you will have successfully renamed a folder, moved a file into that renamed folder, and renamed a file in the newly created folder.
In the instance that you want to rename a registry key, do the following action:
New-item –path "HKCU:SoftwareMyCustomSoftware" –name CInfo –force | out-null
Rename-item –path "HKCU:SoftwareMyCustomSoftwareCInfo" –newname ConnectionInformation –force
The output of this is shown in the following screenshot:
After renaming the subkey, the registry will look like the following screenshot:
This example displays how to create a new subkey and rename it. You first start by using the new-item cmdlet to create a new sub key with the –path argument of the HKCU:SoftwareMyCustomSoftware key and the -name argument set to CInfo. You then pipe that line to out-null in order to suppress the standard output from the script. You proceed to execute the rename-item cmdlet with the –path argument set to HKCU:SoftwareMyCustomSoftwareCInfo and the –newname argument set to ConnectionInformation. You then use the –force argument to force the renaming in instances when the subkey is restricted by UAC. After executing this command, you will see that the CInfo subkey located in HKCU:SoftwareMyCustomSoftware is now renamed to ConnectionInformation.
When you want to update named values in the registry, you will not be able to use the rename-item cmdlet. This is due to the named values being properties of the keys themselves. Instead, PowerShell provides the rename-itemproperty cmdlet to rename the named values in the key. The proper syntax for this cmdlet is calling rename-itemproperty by using the –path argument, followed by the path to the key that contains the named value. You then issue the –name argument to specify the named value you want to rename. Finally, you specify the –newname argument and the name you want the named value to be renamed to.
To rename the registry named value, do the following action:
$regpath = "HKCU:SoftwareMyCustomSoftwareConnectionInformation"
$regname = "DBServer"
$regvalue = "mySQLserver.mydomain.local"
New-itemproperty –path $regpath –name $regname –PropertyType String –value $regvalue | Out-null
Rename-itemproperty –path $regpath –name DBServer –newname DatabaseServer
The output of this is shown in the following screenshot:
After updating the named value, the registry will reflect this change, and so should look like the following screenshot:
The preceding script displays how to create a new named value and rename it to a different named value. You first start by defining the variables to be used with the new-itemproperty cmdlet. You define the location of the registry subkey in the $regpath variable and set it to HKCU:SoftwareMyCustomSoftwareConnectionInformation. You then specify the named value name of DBServer and store it in the $regname variable. Finally, you define the $regvalue variable and store the value of mySQLserver.mydomain.local.
To create the new named value, leverage new-itemproperty, specify the –path argument with the $regpath variable, use the –name argument with the $regname variable, and use the –value argument with the $regvalue variable. You then pipe this command to out-null in order to suppress the default output of the command. This command will create the new named value of DBServer with the value of mySQLserver.mydomain.local in the HKCU:SoftwareMyCustomSoftwareConnectionInformation subkey.
The last step in the script is renaming the DBServer named value to DatabaseServer. You first start by calling the rename-itemproperty cmdlet and then using the –path argument and specifying the $regpath variable which contains the HKCU:SoftwareMyCustomSoftwareConnectionInformation subkey; you then proceed by calling the –name argument and specifying DBServer and finally calling the –newname argument with the new value of DatabaseServer. After executing this command, you will see that the HKCU:SoftwareMyCustomSoftwareConnectionInformation key has a new named value of DatabaseServer containing the same value of mySQLserver.mydomain.local.
Deleting files, folders, registry keys, and named values
When you are creating scripts, there are instances when you need to delete items from a computer. PowerShell has the remove-item cmdlet that enables the removal of objects from a computer. The syntax of this cmdlet starts by calling the remove-item cmdlet and proceeds with specifying the –path argument with a file, folder, or registry key to delete.
The remove-item cmdlet has several useful arguments that can be leveraged. The –force argument is available to delete files, folders, and registry keys that are read-only, hidden, or restricted by UAC. The –recurse argument is available to enable recursive deletion of files, folders, and registry keys on a system. The –include argument enables you to delete specific files, folders, and registry keys. The –include argument allows you to use the wildcard character of an asterisk (*) to search for specific values in an object name or a specific object type. The –exclude argument will exclude specific files, folders, and registry keys on a system. It also accepts the wildcard character of an asterisk (*) to search for specific values in an object name or a specific object type.
The named values in the registry are properties of the key that they are contained in. As a result, you cannot use the remove-item cmdlet to remove them. Instead, PowerShell offers the remove-itemproperty cmdlet to enable the removal of the named values. The remove-itemproperty cmdlet has arguments similar to those of the remove-item cmdlet. It is important to note, however, that the –filter, -include, and –exclude arguments will not work with named values in the registry. They only work with item paths such as registry keys.
To set up the system for the deletion example, you need to process the following script:
# Create New Directory
new-item –path "c:program filesMyCustomSoftwareGraphics" –ItemType Directory | Out-null
# Create Files for This Example
new-item –path "c:program filesMyCustomSoftwareGraphics" –name FirstGraphic.bmp –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareGraphics" –name FirstGraphic.png –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareGraphics" –name SecondGraphic.bmp –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareGraphics" –name SecondGraphic.png –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareLogs" –name 201301010101LogFile.txt –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareLogs" –name 201302010101LogFile.txt –ItemType File | Out-Null
new-item –path "c:program filesMyCustomSoftwareLogs" –name 201303010101LogFile.txt –ItemType File | Out-Null
# Create New Registry Keys and Named Values
New-item –path "HKCU:SoftwareMyCustomSoftwareAppSettings" | Out-null
New-item –path "HKCU:SoftwareMyCustomSoftwareApplicationSettings" | Out-null
New-itemproperty –path "HKCU:SoftwareMyCustomSoftwareApplicationSettings" –name AlwaysOn –PropertyType String –value True | Out-null
New-itemproperty –path "HKCU:SoftwareMyCustomSoftwareApplicationSettings" –name AutoDeleteLogs –PropertyType String –value True | Out-null
The output of this is shown in the following screenshot:
The preceding example is designed to set up the file structure for the following example. You first use the new-item cmdlet to create a new directory called Graphics in c:program filesMyCustomSoftware. You then use the new-item cmdlet to create new files named FirstGraphic.bmp, FirstGraphic.png, SecondGraphic.bmp, and SecondGraphic.png in the c:Program FilesMyCustomSoftwareGraphics directory. You then use the new-item cmdlet to create new log files in c:Program FilesMyCustomSoftwareLogs named 201301010101LogFile.txt, 201302010101LogFile.txt, and 201303010101LogFile.txt. After creating the files, you create two new registry keys located at HKCU:SoftwareMyCustomSoftwareAppSettings and HKCU:SoftwareMyCustomSoftwareApplicationSettings. You then populate the HKCU:SoftwareMyCustomSoftwareApplicationSettings key with a named value of AlwaysOn set to True and a named value of AutoDeleteLogs set to True.
To remove files, folders, and registry items from a system, do the following action:
# Get Current year
$currentyear = get-date –f yyyy
# Build the Exclude String
$exclude = "*" + $currentyear + "*"
# Remove Items from System
Remove-item –path "c:Program FilesMyCustomSoftwareGraphics" –include *.bmp –force -recurse
Remove-item –path "c:Program FilesMyCustomSoftwareLogs" –exclude $exclude -force –recurse
Remove-itemproperty –path "HKCU:SoftwareMyCustomSoftwareApplicationSettings" –Name AutoDeleteLogs
Remove-item –path "HKCU:SoftwareMyCustomSoftwareApplicationSettings"
The output of this is shown in the following screenshot:
This script displays how you can leverage PowerShell to clean up files and folders with the remove-item cmdlet and the –exclude and –include arguments. You first start by building the exclusion string for the remove-item cmdlet. You retrieve the current year by using the get-date cmdlet with the –f parameter set to yyyy. You save the output into the $currentyear variable. You then create a $exclude variable that appends asterisks on each end of the $currentyear variable, which contains the current date. This will allow the exclusion filter to find the year anywhere in the file or folder names.
The first command is that you use the remove-item cmdlet and call the –path argument with the path of c:Program FilesMyCustomSoftwareGraphics. You then specify the –include argument with the value of *.bmp. This tells the remove-item cmdlet to delete all files that end in .bmp. You then specify –force to force the deletion of the files and –recurse to search the entire Graphics directory to delete the files that meet the *.bmp inclusion criteria but leaves the other files you created with the *.png extension.
The second command leverages the remove-item cmdlet with the –path argument set to c:Program FilesMyCustomSoftwareLogs. You use the –exclude argument with the value of $exclude to exclude files that contain the current year. You then specify –force to force the deletion of the files and –recurse to search the entire logs directory to delete the files and folders that do not meet the exclusion criteria.
The third command leverages the remove-itemproperty cmdlet with the –path argument set to HKCU:SoftwareMyCustomSoftwareApplicationSettings and the –name argument set to AutoDeleteLogs. After execution, the AutoDeleteLogs named path is deleted from the registry.
The last command leverages the remote-item cmdlet with the –path argument set to HKCU:SoftwareMyCustomSoftwareApplicationSettings. After running this last command, the entire subkey of ApplicationSettings is removed from HKCU:SoftwareMyCustomSoftware.
After executing this script, you will see that the script deletes the .BMP files in the c:Program FilesMyCustomSoftwareGraphics directory, but it leaves the .PNG files. You will also see that the script deletes all of the log files except the ones that had the current year contained in them. Last, you will see that the ApplicationSettings sub key that was created in the previous step is successfully deleted from HKCU:SoftwareMyCustomSoftware.
When you use the remove-item and -recurse parameters together, it is important to note that if remote-item cmdlet deletes all the files and folders in a directory, the –recurse parameter will also delete the empty folder and subfolders that contained those files. This is only true when there are no remaining files in the folders in a particular directory. This may create undesirable results on your system, and so you should use caution while performing this combination.
Summary
This article thoroughly explained the interaction of PowerShell with the files, folders, and registry objects. It began by displaying how to create a folder and a registry key by leveraging the new-item cmdlet. It also displayed the additional arguments that can be used with the new-item cmdlet to create a log file with the date time integrated in the filename. The article proceeded to display how to create and view a registry key property using the get-itemproperty and new-itemproperty cmdlets
This article then moved to verification of files, folder, and registry items through the test-path cmdlet. By using this cmdlet, you can test to see if the object exists prior to interacting with it. You also learned how to interact with copying and moving files and folders by leveraging the copy-item and move-item cmdlets. You also learned how to rename files, folders, registry keys and registry properties with the use of the rename-item and rename-itemproperty cmdlets. This article ends with learning how to delete files, folders, and registry items by leveraging the remove-item and remove-itemproperty cmdlets.
Resources for Article:
Further resources on this subject:
Azure Storage [article]
Hyper-V Basics [article]
Unleashing Your Development Skills with PowerShell [article]
Read more