We download file from the internet, and usually all files gets downloaded in the same folder.
We want to move the files to different folders, and folder can be named after their extension.
.png file wll be move into png folder.
.txt file will be moved to txt folder and so on.
How are we going to do that?
Here are the steps;
- Get all the files
- Loop over all the files
- For each file extract the extension
- Check if the folder already exists
- if folder does not exists, then we create it.
- Move the file to the new folder
Here is the function to do that.
We can either store the files in a $files variable first, like code below.
$files = Get-ChildItem -File;
foreach($file in $files) {
$foldername = $file.Extension.Substring(1);
if( -not (Test-Path -Path $foldername)) {
New-Item -ItemType Directory -Path . -Name $folderName;
}
Move-Item -Path $file.Name -Destination $foldername -Verbose;
}
Or, we can directly use the command in the foreach loop, itself.
foreach($file in (Get-ChildItem -File)) {
$foldername = $file.Extension.Substring(1);
if( -not (Test-Path -Path $foldername)) {
New-Item -ItemType Directory -Path . -Name $folderName;
}
Move-Item -Path $file.Name -Destination $foldername -Verbose;
}
Both of the approaches would work.