I have the following code:
$items = Get-ChildItem -Path 'D:\Myoutput\'
$items | ForEach-Object
{
$lastWrite = ($_).LastWriteTime
$timespan = New-Timespan -days 3 -hours 0 -Minutes 0
if(((get-date) - $lastWrite) -gt $timespan) {
$name = $_.Name
$isDir = $_.PSIsContainer
if(!$isDir) {
$_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip"
if (**above_line** is success) {
echo "$name is zipped"
$_ | Remove-Item
}
}
}
}
Please help, how I can find out if '$_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive$name.zip"' is success or not.
Compress-Archive
will throw exceptions if something goes wrong, and it will delete partially created archives (source). So, you can do two things to make sure, it was successful:
Example:
$items = Get-ChildItem -Path 'D:\Myoutput\'
$items | ForEach-Object
{
$lastWrite = ($_).LastWriteTime
$timespan = New-Timespan -days 3 -hours 0 -Minutes 0
if(((get-date) - $lastWrite) -gt $timespan) {
$name = $_.Name
$isDir = $_.PSIsContainer
if(!$isDir) {
try {
$_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip"
if (Test-Path -Path "D:\Myoutput\Archive\$name.zip") {
Write-Host "$name is zipped"
$_ | Remove-Item
} else {
Write-Host "$name is NOT zipped" -ForegroundColor Red
}
} catch {
Write-Host "$name is NOT zipped" -ForegroundColor Red
}
}
}
}