File and Folder Management Made Easy with PowerShell
In this post, we will share a useful PowerShell script designed for effective file and folder management. This script provides functionality to create, copy, and delete files and folders, making it a handy tool for system administrators and power users alike.
Additionally, if you’re looking for a robust server management solution, check out our software, ServerEngine, available at https://serverengine.co. Now, lets dive into the script.
### Step 1: Set the Source and Destination Paths
In this step, we will define the source directory and the destination directory where the files will be copied. Adjust these paths according to your requirements.
$sourcePath = 'C:\SourceFolder' $destinationPath = 'C:\DestinationFolder'
### Step 2: Create Destination Directory
Before copying files, it is essential to ensure that the destination folder exists. This step will check for the existence of the destination directory and create it if it does not exist.
if (-Not (Test-Path -Path $destinationPath)) { New-Item -ItemType Directory -Path $destinationPath Write-Host "Destination folder created: $destinationPath" }
### Step 3: Copy Files from Source to Destination
Now, we will copy all files from the source directory to the destination directory. This command will handle files safely, creating a copy while maintaining the original files intact.
Get-ChildItem -Path $sourcePath -File | ForEach-Object { Copy-Item -Path $_.FullName -Destination $destinationPath Write-Host "Copied: $($_.Name) to $destinationPath" }
### Step 4: Delete Files Older than 30 Days
In the final step, we will delete files in the source directory that are older than 30 days. This helps in maintaining a clean and efficient storage system.
$thresholdDate = (Get-Date).AddDays(-30) Get-ChildItem -Path $sourcePath -File | Where-Object { $_.LastWriteTime -lt $thresholdDate } | ForEach-Object { Remove-Item -Path $_.FullName -Force Write-Host "Deleted: $($_.Name) from $sourcePath" }
Feel free to modify the paths and parameters according to your specific use case. Stay tuned for more useful PowerShell scripts on our website!