want the max and used from string - powershell

#http://stackoverflow.com/a/24036900/175063
$user = "uuuu"
$pwd = "pppp"
$source = "http://1.1.1.1/manager/jmxproxy?get=java.lang:type=Memory&att=HeapMemoryUsage"
$destination = "D:\Work\ps\test.xml"
$wc = new-object System.Net.WebClient
$p = New-Object System.Net.WebProxy 'http://proxy:8080'
$p.UseDefaultCredentials = $true
$wc.proxy = $p
$credCache = New-Object System.Net.CredentialCache
$creds = New-Object System.Net.NetworkCredential($user, $pwd)
$credCache.Add($source, "Basic", $creds)
$wc.Credentials = $credCache
$wc.DownloadFile($source, $destination)
# max=1445462016, used=898674904
# free
foreach ($thing in Get-Content $destination) {
$max = $thing.split("max=")
$used = $thing.split("used=")
Write-Host $max
Write-Host $used
}
#$free = $max - $used
#Write-Host $free
The string the file that is downloaded is a one-liner:
OK - Attribute get 'java.lang:type=Memory' - HeapMemoryUsage= javax.management.openmbean.CompositeDataSupport(compositeType=javax.management.openmbean.CompositeType(name=java.lang.management.MemoryUsage,items=((itemName=committed,itemType=javax.management.openmbean.SimpleType(name=java.lang.Long)),(itemName=init,itemType=javax.management.openmbean.SimpleType(name=java.lang.Long)),(itemName=max,itemType=javax.management.openmbean.SimpleType(name=java.lang.Long)),(itemName=used,itemType=javax.management.openmbean.SimpleType(name=java.lang.Long)))),contents={committed=1444478976, init=1494220800, max=1445462016, used=868228272})
And all I really want from it is:
max=1445462016
used=868228272
to be:
1445462016-868228272=577233744

I would extract the values from the contents={...} portion of the string with a regular expression, replace the commas with newlines and convert the result to a hashtable. Then you just need to cast the values to integers for the calculation.
Get-Content $destination | Where-Object {
$_ -match ',contents=\{(.+?)\}'
} | ForEach-Object {
$values = $matches[1] -replace ', ', "`n" | ConvertFrom-StringData
$free = [int]$values['max'] - [int]$values['used']
'Max: {0}' -f $values['max']
'Used: {0}' -f $values['used']
'Free: {0}' -f $free
}

I think I interpreted this correctly, do you want to display this in the console or store it in a variable, I'm assuming console here:
write-host "$max-$used="($max-$used)

I have figured out my own solution... I know it may not be the best way, but seems to work..
#http://stackoverflow.com/a/24036900/175063
$user="uuuu"
$pwd="pppp"
$source="http://1.1.1.1/manager/jmxproxy?get=java.lang:type=Memory&att=HeapMemoryUsage"
$destination="D:\Work\ps\test.xml"
$wc=new-object System.Net.WebClient
$p = New-Object System.Net.WebProxy 'http://proxy:8080'
$p.UseDefaultCredentials = $true
$wc.proxy=$p
$credCache=new-object System.Net.CredentialCache
$creds=new-object System.Net.NetworkCredential($user,$pwd)
$credCache.Add($source, "Basic", $creds)
$wc.Credentials=$credCache
$wc.DownloadFile($source, $destination)
# max=1445462016, used=898674904
# free
foreach ($thing in Get-Content $destination) {
# , max=1445462016, used=696318832})
# $a = $a.substring(2,3)
# MID: https://technet.microsoft.com/en-us/library/ee176901.aspx
# LEN: https://technet.microsoft.com/en-us/library/ee176895.aspx
# Instr: https://technet.microsoft.com/en-us/library/ee176876.aspx
$len = $thing.length
$maxst = $thing.indexof("max=")
$usedst = $thing.indexof("used=")
$max=$thing.substring($maxst+4,$len-$usedst-6)
$used=$thing.substring($usedst+5,$len-$usedst-7)
$free=$max-$used
# , max=1445462016, used=696318832})
write-host $len
write-host $maxst
write-host $usedst
write-host $max
write-host $used
write-host $free
}

Related

PowerShell filter in utf8 output from MSMQ journal

I have this code:
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
$queueName = '.\Private$\wwprodmsgqueue1.0\Journal$';
$queue = new-object System.Messaging.MessageQueue $queueName;
$utf8 = new-object System.Text.UTF8Encoding;
$msgs = $queue.GetAllMessages();
$msgs | %{
write-host $_.Id;
write-host $utf8.GetString($_.BodyStream.ToArray())
And I want to filter so I only get Journal for this name "A15C05U01_SAPProduced"
<MessageID>acc8bc3f-b0b7-4362-8c93-b80cf69c78f4</MessageID>
<MessageName>Produce Material</MessageName>
<Retry>false</Retry>
<MessageData>
<string>A15C05U01_SAPProduced</string>
<string>A15C05U01_ProdLog.Produce.LogProduced</string>
<string>A15C05U01</string>
<string>BSM_Förpackning.A15.Pallastare_5</string>
</MessageData>
Have tried with "| Where-Object {$utf8.MessageName -like "Produce Material"}"

Scope/persistence of data issue

I'm not sure what to search for to solve this one. I have a scope/persistence of data issue, where a variable used to populate my data structure is over-writing other items in the data structure (ImageFileName). This is my code:
###Functions...first two are just for info
#method to get messages for mdb files
#dependency-Need to download accessDatabaseEngine(64 bit) redestributable: https://www.microsoft.com/en-us/download/details.aspx?id=54920
Function ProcessHelpMDB{
[cmdletbinding()]
Param ([string]$mdbLookupError, [string]$mdbFilePath, [string]$mdbDeviceSeries) #$mdbLookupError = error number, like 701. $mdbDeviceSeries is 1000
Process
{
#Write-Host "mdbLookupString: $mdbLookupString" -ForegroundColor Cyan
$adOpenStatic = 3
$adLockOptimistic = 3
#Write-Host "In ProcessMDB" -ForegroundColor darkRed
#$pathViewBase = 'C:\me\EndToEnd_view\' #View dir. Maybe param later
#$pathToMdb = Join-Path -Path $pathViewBase -ChildPath $mdbFileName
$deviceTable = $mdbDeviceSeries + "PP"
$mdbLookupError -Match '[0-9]*-([0-9]*)'
$errLookup = $Matches[1]
#Write-Host "dps" -ForegroundColor DarkMagenta
$selectQuery = “SELECT [$($deviceTable)].[HelpCode],
[$($deviceTable)].[ScreenNumber],
[$($deviceTable)].[TextID],
[$($deviceTable)].[PictureID]
FROM [$($deviceTable)]
WHERE
[$($deviceTable)].[HelpCode] = $($errLookup)"
$cn = new-object -comobject ADODB.Connection
$rs = new-object -comobject ADODB.Recordset
$cn.Open("Provider = Microsoft.ACE.OLEDB.16.0;Data Source = $mdbFilePath")
$rs.Open($selectQuery,
$cn, $adOpenStatic, $adLockOptimistic)
$i=0
$ret = [System.Collections.Generic.List[psobject]]::new()
if($rs.EOF)
{
Write-Host "$mdbLookupString not in $mdbFileName...record set returned emtpy for query"
}#if
else
{
while($rs.EOF -ne $True)
{
$result = [ordered]#{}
#$hash = #{}
foreach ($field in $rs.Fields)
{
$result[$field.name] = $field.Value
}#result
$newObject = [PSCustomObject]$result
$ret.Add($newObject) #
$rs.MoveNext()
} #while
}#else
Write-Host "retArr[0] $($ret[0])" #prints retArr[0] #{PictureID=HELP_...; TextID=HELP_...; HelpCode=9; ScreenNumber=1}
$i=0
foreach($row in $ret) #goes thru all rows
{
Write-Host "retArr[0] $($ret[$i,"TextID"])" #prints retArr[0] #{HelpCode=9; ScreenNumber=1; TextID=HELP_...; PictureID=HELP_...}
####
Write-Host "retArr[] $($row)" #prints retArr[] #{HelpCode=9; ScreenNumber=1; TextID=HELP_...; PictureID=HELP_7000_POWER_COVER_RIBBON}
Write-Host "retArr[0] $($row[$i])" #prints retArr[0] #{HelpCode=9; ScreenNumber=1; TextID=HELP_...; PictureID=HELP_...}
$i++
}
foreach($row in $ret.GetEnumerator()) #this is working for each row
{
Write-Host $row.TextID #prints HELP_...
Write-Host $row.'TextID' #prints HELP_...
}
$ret | ForEach-Object {
Write-Host TextID= $($_.TextID) #prints TextID= HELP_...
Write-Host TextID= $($_.'TextID') #prints TextID= HELP_...
} #
$cn.Close()
return $ret #Items queried from db ################################################# need to put them in excel file in order next
} #end Process
}# End of Function process mdb's
#This function gets mdb info out and returns English-US message found
Function ProcessK_MDB{
[cmdletbinding()]
Param ([string]$mdbLookupstring) #$mdbLookupString like HELP_...
Process
{
$adOpenStatic = 3
$adLockOptimistic = 3
$pathViewBase = 'C:\me\\EndToEnd_view\' #View dir. Maybe param later
$mdbFileNamePath = 'KAppText.mdb'
$pathToMdb = Join-Path -Path $pathViewBase -ChildPath $mdbFileNamePath
if(Test-Path $pathToMdb)
{
$selectQuery = “SELECT [Messages].[Message Description],
[Messages].[English - Us]
FROM [Messages]
WHERE [Messages].[Message Description] = '$($mdbLookupString)'”
$cn = new-object -comobject ADODB.Connection
$rs = new-object -comobject ADODB.Recordset
$cn.Open("Provider = Microsoft.ACE.OLEDB.16.0;Data Source = $pathToMdb")
$rs.Open($selectQuery,
$cn, $adOpenStatic, $adLockOptimistic)
if($rs.EOF) #empty
{
Write-Host "$mdbLookupString not in $mdbFileName...record set returned emtpy for query"
$ret = ""
}#if
else #got results
{
$returnArr = $rs.GetRows()
#$ret = $returnArr[0,1]
#$ret2 = $returnArr[1,1]
$ret = $returnArr[1,0] #has long text
#$ret4 = $returnArr[0,0] #has short text
#Write-Host $ret
}#else got results
$cn.Close()
} #testPath
else {
Write-Host "$pathToMdb does not exist"
}
return $ret #Message English-US for parameter/Message Description given
} #end Process
}# End of Function process mdb's
Function Get-ImageName{
[cmdletbinding()]
Param ([string]$imageName, [string]$fileNamePath)
Process
{
#find image file name to look for
[System.String] $pictureName = ""
if($imageName -Match "HELP")
{
#remove "HELP" part of file name
$($row.PictureID) -Match "HELP_(.*)" #get the part after HELP_
Write-Host $Matches[0]
Write-Host $Matches[1]
$pictureName = $Matches[1]
}
else {
$pictureName = $imageName
}
$imageFile2 = Get-ChildItem -Recurse -Path $ImageFullBasePath -Include #("*.bmp","*.jpg","*.png") | Where-Object {$_.Name -match "$($pictureName)"} #$imageFile | Select-String -Pattern '$($pictureName)' -AllMatches
Write-Host "ImageFile2: $($imageFile2)"
$imgFile = ""
foreach($imgFile in $imageFile2) #there may be more than one...just get last one...there are multiple telephone images
{
if($imgFile.Exists) #if($imageFile2.Exists)
{
#$image = [System.Drawing.Image]::FromFile($imgFile) #may not need this step
#need to figure out which is correct if there's multiple images
return $imgFile
}
else {
Write-Host "$($imgFile) does not exist"
return $null
}
} #foreach imageFile2
return $null
} #end Process
}# End of Function process mdb's
###main####
$resultHelp = ProcessHelpMDB -mdbLookupError $errCode -mdbFilePath $basePathFull -mdbDeviceSeries $deviceVer #######
$result = foreach($row in $resultHelp.GetEnumerator()) #this is working for each row
{
if($row -ne $True) #not sure why it adds true at the top
{
Write-Host $row.TextID #prints HELP_...
#lookup value from kapptext.mdb
Write-Host $($row.TextID) #prints nothing but looks ok in next function
$longText = ProcessK_MDB -mdbLookupstring $($row.TextID) #gives English-US message from device for parameter given
#insert images######################
#I can see that these are assigned correctly and returned from Function:
[System.Drawing.Image] $image = New-Object System.Drawing.Image #error...see Update2
[System.String] $imageNamePath = New-Object System.String #error...see Update2
[System.String] $imageNamePath = Get-ImageName -imageName $($row.PictureID) -fileNamePath $ImageFullBasePath
if($null -ne $imageNamePath)
{
$image = Get-Image -imageFileName $imageNamePath
}
else
{
Write-Host "Did not find an image file for $($row.PictureID) in $ImageFullBasePath"
}
#get the data ready to put in spreadsheet
New-Object psobject -Property $([ordered]#{
ScreenNumber = $($row.ScreenNumber)
KPMKey = $($row.TextID)
EnglishUS = $($longText)
PictureID = $($row.PictureID)
ImageFound = ""
ImageFileName = $($imageNamePath) ###???this is over-written...all same in $result after done with loop
})
} #if not true
} #foreach row $resultHelp
##note: $image gets inserted in the spreadsheet later, but since the names aren't showing correctly when use $results, I'm not sharing that part.
I can see after this runs for the 9 rows, that each ImageFileName is the same in $result. How do I do this so it maintains what is returned from the method? Right now I am trying New-Object, but it didn't fix the issue.
This is what $resultHelp looks like:
[0] $true (I'm not sure why it puts true at the top) [1]
#(HelpCode=9;ScreenNumber=1;TextID=HELP_...JA;PictureID=HELP_...RIB)
[2]
#(HelpCode=9;ScreenNumber=2;TextID=HELP_...ROLL;PictureID=HELP_...ROLL)
[3]
#(HelpCode=9;ScreenNumber=3;TextID=HELP_...EDGE;PictureID=HELP_...UT)
...
I am using Powershell 5.1 and VSCode.
Update:
I checked again, and in Get-ImageName, it's returning a file name like "Contact_Service"...bmp and it looks like it's getting put in the psObject ImageFileName...($imageNamePath), and the same thing for the other images found. When I look in the end, $result has all the same values for that ImageFileName. and the one that used to say "Contact_Service"..bmp is something else now, matching the other ones in $result.
Update2:
There are a couple errors:
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type System.Drawing.Image
and
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type System.String.
for where I tried dealing with the object over-write issue in the main code
Update3:
After I get the psobject in good shape, I put it in a spreadsheet with Export-Excel. I just wanted to give this info so you know why I'm putting it in the psobject like that:
$xlsx = $result | Export-Excel -Path $outFilePath -WorksheetName $errCode -Autosize -AutoFilter -FreezeTopRow -BoldTopRow -PassThru # -ClearSheet can't ClearSheet every time or it clears previous data
I figured it out.
the problem was that even though I was finding different $imageNamePaths for to assign to the Property as ImageFileName for each PictureID, and assigning those properties in the psobject in the foreach loop, I wound up with the same thing for each ImageFileName property (overwritten). This fixed it.
New-Object psobject -Property $([ordered]#{
ScreenNumber = $($row.ScreenNumber)
KPMKey = $($row.TextID)
EnglishUS = $($longText)
PictureID = $($row.PictureID)
ImageFound = ""
ImageFileName = "$($imageNamePath)" ####added double quotes
})
The double quotes let the different $imageNamePath values remain instead of being over-written. I'm not exactly sure why.
And thank you #Mathias, I will suppress output from my -Match to see if the $true is removed at the top of my data returned from the Function. :)

update a cell in a excel sheet using powershell

I need to search for a word in a row from a spreadsheet and update another cell in the same row with a different value. For example, I have the data like this. I need to search for the person "Smith" from the below spreadsheet and update the value of the 'Status' column from 'Enabled' to 'Disabled' for that row.
"Region","Zone","Customer","Process","Status"
"TEST","East","Smith","HR","Disabled"
"TEST","East","Allen","Finance","Enabled"
"TEST","East","Jake","Payroll","Enabled"
I tried regex and few other functions before posting the question. But I can't get them to work.
Thanks.
It's very easy to use Excel with PowerShell:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$excelFile = 'C:\test\testsheet.xlsx'
$searchFor = 'Smith'
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.ScreenUpdating = $true
$workbook = $excel.Workbooks.Open( $excelFile ,$null, $false )
$ws = $workbook.WorkSheets.item(1)
[void]$ws.Activate()
$searchRange = $ws.UsedRange
$searchResult = $searchRange.Find( $searchFor, [System.Type]::Missing, [System.Type]::Missing,
[Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole,
[Microsoft.Office.Interop.Excel.XlSearchOrder]::xlByColumns,
[Microsoft.Office.Interop.Excel.XlSearchDirection]::xlNext )
while( $searchResult ) {
$row = $searchResult.Row
$col = $searchResult.Column
$ws.Cells( $row, $col + 2 ).Value2 = 'Disabled'
$searchResult = $searchRange.FindNext( $searchResult )
if( $searchResult -and $searchResult.Row -le $row ) {
break
}
}
[void]$workbook.Save()
[void]$workbook.Close()
[void]$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
I got it working using the below script.
$TGTSERVER = "testservwc01"
$name = "ORATDLLSTR"
$input = Invoke-Command -ComputerName "$TGTSERVER" -ScriptBlock {Import-Csv 'C:\test.csv'}
$value = "Disabled"
$Output = foreach ($i in $input) {
if ($i.Process_Instance -match "$name") {$i.Status = "$value"} $i }
$OutArray = $Output | Select-Object -Property * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName
$OutArray | Invoke-Command -ComputerName "$TGTSERVER" -ScriptBlock {Export-Csv 'C:\test.csv' -NoTypeInformation}
if ( $LastExitCode -ge 1)
{
Write-Warning -Message "$Computer : Disable Step failed"
exit 1
}
However the script fails with exit code 1 even though it updates the csv file with the right value on the remote server.
I have found solution which meet my needs... using Powershell
Not the issue mentioned as in topic.. but overall module have a lot of options which might help modify Excel File using PowerShell
https://www.powershellgallery.com/packages/PSWriteExcel/0.1.15
https://github.com/EvotecIT/PSWriteExcel/blob/master/Examples/Run-Example-FindReplace.ps1
Install-Module -Name PSWriteExcel
Import-Module PSWriteExcel -Force
$FilePath = "D:\Excel_test.xlsx"
$FilePathOutput = "D:\Excel_test1.xlsx"
Find-ExcelDocumentText -FilePath $FilePath -Find 'evotec' -Replace -ReplaceWith 'somethingelse' -FilePathTarget $FilePathOutput -OpenWorkBook -Regex -Suppress $true

What can I change in this script to prevent an infinite loop

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
}

PowerShell - Send-MailMessage - Export mail to a file

I'm using the Send-MailMessgae Cmdlet to send an automated message with content each quarter.
The actual email works as expected etc however I want to save a copy of this email to a network share.
I've tried using Tee-Object to place it in a variable and then out-file to save it but this did not work.
I'm I'm thinking the only way i'm going to be able to do this is to just create a Here String with the details in it them output that.
Ideally I would like it to be in the .eml format as its a conformation that we are notifying users for the project the email is for.
I hope this makes sense.
Kind Regards,
Nigel Tatschner
You could actually use Tee-Object to send the data straight to the file, instead of trying to use both Out-File and Tee-Object.
$logfile = 'C:\data\logfiles'
<data> | Tee-Object $logfile -Append
You can use System.Net.Mail.MailMessage
# Based on MailMessageExt
# By Allan Eagle | 11 Jan 2009
# http://www.codeproject.com/KB/IP/smtpclientext.aspx
######################################
function createMailMessage([string]$from, [string]$to, [string]$subject) {
[System.Net.Mail.MailMessage]$msg = New-Object -TypeName "System.Net.Mail.MailMessage" -ArgumentList $from, $to
[System.Text.Encoding]$enc = [System.Text.Encoding]::UTF8
$msg.SubjectEncoding = $enc
$msg.Subject = $subject
$msg.BodyEncoding = $enc
return $msg
}
######################################
function mailAddAttachment([System.Net.Mail.MailMessage]$msg, [string]$filePath) {
$fileExists = Test-Path -path $filePath -pathtype leaf
if ($fileExists) {
$fileName = Split-Path $filePath -Leaf
[System.Net.Mail.Attachment]$att = New-Object -TypeName "System.Net.Mail.Attachment" -ArgumentList $filePath
$att.ContentType.MediaType = [System.Net.Mime.MediaTypeNames+Application]::Octet
$att.ContentType.Name = $fileName
$att.ContentDisposition.FileName = $fileName
$att.ContentDisposition.DispositionType = [System.Net.Mime.DispositionTypeNames]::Attachment
$att.ContentDisposition.Inline = $false
$att.TransferEncoding = [System.Net.Mime.TransferEncoding]::Base64
$msg.Attachments.Add($att)
$att = $null
return $true
} else {
$txt = "File ""$filePath"" not found"
Write-Output $txt
return $false
}
}
######################################
function saveMailMessage([System.Net.Mail.MailMessage]$msg, [string]$filePath) {
$binding = [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic
$mailMessageType = $msg.GetType()
$emlFilePath = $filePath
[System.Type]$scType = [System.Type]::GetType("System.Net.Mail.SmtpClient")
[System.Net.Mail.SmtpClient]$smtpClient = New-Object -TypeName "System.Net.Mail.SmtpClient"
$scType = $smtpClient.GetType()
[System.Type]$booleanType = [System.Type]::GetType("System.Boolean")
[System.Reflection.Assembly]$assembly = $scType.Assembly
[System.Type]$mailWriterType = $assembly.GetType("System.Net.Mail.MailWriter")
[System.IO.FileStream]$fileStream = New-Object -TypeName "System.IO.FileStream" -ArgumentList ($emlFilePath,[System.IO.FileMode]::Create)
[System.Array]$typeArray = ([System.Type]::GetType("System.IO.Stream"))
[System.Reflection.ConstructorInfo]$mailWriterConstructor = $mailWriterType.GetConstructor($binding ,$null, $typeArray, $null)
[System.Array]$paramArray = ($fileStream)
$mailWriter = $mailWriterConstructor.Invoke($paramArray)
#get MailMessage.Send(MailWriter,Boolean,Boolean)
$doubleBool = $true
[System.Array]$typeArray = ($mailWriter.GetType(),$booleanType,$booleanType)
[System.Reflection.MethodInfo]$sendMethod = $mailMessageType.GetMethod("Send", $binding, $null, $typeArray, $null)
if ($null -eq $sendMethod) {
$doubleBool = $false
[System.Array]$typeArray = ($mailWriter.GetType(),$booleanType)
[System.Reflection.MethodInfo]$sendMethod = $mailMessageType.GetMethod("Send", $binding, $null, $typeArray, $null)
}
#get MailWriter.Close()
[System.Array]$typeArray = #()
[System.Reflection.MethodInfo]$closeMethod = $mailWriterType.GetMethod("Close", $binding, $null, $typeArray, $null)
#execute MailMessage.Send(MailWriter,Boolean,Boolean)
[System.Array]$sendParams = ($mailWriter,$true)
if ($doubleBool) {
[System.Array]$sendParams = ($mailWriter,$true,$true)
}
$sendMethod.Invoke($msg,$binding,$null,$sendParams,$null)
#execute MailWriter.Close()
[System.Array]$closeParams = #()
$closeMethod.Invoke($mailWriter,$binding,$null,$closeParams,$null)
}
######################################
function Get-ScriptDirectory {
Split-Path -Parent $PSCommandPath
}
######################################
$smtpServer = "smtp.here.com"
$smtpPort = 25
######################################
#$fileDir = Convert-Path "."
$fileDir = Get-ScriptDirectory
$fileDir
[System.Text.Encoding]$enc = [System.Text.Encoding]::UTF8
$dt = Get-Date
$dtStart = Get-Date $dt -Hour 0 -Minute 0 -Second 0
$baseName = $fileDir+"\report_"+$dtStart.toString("yyyy-MM-dd")
$repName = $baseName+".csv"
$emlName = $baseName+".eml"
[System.Collections.ArrayList]$rep = #()
$rep.Add("This is a report")
$rep.Add("----------------")
for ($i=0; $i -lt 100; $i++) {
$index = $rep.Add("Line $i")
}
Set-Content $repName $rep
$from = "Sender <Me#here.com>"
$to = "Recipient <Them#there.com>"
$subject = "This is a report generated here on "+$dtStart.toString("yyyy-MM-dd")
$body = "$subject`n`n$repName"
[System.Net.Mail.MailMessage]$msg = createMailMessage $from $to $subject
$msg.IsBodyHtml = $false
$msg.Body = $body
mailAddAttachment $msg $repName
$emlName
[System.Net.Mail.SmtpClient]$smtp = New-Object -TypeName "System.Net.Mail.SmtpClient" -ArgumentList $smtpServer, $smtpPort
# $smtp.Send($msg)
saveMailMessage $msg $emlName
$msg.Dispose()
Remove-Item $repName
Pause