How to write a Powershell script that cleans your computer
To create a PowerShell script, you can use any text editor such as Notepad, Notepad++, or Visual Studio Code. You will also need to have PowerShell installed on your computer. You can check if it is installed by opening a Command Prompt or PowerShell window and typing “powershell” and press enter.
Here is an example of a simple PowerShell script that displays the current date and time:
# This script displays the current date and time
$currentDate = Get-Date
Write-Host “Current date and time: $currentDate”
You can also run the script by right-clicking on the script file and selecting “Run with PowerShell”
It is important to note that PowerShell scripts can be used to perform a wide range of tasks, from simple operations like displaying text on the screen to complex tasks such as managing multiple servers or automating the deployment of software. Before running any script, it’s important to understand what it does and how it works, and to test it in a safe environment.
Here is an example of a PowerShell script that clears temp folders, logs, and unnecessary files, including child objects:
$RetentionTime = “7”
$Shell = New-Object -ComObject Shell.Application
$Recycler = $Shell.NameSpace(0xa)
foreach($item in $Recycler.Items())
$DeletedDatetime = Get-Date $DeletedDate
If($DeletedDays -ge $RetentionTime)
Remove-Item -Path $item.Path -Confirm:$false -Force -Recurse
$RecyclerError = $true
} -Credential $ComputerOBJ.Credential
Write-Host “All recycler items older than $RetentionTime days were deleted” -ForegroundColor Green
Write-Host “Unable to delete some items in the Recycle Bin.” -ForegroundColor Red
$Shell = New-Object -ComObject Shell.Application
$Recycler = $Shell.NameSpace(0xa)
foreach($item in $Recycler.Items())
$DeletedDatetime = Get-Date $DeletedDate
If($DeletedDays -ge $RetentionTime)
Remove-Item -Path $item.Path -Confirm:$false -Force -Recurse
$RecyclerError = $true
Write-Host “Unable to delete some items in the Recycle Bin.” -ForegroundColor Red
Write-Host “All recycler items older than $RetentionTime days were deleted” -ForegroundColor Green
Remove-item -Path $item.FullName -Confirm:$False -Recurse -ErrorAction Stop
Write-verbose “$($Item.path) – $($_.Exception.Message)”
} -Credential $ComputerOBJ.Credential
Remove-item -Path $item.FullName -Confirm:$False -Recurse -ErrorAction Stop
Write-verbose “$($Item.path) – $($_.Exception.Message)”
Write-host “Current Free Space on the OS Drive : $FreeSpaceGB GB” -ForegroundColor Yellow
$FreeSpaceGB = $False
Write-host “Final Free Space on the OS Drive : $FreeSpaceGB GB” -ForegroundColor Yellow
$FreeSpaceGB = $False
$Websites = Get-WebSite -ErrorAction Stop
Write-Output “No Websites”
} -Credential $ComputerOBJ.credential
Write-output “No Websites”
$Path = “$($Website.logFile.directory)\w3scv$($website.id)”.replace(“%SystemDrive%”,$env:SystemDrive)
LogPath = $Path
SiteName = $WebSite.name
$LogInfo += $Obj
$Websites = Get-WebSite -ErrorAction Stop
Write-output “No Websites”
$Path = “$($Website.logFile.directory)\w3scv$($website.id)”.replace(“%SystemDrive%”,$env:SystemDrive)
LogPath = $Path
SiteName = $WebSite.name
$LogInfo += $Obj
Write-Host “Please enter the computername to connect to or just hit enter for localhost” -ForegroundColor Yellow
$ComputerName = Read-Host
ComputerName = $env:COMPUTERNAME
Remote = $False
ComputerName = $Computername
Remote = $True
Write-Host “Please enter your credentials for the remote machine.” -ForegroundColor Yellow
Write-Host “PowerShell Remoting was successful” -ForegroundColor Green
Write-host “PowerShell Remoting FAILED press enter to exit script.” -ForegroundColor Red
Write-Host “Attempting to clean old Virus Definitions” -ForegroundColor Yellow
$Folders = $null
} -Credential $ComputerOBJ.Credential
Write-Host “Symantec Definition Directory could not be located. Skipping removal of old definitions.” -ForegroundColor Red
Write-Host “Symantec Definition Directory contained only current definitions.” -ForegroundColor Green
Write-Host “Symantec Definition Directory contained $PathCount folders.” -ForegroundColor Yellow
Clean-Path -Path $Folder.fullname -ComputerOBJ $Using:ComputerOBJ
} -Credential $ComputerOBJ.Credential
Write-host “All Old Virus Definition Files cleaned successfully.” -ForegroundColor Green
Write-Host “Symantec Definition Directory could not be located. Skipping removal of old definitions.” -ForegroundColor Red
Write-Host “Symantec Definition Directory contained only current definitions.” -ForegroundColor Green
Write-Host “Symantec Definition Directory contained $PathCount folders.” -ForegroundColor Yellow
Clean-Path -Path $Folder.fullname -ComputerOBJ $ComputerOBJ
Write-host “All Old Virus Definition Files cleaned successfully.” -ForegroundColor Green
Write-Host “Attempting to Run Windows Disk Cleanup With Parameters” -ForegroundColor Yellow
$ErrorActionPreference = ‘Stop’
Start-Process -FilePath Cleanmgr -ArgumentList ‘/sagerun:1’ -Wait
$ErrorActionPreference = ‘SilentlyContinue’
$ErrorActionPreference = ‘SilentlyContinue’
} -Credential $ComputerOBJ.Credential
Write-Host “Windows Disk Cleanup has been run successfully.” -ForegroundColor Green
Write-host “Desktop-Experience, Ink-Handwriting” -ForegroundColor Red
Write-Host “Attempting to Run Windows Disk Cleanup With Parameters” -ForegroundColor Yellow
$ErrorActionPreference = ‘Stop’
Start-Process -FilePath Cleanmgr -ArgumentList ‘/sagerun:1’ -Wait
Write-Host “Windows Disk Cleanup has been run successfully.” -ForegroundColor Green
Write-host “Desktop-Experience, Ink-Handwriting” -ForegroundColor Red
$ErrorActionPreference = ‘SilentlyContinue’
Write-Host “Running DISM to clean old servicepack files” -ForegroundColor Yellow
$ErrorActionPreference = ‘Stop’
$DISMResult = dism.exe /online /cleanup-Image /spsuperseded
$ErrorActionPreference = ‘SilentlyContinue’
$ErrorActionPreference = ‘SilentlyContinue’
} -Credential $ComputerOBJ.Credential
Write-Host “DISM Completed Successfully.” -ForegroundColor Green
Write-Host “Unable to clean old ServicePack Files.” -ForegroundColor Red
Write-Host “Running DISM to clean old servicepack files” -ForegroundColor Yellow
$ErrorActionPreference = ‘Stop’
$DISMResult = dism.exe /online /cleanup-Image /spsuperseded
$ErrorActionPreference = ‘SilentlyContinue’
$ErrorActionPreference = ‘SilentlyContinue’
$DISMResult = $False
$ErrorActionPreference = ‘SilentlyContinue’
Write-Host “DISM Completed Successfully.” -ForegroundColor Green
Write-Host “Unable to clean old ServicePack Files.” -ForegroundColor Red
Write-Output = $False
} -Credential $ComputerOBJ.Credential
$LogPaths = Get-IISLogPaths -ComputerOBJ $ComputerOBJ
Write-Host “No Websites were found on this server so no IIS log files will be present.” -ForegroundColor Yellow
Write-Verbose “Checking Website : $($Item.sitename)”
$LogFiles = $Null
} -Credential $ComputerOBJ.Credential
Delete-IISLogFile -ComputerOBJ $Computerobj -LogFile $File
Write-Host “No IIS Log Files Older than 30 days for this site.” -ForegroundColor Green
Write-Host “Cleanup of old IIS Log files completed!” -ForegroundColor Green
$ModuleLoad = $True
$ModuleLoad = $False
$LogPaths = Get-IISLogPaths
Write-Host “No Websites were found on this server so no IIS log files will be present.” -ForegroundColor Yellow
Write-Host “Checking Website : $($item.sitename)” -ForegroundColor Yellow
Write-Host “No Log File directory for this site.” -ForegroundColor Red
Delete-IISLogFile -ComputerOBJ $Computerobj -LogFile $File
Write-Host “No IIS Log Files Older than 30 days for this site.” -ForegroundColor Green
Write-Host “Cleanup of old IIS Log files completed!” -ForegroundColor Green
} -Credential $ComputerOBJ.Credential
Write-Host “`t$($File.BaseName) was older than 30 days and has been deleted”
Write-Host “Deleting files from ‘C:\Windows\SoftwareDistribution\'” -ForegroundColor Yellow
$WUpdateError = $false
$WUpdateError = $true
} -Credential $ComputerOBJ.Credential
Write-Host “Files Deleted Successfully” -ForegroundColor Green
Write-Host “Unable to stop the windows update service. No files were deleted.” -ForegroundColor Red
$WUpdateError = $false
$WUpdateError = $true
Write-Host “Files Deleted Successfully” -ForegroundColor Green
Write-Host “Unable to stop the windows update service. No files were deleted.” -ForegroundColor Red
$ProfileError = $false
$ProfileError = $true
} -Credential $ComputerOBJ.Credential
Write-host “Starting Profile : $Profile” -ForegroundColor Yellow
Clean-Path -Path $TempPath -ComputerOBJ $ComputerOBJ
Clean-Path -Path $DownloadPath -ComputerOBJ $ComputerOBJ
$ProfileError = $false
$ProfileError = $true
Write-host “Starting Profile : $Profile” -ForegroundColor Yellow
Clean-Path -Path $TempPath -ComputerOBJ $ComputerOBJ
Clean-Path -Path $DownloadPath -ComputerOBJ $ComputerOBJ
$ComputerOBJ = Get-Computername
$ComputerOBJ = Test-PSRemoting -ComputerOBJ $ComputerOBJ
$ComputerOBJ = Get-OrigFreeSpace -ComputerOBJ $ComputerOBJ
Clean-path -Path ‘C:\windows\Temp’ -ComputerOBJ $ComputerOBJ
Clean-path -Path ‘C:\Temp’ -ComputerOBJ $ComputerOBJ
Clean-path -Path ‘C:\ProgramData\Microsoft\Windows\WER\ReportArchive’ -ComputerOBJ $ComputerOBJ
Clean-path -Path ‘C:\ProgramData\Microsoft\Windows\WER\ReportQueue’ -ComputerOBJ $ComputerOBJ
Clean-path -Path ‘C:\ServiceProfiles\LocalService\AppData\Local\Temp’ -ComputerOBJ $ComputerOBJ
Write-Host “All Temp Paths have been cleaned” -ForegroundColor Green
TestFor-SymantecPath -ComputerOBJ $ComputerOBJ
Run-CleanMGR -ComputerOBJ $ComputerOBJ
Run-DISM -ComputerOBJ $ComputerOBJ
Process-IISLogs -ComputerOBJ $ComputerOBJ
Set-WindowsUpdateService -ComputerOBJ $ComputerOBJ
Get-Recyclebin -ComputerOBJ $ComputerOBJ
$ComputerOBJ = Get-FinalFreeSpace -ComputerOBJ $ComputerOBJ
$SpaceRecovered = $($Computerobj.finalfreespace) – $($ComputerOBJ.OrigFreeSpace)
Write-Host “Less than a gig of Free Space was recovered.” -ForegroundColor Yellow
Write-host “No Space Was saved :(“
Write-host “Space Recovered : $SpaceRecovered GB” -ForegroundColor Green
Sometimes it can be a hassle to edit the name, the artist, or the year of each music file in iTunes. In this article, I will show how to edit the metadata (i.e., the information) of multiple mp3 files at once by creating two functions, Get-MetaData and Set-MetaData, in PowerShell. The task in this article is to change the contributing artist names of mp3 files in the folder test.
The names of the contributing artists are represented with the year + “ “ + name. We want to remove the year + “ “ and transfer the year to the Year metadata.
Create a shell application
Before we even access the metadata of files, we need to create a Shell.Application COM (Component Object Model) object in PowerShell to interact with the Windows Shell, which provides access to various features of the Windows operating system.
$shell = New-Object -ComObject Shell.Application
Application Parent
----------- ------
System.__ComObject System.__ComObject
Access metadata of one MP3 file
Here, we will try to get metadata of the first song Asuka (320 kbps) with the method GetDetailsOf. The metadata is represented in numbers.
明日花
2005 HOI FESTA
Index Name
----- ----
0 Name
1 Size
2 Item type
3 Date modified
4 Date created
This code runs from the number 0 to 10,000 and creates a hash table (i.e., similar to a dictionary in Python) with the number (index) and name of the metadata that represents it (Name).
Install TagLib Sharp library
dotnet add package TagLibSharp --version 2.3.0
Get-ChildItem -Path C:\ -Filter "TagLibSharp.dll" -Recurse -ErrorAction SilentlyContinue
Edit metadata of one mp3 file
Create functions to access and edit metadata
We will run the Get-MetaData function on the test folder to read the metadata.
Use Excel to separate year and artist
We will now copy the metadata to Excel (or Google Sheets) for editing.
We will start editing the file artist and year in columns C and D respectively. These represent the parameters for the Set-MetaData function. We will write the function statement for the Set-MetaData function of each file in column E (See Figure 6). Formulae are used to edit the columns.
For example, the formula in:
Cell C1 = TRIM(SUBSTITUTE(B1, D1, “”)) (Get a new artist name by replacing year with blank ""
and removing unnecessary spaces.)
Cell D1 = LEFT(B1,4) (Get the year from the first 4 characters of the artist)
Cell E1 = “Set-MetaData -filePath ”&A1&“ -artist”&” ‘”&C1&”’ ”&“ -year ”&D1
Run Set-Metadata
We now copy column E into PowerShell. The output will be Figure 2.
Summary
Below is a summary of the workflow for this task.
Source Code
The details of my problem:
I have some .m4a
recording files. I can use the Explorer
to get detail from Properties > Details > Origin > Media created
. But as you may know, the Properties
window does not show time in HH:MM:SS
format but only in HH:MM
, and I do need the second
very much.
I learned a way to fetch info by Power Shell
code something like this:
(Get-Item C:\Users\natsu\Desktop\FolderName\RecordingFile.m4a).VersionInfo | select Media created
But, select Media created
returns an error, select "Media created"
returns blank value. I can avoid the space
in the path but I don’t know how to escape
it in the command.
May you please help me: (1) Try telling me the correct command for the Power Shell
. or (2) Other Applications that can read it in HH:MM:SS
format?
What did I try:
I did try sttmedia
but this application does not support the Media created
property.
I did try Explorer++
but this application can only show in HH:MM
format too.
What am I expecting:
I want to get my .m4a
files, for the Media created
property, in HH:MM:SS
format.
This PowerShell script recursively sorts image and video files in a specified folder by their creation date or media date, placing them into new directories named after the year and month of their creation or media date.
{ | |
{ | |
‘.png’, ‘.jpg’, ‘.jpeg’, ‘.tif’, ‘.tiff’ -Contains $extension { | |
} | |
‘.mp4’, ‘.avi’, ‘.mpeg’, ‘.3gp’, ‘.mov’, ‘.wmv’ -Contains $extension { | |
} | |
[] | |
{ | |
[]$mDate, “dd/MM/yyyy h:mm tt”, $null | |
} | |
{ | |
[]$creationDate, “dd/MM/yyyy h:mm:ss tt”, $null | |
} | |
} | |
} | |