0

I have powershell script that works, but I'd like to see if there is a better way to accomplish this task.

Right now I am using several different if statements followed by script blocks containing one cmdlet each. Is there a way to put these cmdlets all within the curly braces?

I've tried piping but the cmdlets don't need input from the prior cmdlet.

$Filepath1 = 'h:\test_network\book1.csv'
$Filepath2 = 'c:\test_local\book2.csv'

$hashes = 
foreach ($Filepath in $Filepath1,$Filepath2)
{
 $MD5 = [Security.Cryptography.HashAlgorithm]::Create( "MD5" )
 $stream = ([IO.StreamReader]"$Filepath").BaseStream
 -join ($MD5.ComputeHash($stream) | 
 ForEach { "{0:x2}" -f $_ })
 $stream.Close()
 }

if ($hashes[0] -eq $hashes[1])
        {write-host 'Files Match' -foregroundcolor green}

if  ($hashes[0] -eq $hashes[1])
        {copy-item $filepath2 c:\test_archive\}

if ($hashes[0] -eq $hashes[1])
        {remove-item $filepath2}

if  ($hashes[0] -ne $hashes[1])
        {write-host 'Files do not match' -foregroundcolor red}  

if  ($hashes[0] -ne $hashes[1])
        {remove-item $filepath2}

1 Answers1

0

A simple if statement should work in PowerShell:

if ($hashes[0] -eq $hashes[1])
{
    write-host 'Files Match' -foregroundcolor green
    copy-item $filepath2 c:\test_archive\
    remove-item $filepath2
}
else
{
    write-host 'Files do not match' -foregroundcolor red
    remove-item $filepath2
}
dustinmoris
  • 3,195
  • 3
  • 25
  • 33