user 9191
user 9191

Reputation: 747

List all files that were moved in an email Body - Powershell

Trying to accomplish the following:

1)Move files from multiple sources into multiple destinations. Therefore i listed sources under a SOURCE column, and destinations under a DESTINATION column (WORKING)

2)Send an email with a list of files that were moved and the destination (Not working)

Param (
  [string]$SMTPServer = "XXX.XX.xXX",
  [string]$From = "[email protected]",
  [string]$To = "[email protected]",
  [string]$Subject = "New File"
)

Import-Csv -Path "C:\moveallfiles.csv" -ErrorAction Stop | foreach {
if (-not (Test-Path -Path $_.Destination))
{
    # Create directory if needed
    New-Item -ItemType directory -Path $_.Destination -WhatIf
}
# Copy file
 $MoveFileprocess = Move-Item -Path $_.Source -Destination $_.Destination -force -PassThru
}
 $SMTPMessage = @{
    To = $To
    From = $From
    Subject = "$Subject"
    Smtpserver = $SMTPServer
}
$SMTPBody = "`nThe following files have recently been added `n
          $MoveFileprocess   `n"
Send-MailMessage @SMTPMessage -Body $SMTPBody

Right now its listing all the files in one single line, hard to read I was wondering if theres a way to send the body email as

File 1 moved to Destination 1
File 2 moved to Destination 2

and so on...

Upvotes: 1

Views: 257

Answers (1)

Rich Moss
Rich Moss

Reputation: 2384

You were pretty close. Try this:

Param (
  [string]$SMTPServer = "XXX.XX.xXX",
  [string]$From = "[email protected]",
  [string]$To = "[email protected]",
  [string]$Subject = "New File"
)
$SMTPBody = "`nThe following files have recently been added `n"
Import-Csv -Path "C:\moveallfiles.csv" -ErrorAction Stop | foreach {
    if (-not (Test-Path -Path $_.Destination)){
        # Create directory if needed
        New-Item -ItemType directory -Path $_.Destination 
    }
    If((Get-Item $_.Source).LastWriteTime -gt (Get-Item $_.Destination).LastWriteTime){
        Move-Item -Path $_.Source -Destination $_.Destination -force
        $SMTPBody += "$($_.Source) moved to $($_.Destination)`n"
    }Else{
        Write-Warning "Skipped overwriting newer $($_.Destination)"
    }
}
$SMTPMessage = @{
    To = $To
    From = $From
    Subject = "$Subject"
    Smtpserver = $SMTPServer
}
Send-MailMessage @SMTPMessage -Body $SMTPBody

Note that Move-Item -PassThru returns the affected object, not a string. I took out the -WhatIf parameter for the New-Item command, indented the foreach{} loop and made indenting and brackets consistent.

Upvotes: 1

Related Questions