Powershell script check for files and log

Hi ,

i have working script..
i want to put additional checks in the script to check for files and proceed further.
it should check for files after it checks for source folder.
if all three files available then proceed further to run remaining lines of checking backupfolder.
if even one file is missing or all missing it should write log the missing files and exit

Files names to check-
cat.xml
rat.xml
bat.xml

$logdate=Get-Date -Format ddMMMyyyy_HHmmss
$Logfile = "E:\Logs\FileProcessing_$logdate.txt"

function LogWrite ([string]$logstring)
{  
   Add-content $Logfile -value $logstring
}

#Zip Files
$sourcefolder="E:\INT\PUT"
$backupFolder="E:\INT\Archive"

#check if source exists
if(!(Test-Path $sourcefolder)){
    $msj="The source folder ""$($sourcefolder)"" doesn't exists. Exiting..."
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
    LogWrite -ForegroundColor Red $msj
    exit -1
}

#check the target folder or create it
if(!(Test-Path $backupFolder)){
    $msj="The target folder ""$($backupFolder)"" was created"
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) EXECUTE:`t$msj"
    LogWrite -ForegroundColor Magenta $msj
    New-Item -ItemType Directory -Path $backupFolder | Out-Null
}
foreach($file in (Get-ChildItem -File $sourcefolder -Filter "*.xml" -Recurse)){
    $date = Get-date -Format "ddMMyyyy_HHmmss"
    $destinationFile = "$($FILE.Directory.FullName)\$($file.Name).zip"
    $MoveFile = "$backupFolder\$($file.BaseName)_$date.xml"
    try{
        $msj="Compressing File ""$($file.Name)"" into ""$destinationFile"" succeeded"
        Compress-Archive -Path $($file.FullName) -CompressionLevel Optimal -DestinationPath  $destinationFile -Force
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) COMPRESS:`t$msj"

        #successful compress
        $msj="Moving File ""$MoveFile"""
        Move-Item -Path $($file.FullName) -Destination $MoveFile -Force
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ARCHIVE:`t$msj"
    }  
    catch{
        $msj="There was an Error: $($_.exception.Message)"
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
        LogWrite -ForegroundColor Red $msj
        exit -1
    }
}
Skumar_CCSAAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MichelangeloConsultantCommented:
Basically this is it
if ((Test-Path $firstfile) -and (Test-Path $secondfile) -and (Test-Path $Thirdfile)) {
  Yourcodehere
} else { break }
0
Skumar_CCSAAuthor Commented:
I am getting error and given below complete script, error msg and log.

Actually I want to check if 3 files exists..
If exists it should write the filename with path in the log file.
if not exists then should write missing file in the log and exit.
can help pls..



#Requires -version 3.0
$WarningPreference="Continue"

#variables
$ScriptPath = $(Split-Path -Parent $MyInvocation.MyCommand.Definition)

#Log Timestamp
$date=Get-Date -Format ddMMMyyyyHHmmss
$logdate=Get-Date -Format ddMMMyyyy_HHmmss
$Logfile = "E:\INT\LOG\FileProcessing_$logdate.txt"

function LogWrite ([string]$logstring)
{  
   Add-content $Logfile -value $logstring
}
LogWrite ("$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) START:`t"+"File Processing of XML`n")

#Zip Files and move to backup folder
$sourcefolder="E:\INT\PUT"
$backupFolder="E:\INT\Archive"

#check if source folder exists
if(!(Test-Path $sourcefolder)){
    $msj="The source folder ""$($sourcefolder)"" doesn't exists. Exiting..."
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
    LogWrite -ForegroundColor Red $msj
    exit -1
}

#check if source file exists
if ((Test-Path $cat.xml) -and (Test-Path $rat.xml) -and (Test-Path $bat.xml)) {
    $msj="The source files ""$($sourcefolder)"" doesn't exists. Exiting..."
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
    LogWrite -ForegroundColor Red $msj
    exit -1
}

#check the target folder or create it
if(!(Test-Path $backupFolder)){
    $msj="The target folder ""$($backupFolder)"" was created"
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) EXECUTE:`t$msj"
    LogWrite -ForegroundColor Magenta $msj
    New-Item -ItemType Directory -Path $backupFolder | Out-Null
}

foreach($file in (Get-ChildItem -File $sourcefolder -Filter "*.xml" -Recurse)){
    $date = Get-date -Format "ddMMyyyy_HHmmss"
    $destinationFile = "$($FILE.Directory.FullName)\$($file.Name).zip"
    $MoveFile = "$backupFolder\$($file.BaseName)_$date.xml"
    try{
        $msj="Compressing File ""$($file.Name)"" into ""$destinationFile"" succeeded"
        Compress-Archive -Path $($file.FullName) -CompressionLevel Optimal -DestinationPath  $destinationFile -Force
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) COMPRESS:`t$msj"

        #successful compress
        $msj="Moving File ""$MoveFile"""
        Move-Item -Path $($file.FullName) -Destination $MoveFile -Force
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ARCHIVE:`t$msj"
    }  

    catch{
        $msj="There was an Error: $($_.exception.Message)"
        LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
        LogWrite -ForegroundColor Red $msj
        exit -1
    }
}

exit 0

**********************************************************************************

I get this error msg .

PS E:\INT> E:\INT\FileCheck_Revise.ps1
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At E:\INT\FileCheck_Revise.ps1:31 char:16
+ if ((Test-Path $cat.xml) -and (Test-Path $rat.xml) -and (Test-Path $b ...
+                ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
 PS E:\INT>

**********************************************************************************

Log file output

2018-09-18 17:09:46 START:      File Processing of XML
2018-09-18 17:09:49 COMPRESS:      Compressing File "bat.xml" into "E:\INT\PUT\bat.xml.zip" succeeded
2018-09-18 17:09:49 ARCHIVE:      Moving File "E:\INT\Archive\bat_18092018_170946.xml"
2018-09-18 17:09:49 COMPRESS:      Compressing File "cat.xml" into "E:\INT\PUT\cat.xml.zip" succeeded
2018-09-18 17:09:49 ARCHIVE:      Moving File "E:\INT\Archive\cat_18092018_170949.xml"
2018-09-18 17:09:49 COMPRESS:      Compressing File "rat.xml" into "E:\INT\PUT\rat.xml.zip" succeeded
2018-09-18 17:09:49 ARCHIVE:      Moving File "E:\INT\Archive\rat_18092018_170949.xml"
0
MichelangeloConsultantCommented:
I used variables, if you use filenames do not prepend the $
0
Michael B. SmithManaging ConsultantCommented:
This is probably more like what you want:
$files   = 'cat.xml', 'rat.xml', 'bat.xml'
$success = $true
foreach( $file in $files )
{
	$filename = Join-Path $sourcefolder $file
	if( Test-Path -LiteralPath $filename )
	{
		LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) FILECHECK:`tFile exists: $filename"
	}
	else
	{
		$msj = "The source file '$fileName' doesn't exist. Exiting..."
		LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
		LogWrite -ForegroundColor Red $msj
		$success = $false
	}
}
if( -not $success )
{
	exit -1
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Skumar_CCSAAuthor Commented:
Hi Michael ,
thanks for help..
it works.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.