none
Script to sort files RRS feed

  • Question

  • Hi all

    I'm relatively new to powershell and still have a lot to learn. I hope you will help me with my script.

    Let's say I have this folder sctructure:

    Downloads
    - Projects
    - - Builds
    - - - 01
    - - - 02
    - - - 03
    - - Testing
    - - - 01
    - - - 02
    - - - 03
    - - Plans
    - - - 01
    - - - 02
    - - - 03
    - Notes

    Whenever I download a bunch of files and folders, they are all placed in the Downloads folder. I need my script to sort the files of filetypes xlxs, docx and pdf, into the folders below depending on their name.

    My script so far:

    [array]$Contents = Get-ChildItem "\\NAS\Downloads" -Exclude Projects,Notes
    
    [array]$Files = $Contents | Get-ChildItem -Recurse | where {$_.Name -like '*.xlsx' -or $_.Name -like '*.docx' -or $_.Name -like '*.pdf'}
    
    [array]$Keywords = "*Design*","*Plans*","*Testing*","*Notes*"
    
    If ($Files.Name -like $Keywords) {}

    Now what I would like to do is some sort of search in the files in my $Files array for the keywords and then whenever it hits a keyword it will move that file to the correct folder for that keyword. If there are any files/folders left, then they must be irrelevant and deleted.

    I hope you understand what I'm asking and that someone is able to help me. Thank you very much! :-)


    • Edited by Casper83DK Thursday, January 2, 2014 7:48 AM
    Thursday, January 2, 2014 7:46 AM

Answers

  • $Files = Get-ChildItem "\\NAS\Downloads" -Exclude Projects,Notes -Directory | Get-ChildItem  -Recurse -Include @('*.xlsx','*.docx','*.pdf') -File
     
    $Files |  %{
     switch -wildcard ($_.Name)
     {
      "*design*"{Write-host "$_ is Design"}
      "*plans*" {Write-host "$_ is Plans"}
      "*testing*" {Write-host "$_ is Testing"}
      "*notes*" {Write-host "$_ is Notes"}  
     }
    }
    


    Thursday, January 2, 2014 11:44 AM

All replies

  • Start like this:

    Your variable "$files" is  collection.  You need to enumerate a collection.

    $Files  |
         ForEach-Object{
              switch($_.
    Name){
                  'design' {}
                  'plans' {}
                 'testing' {}
              }
          }

    use help to study how "switch" statement works:

    help about_switch


            


    ¯\_(ツ)_/¯

    Thursday, January 2, 2014 8:31 AM
  • $Files = Get-ChildItem "\\NAS\Downloads" -Exclude Projects,Notes -Directory | Get-ChildItem  -Recurse -Include @('*.xlsx','*.docx','*.pdf') -File
     
    $Files |  %{
     switch -wildcard ($_.Name)
     {
      "*design*"{Write-host "$_ is Design"}
      "*plans*" {Write-host "$_ is Plans"}
      "*testing*" {Write-host "$_ is Testing"}
      "*notes*" {Write-host "$_ is Notes"}  
     }
    }
    


    Thursday, January 2, 2014 11:44 AM