Search code examples
powershellmove

Powershell Script to Move Files, but moves the Script itself - How to Fix?


I have the following script to break up a large number of files in a single directory into subfolders, split up to keep the subfolder size/file count manageable. It works, but has two minor issues I'd like to fix:

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100

$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++; 
[math]::Ceiling($n/9990)} | 
ForEach-Object {                               
    $dir = New-Item -Type Directory -Name $_.Name   # Create directory
    $_.Group | Move-Item -Destination $dir          # Move files there

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete             
$percent -verbose
$i++
    }

First, how do I prevent the script itself from moving to the first script-created subfolder?

Second, how do I prepend the name "Move Files" to the script-created folders? Right now they are just numbered sequentially.


Solution

  • Exclude the script itself by inspecting $MyInvocation like this:

    $n = 0; Get-ChildItem -File |Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property { ...
    

    When you call New-Item to create the directory, you can pre-pend whatever you want to the -Name argument:

    $dir = New-Item -Type Directory -Name "Move Files $($_.Name)"   # Create directory