Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates a ZIP file with a unique name and uploads to a given FTP site
function ZipAndUpload([string]$ftpUrl, [string]$ftpUsername, [string]$ftpPassword, [string]$inputPath, [string]$filterExpression) {
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($ftpUsername,$ftpPassword)
$inputPath = Resolve-Path $inputPath
$file = [System.Io.File]::GetAttributes($inputPath)
$uniqueFormatPart = Get-Date -format yyyyMMddHHmmssfff
$destinationPath = [System.IO.Path]::GetDirectoryName($inputPath) + "_" + $uniqueFormatPart
if($filterExpression -ne $null) {
$directoryExists = Test-Path $destinationPath
if(!$directoryExists){
mkdir $destinationPath
}
else{
remove-item $destinationPath -Force -Recurse
}
Get-ChildItem -Path $inputPath | Where-Object { $_.Name -match $filterExpression} | Copy-Item -Destination $destinationPath
$inputPath = $destinationPath
}
if ($file -eq [System.Io.FileAttributes]::Directory) {
$destinationPath = $destinationPath + ".zip"
$destinationFileName = [System.IO.Path]::GetFileName($destinationPath)
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | out-null
[System.IO.Compression.ZipFile]::CreateFromDirectory($inputPath, $destinationPath)
write-host "sucessfully created zip file $destinationFileName" -foreground "green"
}
else {
$destinationPath = $inputPath
}
$destinationFileName = [System.IO.Path]::GetFileName($destinationPath)
write-host $destinationPath
$uriPath = "$ftpUrl/$destinationFileName"
write-host "uploading file to $uriPath ..."
$uri = New-Object System.Uri($uriPath)
$webclient.UploadFile($uri,$destinationPath)
write-host "successfully uploaded file" -foreground "green"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.