Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell, Mass moving files of a certain type

I want to make a script which will take a parent directory which has a number of child directories which have files in them. Using a listing I wish to move all of the files in the child directories in to the parent directory.

I have created the following code so far which gives a listing of all the files of the specified type in the child directories but I am unsure how to a mass move of all the child files.

    Write-host "Please enter source Dir:"
$sourceDir = read-host

Write-Host "Format to look for with .  :"
$format = read-host

#Write-host "Please enter output Dir:"
#$outDir = read-host

$Dir = get-childitem -Path $sourceDir -Filter $format -recurse | format-table name

$files = $Dir | where {$_.extension -eq "$format"} 
$files #| format-table name
like image 745
Craig Hendley Avatar asked Aug 22 '11 17:08

Craig Hendley


1 Answers

A few things:

  1. You can pass the text you write to the screen directly to the read-host cmdlet, it saves you a line per user input.

  2. As a rule of thumb, if you plan to do more with an output of a command, DO NOT pipe it to the format-* cmdlets. The format cmdlets produces formatting objects that instructs powershell how to display the result on screen.

  3. Try to avoid assigning the result to a variable, if the result contains a large set of file system, memory consumption can go very high and you can suffer a performance degradation.

  4. Again, in terms of performance, try to use cmdlet parameters instead of the where-object cmdlet (server side filtering vs. client side). The first filters the objects on the target while the latter filters the objects only after the get to your machine.

The WhatIf switch will show you which files would have moved. Remove it to execute the command. You may also need to twick it to deal with duplicate file names.

$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for"

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Move-Item -Destination $sourceDir -Whatif
like image 147
Shay Levy Avatar answered Oct 13 '22 00:10

Shay Levy