Powershell Script: Move files from one location to another, based on file size and not in use.

Time to read: 4 mins

As an engineer for a local radio station, we legally have to record all audio. I have one server that records the audio and another that stores the recordings. So I created a Powershell script that moves the files over.

This script also ignores files that are currently in use (i.e. still recording) and files that are less than 60mb (i.e. not a full-hour recording).

Hope you find this useful.

# Define source and destination directories
$sourceDirectory = "C:\OriginalPath"
$destinationDirectory = "C:\NewPath"

# Ensure the destination directory exists
if (-not (Test-Path $destinationDirectory)) {
    New-Item -Path $destinationDirectory -ItemType Directory
}

# Move all files from source to destination that are not in use and greater than 60MB
Get-ChildItem -Path $sourceDirectory -File | ForEach-Object {
    $canMove = $true
    $fileSizeLimit = 60MB

    # Check if file is in use
    try {
        [IO.File]::Open($_.FullName, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None).Close()
    } catch {
        $canMove = $false
    }

    # Check if file size is greater than 60MB
    if ($_.Length -lt $fileSizeLimit) {
        $canMove = $false
    }

    if ($canMove) {
        Move-Item -Path $_.FullName -Destination $destinationDirectory
    }
}

Write-Output "Files moved successfully!"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.