I got a little powershell problem troubling me for quite a while now.
Im trying to get information from a RSS site. I download the XML and go through it. I just want certain stuff from it. That for I use .document.getElementByID().outerText
The problem is that somehow it pulls the first information correctly but after that everything fails he just picks random text or just keeps the one text from the beginning without refreshing the variable. Also Powershell ISE says "You cannot call a method on a null-valued expression." randomly.
Here is my code:
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 19.07.17
LAST CHANGE:
#>
$debug = 1 #DEBUG
$receiver="A#MailAdress.com"
$sender="A#MailAdress.com"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8
$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0
Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = #()
if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
while($count -ne $lines.Lines)
{
if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
{
$entrys >> $tag[$nmbr]
if ($debug -eq 1)
{
Write-Output "$tag[$nmbr]"
Write-Output "$entrys"
Write-Output "$count"
}
}
$count++
$nmbr++ #jumps into the next line
}
}
$ie = New-Object -ComObject "InternetExplorer.Application"
Foreach($msg in $feed.Item)
{
$link = ($msg.link)
$subject = ($msg.title)
$ie.navigate("$link")
#$return = Invoke-WebRequest -Uri $link -OutFile "C:\RSS\Zoll\link.html"
$return = $ie.document
$innertext = $return.documentElement.document.getElementById("main").outerText
$body = $innertext#.Replace('Ä', 'Ä')
<#
$body = $innertext.Replace('ä', 'ä')
$body = $innertext.Replace('Ö', 'Ö')
$body = $innertext.Replace('ö', 'ö')
$body = $innertext.Replace('Ü', 'Ü')
$body = $innertext.Replace('ü', 'ü')
$body = $innertext.Replace('ß', 'ß')
#>
if ($debug -eq 1)
{
Write-Output "Subject $subject"
Write-Output "Tag $tag"
Write-Output "Link $link"
Write-Output $body
#exit
}
if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
{
if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
{
if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
{
if($debug -eq 1)
{
Write-Output "$tag"
Write-Output "Send. Tag = $tag"
}
Write-Output "Send."
}
}
}
else
{
Write-Host "Empty."
}
}
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie
Added a wait if busy loop to make sure IE loads the full html document. Thats the solution of the problem ! :)
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 20.07.17
LAST CHANGE: ADDED WAIT IF BUSY !
#>
$debug = 0 #DEBUG
$receiver="A#MailAdress.de"
$sender="A#MailAdress.de"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8
$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0
Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = #()
if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
while($count -ne $lines.Lines)
{
if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
{
$entrys >> $tag[$nmbr]
if ($debug -eq 1)
{
Write-Output "$tag[$nmbr]"
Write-Output "$entrys"
Write-Output "$count"
}
}
$count++
$nmbr++ #jumps into the next line
}
}
$ie = New-Object -ComObject InternetExplorer.Application #creates new ComObject IE
Foreach($msg in $feed.Item)
{
$link = ($msg.link)
$subject = ($msg.title)
if ($debug -eq 1)
{
$ie.visible = $true
}
$ie.navigate("$link") #navigate with Internetexplorer to the website
while ($ie.busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting the website from IE.navigate is still .busy wait 200 milliseconds
$return = $ie.document
$innertext = $return.documentelement.document.IHTMLDocument3_getElementById("main").outerText #gets the outer text from the div with the element ID "main"
while ($innertext.busy -and $innertext.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting Text is .busy wait 200 milliseconds
$body = $innertext
if ($debug -eq 1)
{
Write-Output "Subject $subject"
Write-Output "Tag $tag"
Write-Output "Link $link"
Write-Output "INNERTEXT $innertext"
Write-Output "BODY $body"
#exit
}
if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
{
if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
{
if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
{
Write-Output "Send."
}
}
}
else
{
Write-Host "Empty."
}
}
$ie.Quit() #----|
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie) # ---> Quits the Internet Explorer Session otherwise there are to many IE.exe open and no more ID's left
Remove-Variable ie
Related
I'm using FileSystemWatcher to monitor a folder where documents are scanned to. When a new file is detected, it will send an email to notify someone. It's working as is, but sometimes (not every file) it will trigger 2 or 3 times on a new file and send the email 2-3 times for the same file. I'm guessing it has to do with the way the file is created by the scanner or something like that.
I'm trying to figure out a way to protect against this happening, to ensure it only sends one email per file. Any suggestions would be greatly appreciated.
$PathToMonitor = "\\path\to\folder"
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToMonitor
$FileSystemWatcher.Filter = "*.*"
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.EnableRaisingEvents = $true
$Action = {
if ($EventArgs.Name -notlike "*.pdf" -and $EventArgs.Name -notlike "*.tif") {
return
}
$details = $event.SourceEventArgs
$Name = $details.Name
$Timestamp = $event.TimeGenerated
$text = "{0} was submitted on {1}." -f $Name, $Timestamp
$FromAddress = "Email1 <email1#email.com>"
$ToAddress = "Email2 <Email2#email.com>"
$Subject = "New File"
$SMTPserver = "123.4.5.678"
Send-MailMessage -From $FromAddress -To $ToAddress -Subject $Subject -Body $text -SmtpServer $SMTPserver
}
$handlers = . {
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateConsumer
}
try {
do {
Wait-Event -Timeout 5
} while ($true)
}
finally {
Unregister-Event -SourceIdentifier FSCreateConsumer
$handlers | Remove-Job
$FileSystemWatcher.EnableRaisingEvents = $false
$FileSystemWatcher.Dispose()
}
This may be because you listen too many notifications. The default is LastWrite, FileName, and DirectoryName
FileName is sufficient for your need and may prevent your issue.
$FileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::FileName
As a remark, I don't know why you use Wait-Event -Timeout 5. Script is working fine without the try{} block.
EDIT: Add a ConcurrentDictionary to avoid duplicate events
Try this sample code. I've included only the beginning part of your script. End is untouched.
$PathToMonitor = "\\path\to\folder"
$KeepFiles = 5 #minutes
$MonitoredFiles = New-Object -TypeName 'System.Collections.Concurrent.ConcurrentDictionary[[System.String],[System.DateTime]]'
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToMonitor
$FileSystemWatcher.Filter = "*.*"
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::FileName
$FileSystemWatcher.EnableRaisingEvents = $true
$Action = {
if ($EventArgs.Name -notlike "*.pdf" -and $EventArgs.Name -notlike "*.tif") {
return
}
#Cleaning events -gt 5mn
$Now = [System.DateTime]::Now
$OriginEventDate = [System.DateTime]::MinValue
foreach($MonitoredFile in [System.Linq.Enumerable]::ToList(($MonitoredFiles.Keys))) {
if ($MonitoredFiles.TryGetValue($MonitoredFile, [ref]$OriginEventDate)) {
if ($OriginEventDate.AddMinutes($KeepFiles) -gt $Now) {
try {
[void]$MonitoredFiles.Remove($MonitoredFile)
}
catch {}
}
}
}
$ProcessEvent = $false
# any same file creation event within 5mn are discarded
$OriginEventDate = [System.DateTime]::MinValue
if ($MonitoredFiles.TryGetValue($event.SourceEventArgs.Name, [ref]$OriginEventDate)) {
if ($OriginEventDate -ne [System.DateTime]::MinValue -and $OriginEventDate.AddMinutes($KeepFiles) -le $Now) {
return
}
else {
$ProcessEvent = $true
}
}
else {
#not successful means a concurrent event was successful, so discard this one.
if ($MonitoredFiles.TryAdd($event.SourceEventArgs.Name, $event.SourceEventArgs.TimeGenerated)) {
$ProcessEvent = $true
}
else {
return
}
}
if ($ProcessEvent) {
$details = $event.SourceEventArgs
$Name = $details.Name
$Timestamp = $event.TimeGenerated
$text = "{0} was submitted on {1}." -f $Name, $Timestamp
$FromAddress = "Email1 <email1#email.com>"
$ToAddress = "Email2 <Email2#email.com>"
$Subject = "New File"
$SMTPserver = "123.4.5.678"
Send-MailMessage -From $FromAddress -To $ToAddress -Subject $Subject -Body $text -SmtpServer $SMTPserver
}
}
I had to adjust these two things to make it work:
if ($MonitoredFiles.TryAdd($Event.SourceEventArgs.Name, $Event.TimeGenerated))
if ($OriginEventDate -ne [System.DateTime]::MinValue -and $OriginEventDate.AddMinutes($KeepFiles) -ge $Now)
Symantec recently changed their download page which moved to broadcom. Since then Invoke-WebRequest cannot grab the http url for the v5i64.exe file.
However the http url can be found when using Developer Tools in the browser looking at the Elements level, inside the body section of the page.
Does anyone have an idea on how this daily-changed url can be extracted with PowerShell?
$webreq = Invoke-WebRequest "https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep"
$webreq.Links | Select href
Use IE via ComObject
$ie = new-object -ComObject "InternetExplorer.Application"
$ie.visible=$True
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$IE.navigate2("https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep")
while ($IE.busy) {
start-sleep -milliseconds 1000 #wait 1 second interval to load page
}
Then find elementy by $ie.Document.IHTMLDocument3_getElementsByTagName("element name")
The following PowerShell script will prompt you to download the links containing the text v5i64.exe and HTTPS. This works on PowerShell 5.1 for Windows. It does not work for PowerShell 6 or 7 (PowerShell Core).
Tested on Windows 10.0.18363.657, Internet Explorer 11.657.18362, PowerShell 5.1.18362.628
$url = "https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep"
$outfile = "./v5i64.exe"
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.visible=$True
while($ie.Busy) {
Start-Sleep -Milliseconds 100
}
$ie.navigate2($url)
while($ie.ReadyState -ne 4 -or $ie.Busy) {
Start-Sleep -milliseconds 500
}
$ie.Document.getElementsByTagName("a") | % {
if ($_.ie8_href -like "*v5i64.exe") {
if ($_.ie8_href -like "https://*") {
$len = (Invoke-WebRequest $_.ie8_href -Method Head).Headers.'Content-Length'
Write-Host "File:" $_.ie8_href
Write-Host "Size:" $len
$confirm = Read-Host "Download file? [y/n]"
if ($confirm -eq "y") {
Write-Host "Downloading" $_.ie8_href
Invoke-WebRequest -Uri $_.ie8_href -OutFile $outfile
}
}
}
}
$ie.Stop()
$ie.Quit()
thanks for the proposed solutions. However here is my final code I am using:
$SEP_last_link = ("http://definitions.symantec.com/defs/"+($SEP_last | Select-String release -NotMatch | select -Last 1))
$Symantec_folder = "C:\Download for DVD\Symantec"
$Symantec_filepath = "$Symantec_folder\$SEP_last"
if (!(Test-Path "$Symantec_filepath" -PathType Leaf)) {
Write-Host "`rStart to download Symantec $SEP_last file: $(Get-Date)`r"
$start_time = (Get-Date)
$webclient = New-Object System.Net.WebClient
$WebClient.DownloadFile($SEP_last_link, $Symantec_filepath)
Write-Host "`r$SEP_last file has been downloaded successfully`r" -ForegroundColor Green
$end_time = $(get-date) - $start_time
$total_time = "{0:HH:mm:ss}" -f ([datetime]$end_time.Ticks)
Write-Host "`rTime to download Symantec $SEP_last file: $total_time`r"
} else {
Write-Host "`rSymantec $SEP_last file already exists!`r" -ForegroundColor Yellow
}
Get-ChildItem -Path "$Symantec_Folder\*-v5i64.exe" -Exclude "$SEP_last" -Verbose –Force | Remove-Item
The purpose of the scripts is to catch wrong logins to Elasticsearch, and gave the opportunity to retry entering a password. The idea was to count loop iteration by adding i++ after $result = Invoke-RestMethod $uri -Credential $credential step, but it turned out that -ErrorAction SilentlyContinue process is ignored in case it's located in try{} section, so i moved loop counts into finally {$i++} section, but the cons is that the last Attempt 5 does not pass the condition while ($i -lt 6) cuz it is 5+1 in finally {$i++} section.
$elasticsearch_pass = Read-Host "Enter ELASTICSEARCH password"
$uri = "https://${elasticsearch_ip}:9200"
$user = "static_user"
$i = 1
while ($i -lt 6) {
try {
Write-Host -ForegroundColor Cyan `n ("Trying to connect to elasticsearch. Attempt $i")
$secpasswd = ConvertTo-SecureString $elasticsearch_pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $uri -Credential $credential
if ($result.tagline -eq 'You Know, for Search') {
Write-Host -ForegroundColor Green `n ("Connection to elasticsearch {0} established..." -f $elasticsearch_ip)
break
}
}
catch {
Write-Host -ForegroundColor Red $_
if ("$_" -eq "Unauthorized") {
$elasticsearch_pass = Read-Host `n "Wrong elasticsearch password! Pls enter correct one"
}
}
finally {$i++}
}
What is the best approach to set a static loop iteration count and execute the last Attempt?
Why use While, if an interation var is needed the usual solution is a traditional for:
$uri = "https://${elasticsearch_ip}:9200"
$user = "static_user"
$i = 1
$maxTry = 5
For( $i = 1; $i -le $maxTry; ++$i )
{
try {
Write-Host -ForegroundColor Cyan `n ("Trying to connect to elasticsearch. Attempt $i of $maxtry ")
$secpasswd = ConvertTo-SecureString $elasticsearch_pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $uri -Credential $credential
if ($result.tagline -eq 'You Know, for Search') {
Write-Host -ForegroundColor Green `n ("Connection to elasticsearch {0} established..." -f $elasticsearch_ip)
break
}
}
Catch {
Write-Host -ForegroundColor Red $_.Exception.Message
if ($_.Exception.Message -match "Unauthorized") {
}
}
}
In either case I don't think you need to do the ++$i in the finally block, you could just do in the catch and continue. However the for loop allows you to do it at the right point in each iteration without the confusion.
Also added $maxTry gives a slightly better echo...
Since this is interactive I changed some of the catch block to echo a little more cleanly.
Also moved the Read-Host into the loop. and changed the language a little. though there are a couple of ways to do that...
Here is my Powershell code that when i execute it, it will continually loop while waking up my internal sites
$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
foreach($site in Get-Content $urlFile){
function WakeUp([string] $url)
{
Write-Host "Waking up $url ..." -NoNewLine
$client = new-object system.net.WebClient
$client.UseDefaultCredentials = $true
$null = $client.OpenRead($url)
$client.Dispose()
Write-Host " Ok"
}
#(
Get-Content $urlFile
) | % { WakeUp $_ }
}
Well, your script can generally be improved, however I think the error is that you already iterate over Get-Content $urlFile within your foreach condition and also in the loop. Try this:
# define the wake up function once
function WakeUp
{
Param
(
[string] $url
)
Write-Host "Waking up $url ..." -NoNewLine
$client = new-object system.net.WebClient
$client.UseDefaultCredentials = $true
$null = $client.OpenRead($url)
$client.Dispose()
Write-Host " Ok"
}
$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
$sites = Get-Content $urlFile
foreach($site in $sites)
{
# call wake up for each site
WakeUp $site
}
ORIGINAL POST:
Goal: an email is sent to a service account every day from a source.
Take the csv file it gives me and put it in a folder for the DBA guy.
Without further adieu, here is my current script:
#define variables
$datestamp = (get-date).AddDays(-1).ToString("MMddyyyy")
$datestamp = $datestamp.ToString()
$path = "C:\MyPath"
$dest = "C:\MyPath\Archive"
$file = "MyFile.csv"
#create outlook session
$objOutlook = New-Object -Com Outlook.Application
$inbox = $objOutlook.Session.GetDefaultFolder(6)
$inbox.Items.Restrict("[UnRead] = True" -and "[SenderEmailAddress] = 'SomePlace#SomeDomain.net'") | select -Expand Attachments | %
{
for ($i = $_.Count; $i; $i--)
{
$_.Item($i).SaveAsFile("C:\MyPath\$($_.Item($i).FileName)")
$_.Parent.Unread = $false
}
}
if (Test-Path "C:\MyPath\*.csv")
{
if(((Get-ChildItem C:\MyPath | Measure-Object ).Count) -gt '1' )
{
Send-MailMessage –SmtpServer "server.domain.com" –From "PoorITGuy#domain.com" -To "PoorITGuy#domain.com" -Subject " FAIL" -Body "FAILED. Too many valid items from mailbox.
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "Too many items to get."
}
else
{
Get-ChildItem $path\*.csv | foreach {Copy-Item $_ "C:\MyPath\$"}
Copy-Item C:\MyPath\*.csv "$path\$file"
Copy-Item C:\MyPath\*.csv "$dest\${datestamp}_$file"
if(Test-Path "$dest\$file")
{
Send-MailMessage –SmtpServer "server.domain.com" –From "PoorITGuy#domain.com" -To "PoorITGuy#domain.com" -Subject "some message”
#cleanup - remove all files from base directory, clean mailbox, close out com object.
Remove-Item "$path\*.csv"
$inbox.Items | select | %
{
for ($i = $_.Count; $i; $i--)
{
$_.Item($i).Delete
}
}
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
}
else
{
Send-MailMessage –SmtpServer "server.domain.com" –From "PoorITGuy#domain.com" -To "PoorITGuy#domain.com" -Subject " failure" -Body "File manipulation failure."
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "File manipulation failure."
}
}
}
else
{
Send-MailMessage –SmtpServer "server.domain.com" –From "PoorITGuy#domain.com" -To PoorITGuy#domain.com -Subject "FAIL" -Body "No item mailbox."
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "No item to get in inbox."
}
What doesn't work:
$inbox.Items.Restrict("[UnRead] = True" -and "[SenderEmailAddress] = 'SomePlace#SomeDomain.net'") | select -Expand Attachments | %
It seems that you cannot restrict the comObject Outlook.Application with more than one filter.
I've done a ton of searching on this and cannot find an answer on how to best perform this task in lieu of this. But I want my script to be spam-proof, so it needs to know that it is sent from the expected sender AND it needs to be unread only (see error catching right below)
In addition, I'm not certain if this would work:
$inbox.Items | select | %
{
for ($i = $_.Count; $i; $i--)
{
$_.Item($i).Delete
}
}
Also would like input on the script itself. Any input to make it more efficient would be appreciated.
The correct code (lots of syntax errors on the above prevented it from doing what I wanted to)
#define variables
$datestamp = (get-date).AddDays(-1).ToString("MMddyyyy")
$datestamp = $datestamp.ToString()
$path = "C:\MyPath"
$dest = "C:\MyPath\Archive"
$importpath = "C:\MyPath\Import"
$file = "MyFile.csv"
$folderExclude = "C:\MyPath\Archive"
#create outlook session
$objOutlook = New-Object -Com Outlook.Application
$inbox = $objOutlook.Session.GetDefaultFolder(6)
$inbox.Items.Restrict("[Unread] = True AND [SenderEmailAddress] = 'SomePlace#SomeDomain.net'") | select -Expand Attachments | % {
for ($i = $_.Count; $i; $i--) {
$_.Item($i).SaveAsFile("\\server\MyPath\$($_.Item($i).FileName)")
$_.Parent.Unread = $false
}
}
if (Test-Path "C:\MyPath\*.csv") {
if(((Get-ChildItem C:\MyPath -Include "*.csv" | Measure-Object ).Count) -gt '1' ) {
Send-MailMessage -SmtpServer smtpserver.mydomain.com -From Powershell#mydomain.com -To someguy#mydomain.com -Subject "FAIL" -Body "FAILED. Too many items from PSAutomationSrv mailbox."
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "Too many items to get."
}
else {
Copy-Item C:\MyPath\*.csv "$importpath\$file"
Copy-Item C:\MyPath\*.csv "$dest\${datestamp}_$file"
if(Test-Path "$dest\${datestamp}_$file") {
Send-MailMessage -SmtpServer smtpserver.mydomain.com -From Powershell#mydomain.com -To someguy#mydomain.com -Subject " successful" -Body "Date is: ${datestamp} File name is: ${dest}\${file}"
#cleanup - remove all files from base directory, clean mailbox, close out com object.
Remove-Item $path\*.csv
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
}
else {
Send-MailMessage -SmtpServer smtpserver.mydomain.com -From Powershell#mydomain.com -To someguy#mydomain.com -Subject " import - failure" -Body "File manipulation failure."
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "File manipulation failure."
}
}
}
else {
Send-MailMessage -To -SmtpServer smtpserver.mydomain.com -From Powershell#mydomain.com -To someguy#mydomain.com -Subject "FAIL" -Body "FAILED. No item in mailbox."
$objOutlook.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objOutlook)
throw "No item to get in inbox."
}
Notes - I had some code in excess.
Get-ChildItem $path\*.csv | foreach {Copy-Item $_ "C:\MyPath\$"}
is incorrect syntax, and unnecessary since the script already knows it is just manipulating one file anyway.
For deleting the inbox I would need to use Export-Mailbox it seems, which I do not want to do; as the service account performing this function is NOT an exchange admin nor do I want it to be. I'm just going to manually delete the inbox periodically or have the exchange guy do it on his end.