Extension problems

$files = get-childitem 'C:\_KLARA\*'
Foreach ($filename in $files){
$extn = [IO.Path]::GetExtension($filename)
if ($extn -eq ".epub",".pdf",".txt",".mobi"){      
$filename = $filename.name.replace('.',' ').trim()
$NewFileName = $filename + $extn
}
}
Move-Item -Destination 'E:\M01_Backup\Books\$NewFileName' -force

A.Canticle.for.Leibowitz.epub
A Coyote’s in the House.pdf
CopyData.txt
Getting Started.with.OpenOffice - Rob.mobi

What’s your question?

What is wrong. I don’t know how to code properly

So I recommend to do a big step back and start with learning the very basics of PowerShell first. This will save you from a lot of wasted time and frustration. Until that you could start with explaining what your issue is.

This is my way trying to learn. Learn by misstakes

If you want to get help you will have to elaborate a little more detailed though.

Please keep in mind: people coming here to help other do this in their spare time. So please don’t be a jerk wasting their time and energy. At least do your homework first.

Thanks in advance.

If I have done my homework I have no need to ask for PowerShell Help

Me helping others I see as a gift not a burden

Hi, try this:

$files = Get-ChildItem 'C:\_KLARA\*.*'

    Foreach ($filename in $files){

    $extn = [IO.Path]::GetExtension($filename)

        if ($extn -eq ".epub",".pdf",".txt",".mobi"){ 
             
        $filename = $filename.name.replace('.',' ').trim()

        $NewFileName = $filename + $extn

        }

        Move-Item -Path $filename.FullName -Destination "E:\M01_Backup\Books\$NewFileName" -force

    }

Hi, sorry but I can’t get it to work.

file extension if test
================

  • to use a single if construct where the code components is the same process will require the test to use or with each of the criteria which can be achieved using different methods
  1. manually test each criteria within the if construct using -or
    you will need to modify the criteria inside the if test for any changes
    code readability can be an issue

replace :

($extn -eq ".epub",".pdf",".txt",".mobi")

with :

(($extn -eq "epub") -or ($extn -eq "pdf") -or ($extn -eq "txt") -or ($extn -eq "mobi"))
  1. manually create a regex -match construct as the if test
    you will need to modify the criteria inside the if test for any changes
    testing values with regex uses | as the or

replace :

($extn -eq ".epub",".pdf",".txt",".mobi")

with :

($extn -match "epub|pdf|txt|mobi")
  1. use a dynamically created regex -match from array object
    use an array to contain extensions which are concatenated to create the test
    add or remove elements within the array for any changes
    testing values with regex uses | as the or

add at start of script :

$extn_list = [string[]]@("epub","pdf","txt","mobi")

replace :

($extn -eq ".epub",".pdf",".txt",".mobi")

with :

($extn -match ($extn_list -join "|"})
  • functionality with the code
    ‘{0}’ -f (…) : formats the first item with the results that follow
    '($extn_list -join ‘|’) : concatenates the array elements with | as a separator

  • test code and output demonstrating this method

code

$tHost =
@'
==================================
Output - Test Results
==================================

Match Test Created
----- ---- -------
{0}Match : {1}

Match Results
----- -------
{2}
==================================
'@

$tItem =
@'
{0}Test : {1}{0} - Result : {2}
'@

$oNewLine = '{0}' -f ([system.environment]::NewLine)
$oTab = '{0}' -f $([system.char]9)
$rItems = $null

$tExtn = [string[]]@('file','txt','log','pdf')
$lExtn = [string[]]@('epub','pdf','txt','mobi')

$tExtn | 
    ForEach ({
        $isMatch = '{0}' -f ($($_ -match ('{0}' -f ($lExtn -join '|'))) -as [system.string])
        
        If ([system.string]::IsNullOrEmpty($rItems))
        {
            $rItems = '{0}' -f ($tItem -f $oTab,$_,$isMatch)
        }
        Else
        {
            $rItems = '{0}{1}{2}' -f $rItems,$oNewLine,($tItem -f $oTab,$_,$isMatch)
        }})

$oHost = '{0}' -f ($tHost -f $oTab,('{0}' -f ($lExtn -join '|')),$rItems)
Write-Host -Object $oHost

output

==================================
Output - Test Results
==================================

Match Test Created
----- ---- -------
	Match : epub|pdf|txt|mobi

Match Results
----- -------
	Test : file	 - Result : False
	Test : txt	 - Result : True
	Test : log	 - Result : False
	Test : pdf	 - Result : True
==================================

changing the file name
===================

  • I am unsure what you are trying to achieve with the new file name but the . needs to be escaped for it to be replaced.
  • this can be achieved with a single line using the same functionality in the previous information to format an item

replace :

$filename = $filename.name.replace('.',' ').trim()
$NewFileName = $filename + $extn

with :

$NewfileName = '{0}.{1}' -f ($fileName.Name -replace  '\..*?$'),$extn

code to achieve moving eBooks
==========================

  • the following code will achieve identifying files with the extension used for eBooks in a folder and move it to a different folder.
# Make Changes as Required
$FileSoure = '{0}' -f 'C:\_KLARA\*.*'
$FileDestination = '{0}' -f 'E:\M01_Backup\Books'

$ListBooksExtn = [string[]]@('epub','pdf','txt','mobi')


# Process Files Testing the Meet Extension before Moving
$ListFiles = Get-ChildItem -Path $FileSource

ForEach ($ItemFile in $ListFiles)
{
    If ($ItemFile.Name -contains ('{0}' -f ($ListBooksExtn -join '|')))
    {
        $SplatMoveItem = [ordered]@{
            Path         =  '{0}' -f $ItemFile.FullName
            Destination  =  '{0}\{1}' -f $FileDestination,$ItemFile.Name
            Force        =  $true
        }

        Move-Item @SplatMoveItem
    }
}
1 Like

convert the code presented to pseudo code and i believe the question is requesting help to identify eBooks currently saved in one location and relocate the eBooks to another folder

yes the code provided is not gong to achieve the outcomes but it has demonstrated what the requirements are

we were all new to coding, coding processes, syntax and applying all those skills with PowerShell

Whoa this will take some time to melt! Thank’s

Is the end result like this?

$FileSource = '{0}' -f 'C:\_KLARA\*.*'

$FileDestination = '{0}' -f 'E:\M01_Backup\Books'

$ListBooksExtn = [string[]]@('epub','pdf','txt','mobi')

$ListFiles = Get-ChildItem -Path $FileSource

    ForEach ($ItemFile in $ListFiles){
        If ($ItemFile.Name -contains ('{0}' -f ($ListBooksExtn -join '|')))
		{
            $SplatMoveItem = [ordered]@{
                Path         =  '{0}' -f $ItemFile.FullName
                Destination  =  '{0}\{1}' -f $FileDestination,$ItemFile.Name
                Force        =  $true
            }
    
            Move-Item @SplatMoveItem
        }
    }

This line I can’t put in place!

($extn -match ($extn_list -join "|"})

Thanks for putting my code on the right track!!

Hi ingewell

powershell also provides a default parameter to test before you commit

this can be achieved by the following modifications

line in code to change

Move-Item @SplatMoveItem

additional parameter

Move-Item @SplatMoveItem -WhatIf

this will simulate the process listing what will occur - if the results provide your needs then remove the additional parameter and execute

hi ingewell

no the difference is the script no longer references the .ext of the files but the complete filename and checks if it contains one of the extensions specified

yes - i posted this with my initial response as i understood what you really were trying to achieve with the script you posted and requested assistance