Home > Blockchain >  I have a file organiser powershell script which runs without any error but it doesnt perform the mov
I have a file organiser powershell script which runs without any error but it doesnt perform the mov

Time:04-28

It is a file organiser script I wrote for myself. For a specific purpose of mine. Whenever I try to run it It runs and closes off. But the move operation is not happening. The below comments may help you understand what the code is doing.Please help me on what am i doing wrong here. I am extremely new to Powershell Scripting.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# Global variable declarations
$global:pathsFromConfig = Get-Content -Path $PSScriptRoot"\MoverPaths.txt"
$global:categoriesFromConfig = Get-Content -Path $PSScriptRoot"\MoverCategories.txt"
$global:categryHash = @{}

# Method call to read configs, create dirs, & move files
readCreateAndMoveFiles

# Method definition
function readCreateAndMoveFiles{
    # Reads categories config.txt and splits them line by line
    # Adds each line as a key value pair to a hashtable
    foreach($category in $categoriesFromConfig)
    {
        $temp = $category -split ":"  
        $categryHash.add($temp[0].trim().toString(),($temp[1]).trim().toString())
    }

    # For each category in the hash table, calls create directory method, and then moves the files based on current category

    foreach($hashItem in $categryHash.GetEnumerator()){
        # Creates a directory with the Hash Key
        Foreach($pathToMonitor in $pathsFromConfig){
            $categoryFullPath = $pathToMonitor $hashItem.Name
            createDirectory($categoryFullPath)

            # Moves files into that directory 
            Set-Location -Path $pathToMonitor
            $extentions = $hashItem.Value
            Get-Item $extentions | Move-Item -Destination $categoryFullPath
            $categoryFullPath = ""
        }
    }
}
        
# Method Definition
function createDirectory ($categoryName)
{
    if(Test-Path -Path $categoryName)
    {
        # Directory already Exists!
    }
    else
    {
        # Creates Directory
        md $categoryName
    }
}

The config files are hereby:

MoverCategories.txt Images:*.jpg,*.jpeg,*.png,*.tiff,*.raw,*.heic,*.gif,*.svg,*.eps,*.ico Documents:*.txt,*.pdf,*.doc,*.docx,*.xls,*.xlsx,*.ppt,*.pptx,*.html,*.xls,*.csv,*.rtx

MoverPaths.txt

D:\Downloads\

CodePudding user response:

Try this

#specify path(s)
$path = "$env:USERPROFILE\Downloads"

## this is make an array of the extensions in the foloder
$extensions = Get-ChildItem -Path $path  | Select-Object -Unique  -Property @{label = 'ext'
  expression                                                                        = { $_.Extension.substring(1) }
}

## this function will 
function New-FoldersByName {
  param
  (
    [Parameter(Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Data to process')]
    $InputObject
  )
  process { 
    Set-Location $path
    if (!(Test-Path -PathType Container $InputObject )) {

      New-Item -ItemType directory -Name $InputObject.ext -WhatIf
      Write-Host -Message "A folder named $($InputObject.ext) does not exist. Creating..."
    }
    else {
      Write-Host -Message "A folder named $($InputObject.ext) already exists. Skipping..."
    }
  }
}



##this is a reuseable function to moves items in a folder into a subfolder named after the files extension
## if extension is .exe the file with be moved to ./EXE/filename.exe

function Move-ItemsByName {
  param
  (
    [Parameter(Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Data to process')]
    $InputObject
  )
  process {
    Set-Location -Path $path
    Move-Item -Path ('*.{0}' -f $InputObject.ext) -Destination ('{0}' -f $InputObject.ext) -WhatIf
  }
}

$extensions | New-FoldersByName
$extensions | Move-ItemsByName

CodePudding user response:

Found a way to do this. Thanks for all of your input. Now the script moves files. Instead of sending all extentions in a single shot, i made it into an array and sent it one by one. Now it works fine. If you guys could help me reduce the time of execution that would be great.But the code works now I am happy.

foreach($hashItem in $categryHash.GetEnumerator()){
    # Creates a directory with the Hash Key
    Foreach($pathToMonitor in $pathsFromConfig){
        $categoryFullPath = $pathToMonitor $hashItem.Name
        createDirectory($categoryFullPath)
        # Moves files into that directory 
        [String[]]$extentions = @()
        $extentions = $hashItem.Value -split ','
        foreach($string in $extentions)
        {
            Get-Item $pathToMonitor\* -Include $string | Move-Item -Destination $categoryFullPath
        }
    }
}
  • Related