Skip to content

Instantly share code, notes, and snippets.

@jeroensmink98
Last active August 8, 2023 08:21
Show Gist options
  • Save jeroensmink98/79a8d370488aafda4619efa2b25994dd to your computer and use it in GitHub Desktop.
Save jeroensmink98/79a8d370488aafda4619efa2b25994dd to your computer and use it in GitHub Desktop.
Clean remote environments using WinSCP
# Define input parameters for the script
# .\cleanup.ps1 -exclusionList "SOME_FILE_NOT_TO_REMOVE/FOLDER/FILE.js", "/www/app/Folder2/File9.txt" -rootFolder "/www" -username "FTP_USERNAME" -password "FTP_PASSWORD"
param (
[string[]]$exclusionList, # List of files or directories to exclude
[string]$rootFolder, # Starting folder from where files will be enumerated
[string]$ftpServer = "ftp.by-tres.nl", # FTP server address (default is set)
[Parameter(Mandatory=$true)] # Make the username parameter mandatory
[string]$username, # FTP server username
[Parameter(Mandatory=$true)] # Make the password parameter mandatory
[string]$password # FTP server password
)
# Load WinSCP .NET assembly which provides capabilities to connect to FTP and perform file operations
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
# Displaying the specified root folder and exclusion list
Write-Host "Root folder: $rootFolder"
Write-Host "Exclusion list: $exclusionList"
# Setup session options for FTP connection
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Ftp
HostName = $ftpServer
UserName = $username
Password = $password
}
# Create a new FTP session
$session = New-Object WinSCP.Session
try {
# Establish an FTP connection using the session options
$session.Open($sessionOptions)
# Check if connection is successful
if ($session.Opened) {
Write-Host "Connected successfully."
} else {
Write-Host "Connection failed."
}
# Get a list of all files and directories under the specified root folder
$remoteFiles = $session.EnumerateRemoteFiles($rootFolder, "*", [WinSCP.EnumerationOptions]::AllDirectories)
# First Pass: Go through all files and remove those not in the exclusion list
foreach ($fileInfo in $remoteFiles) {
if (-not $fileInfo.IsDirectory) { # If it's a file
$shouldExclude = $false
# Check if the file matches any item in the exclusion list
foreach ($excludeItem in $exclusionList) {
if ($fileInfo.FullName -eq $excludeItem) {
# Direct match with exclusion item
$shouldExclude = $true
break
} elseif ($fileInfo.FullName.StartsWith($excludeItem)) {
# The file is inside an excluded directory
$shouldExclude = $true
break
}
}
# If the file is not to be excluded, attempt to remove it
if (-not $shouldExclude) {
try {
$session.RemoveFiles($fileInfo.FullName).Check()
Write-Host "Removed: $($fileInfo.FullName)"
} catch {
Write-Warning "Failed to remove $($fileInfo.FullName) because $($_.Exception.Message)"
}
} else {
Write-Host "Skipped (due to exclusion): $($fileInfo.FullName)"
}
}
}
# Second Pass: Remove empty directories
# Start from the innermost directories by reversing the order
foreach ($fileInfo in $remoteFiles | Where-Object { $_.IsDirectory } | Sort-Object FullName -Descending) {
try {
# Only remove a directory if it's empty
$session.RemoveFiles($fileInfo.FullName).Check()
Write-Host "Removed empty directory: $($fileInfo.FullName)"
} catch {
Write-Host "Skipped directory (might not be empty or excluded): $($fileInfo.FullName)"
}
}
} finally {
# Dispose of the FTP session to free up resources
$session.Dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment