- 1 year ago
Powershell Script that moves files based on filename
Comment
1 / 1
Certainly! Here's an example PowerShell script that moves files based on their filename:
powershell# Set the source and destination directories
$sourceDirectory = "C:\Path\to\source"
$destinationDirectory = "C:\Path\to\destination"
# Set the filename pattern to match
$filenamePattern = "example*.txt" # Replace with your desired pattern
# Get the list of files in the source directory that match the pattern
$files = Get-ChildItem -Path $sourceDirectory -Filter $filenamePattern
# Move each file to the destination directory
foreach ($file in $files) {
$destinationPath = Join-Path -Path $destinationDirectory -ChildPath $file.Name
Move-Item -Path $file.FullName -Destination $destinationPath
Write-Host "Moved file $($file.Name) to $destinationPath"
}
In this script:
- Set the
$sourceDirectory
variable to the path of the source directory where the files are located. - Set the
$destinationDirectory
variable to the path of the destination directory where the files will be moved. - Set the
$filenamePattern
variable to the pattern of the filenames you want to match. You can use wildcard characters (*
and?
) to specify a pattern that matches multiple files. For example,"example*.txt"
will match any file in the source directory starting with "example" and ending with ".txt". - The script uses the
Get-ChildItem
cmdlet to get a list of files in the source directory that match the specified pattern. - It then iterates through each file using a
foreach
loop and moves it to the destination directory using theMove-Item
cmdlet. - Finally, it displays a message indicating the file that was moved and its new location.
Make sure to replace the source and destination directory paths, as well as the filename pattern, with the appropriate values for your scenario.