I want to write a function that would move IIS logs to a remote server, then verify the move, log the errors if any, send email alerts, and zip the files if move is successful. I would then call the function using another script that would be populated with a CSV file with the servernames and IPs and all other necessary parameters. So, I broke down the function into multiple parts and wrote these functions and cmdlets so far:
1.
Function MoveFile
{
[CmdletBinding()]
param
(
[parameter(Mandatory=$True,
Helpmessage='which server would you like to target?')]
[Alias('host')]
[ValidateLength(3,30)]
[string[]]$Servername,
[string]$Sourcefile,
[string]$DestinationFile,
[string]$logname = 'C:\errors.txt'
)
begin {
write-verbose "Deleting Logname"
del $logname -ErrorAction SilentlyContinue
}
process {
Write-verbose "Copying IIS Logs"
foreach ($item in (Get-ChildItem $Servername\$sourcefile)) {
copy-Item $item.Fullname $DestinationFile -Force
}
}
}
function zip-files
{
param($Sourcedirectory, $zipFilename, $zipFilepath, $zipFile)
#Prepare zip file
if(-not (test-path($zipFile))) {
set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipFile).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}
foreach($file in $files) {
$zipPackage.CopyHere($file.FullName)
#using this method, sometimes files can be 'skipped'
#this 'while' loop checks each file is added before moving to the next
while($zipPackage.Items().Item($file.name) -eq $null){
Start-sleep -seconds 1
}
}
}