- 1 year ago
Powershell: Place all files in a specified directory into separate, uniquely named subdirectories
To place all files in a specified directory into separate and uniquely named subdirectories using PowerShell, you can use the following script:
powershell$sourceDirectory = "C:\Path\to\source\directory"
$destinationDirectory = "C:\Path\to\destination\directory"
# Get all files in the source directory
$files = Get-ChildItem -Path $sourceDirectory -File
# Create a subdirectory for each file and move the file into it
foreach ($file in $files) {
$subdirectoryName = [System.IO.Path]::GetFileNameWithoutExtension($file.Name) + "_" + [System.Guid]::NewGuid()
$subdirectoryPath = Join-Path -Path $destinationDirectory -ChildPath $subdirectoryName
New-Item -ItemType Directory -Path $subdirectoryPath | Out-Null
Move-Item -Path $file.FullName -Destination $subdirectoryPath
}
Make sure to replace $sourceDirectory
and $destinationDirectory
with the actual paths to your source and destination directories, respectively.
The script uses Get-ChildItem
to retrieve all the files in the source directory. Then, for each file, it generates a unique subdirectory name by combining the base file name with a newly generated GUID. It creates a new directory with the generated subdirectory name inside the destination directory using New-Item
. Finally, it moves the file to the corresponding subdirectory using Move-Item
.
After running the script, each file in the source directory will be placed in a separate subdirectory within the destination directory. The subdirectories will have unique names based on the file names.