Разрешить DNS, экспортировать в Excel и HTML, затем отправить почту

Я почти закончил со своим сценарием и немного отредактировал поздно вечером и переписал свою старую версию, так что я не могу вернуться.

Скрипт работал нормально, все еще требовались некоторые настройки, но теперь он полностью остановился.

Идея состоит в том, чтобы собрать список IP-адресов. Определите IP-адреса и поместите их на лист Excel. Затем сохраните лист в форматах htm и xlsx. И, наконец, отправил их мне по почте.

Теперь он застревает при сортировке листа, сохранении И отправке по почте ... Может кто-нибудь дать мне некоторое представление о том, что я сделал здесь не так?

он застревает при сортировке листа, сохранении И отправке по почте.

Он больше не сортирует B3: B $ Count:

Исключение, вызывающее «Сортировка» с аргументом (-ами) «1»: «Ссылка на сортировку недействительна. Убедитесь, что она находится в пределах данных, которые вы хотите отсортировать, а первое поле« Сортировать по »не то же самое или пустое». < br> В C: \ Folder \ Scripts \ Get-IP.ps1: 137 символов: 5
+ [void] $ objRange.Sort ($ objRange2)
+ ~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo: NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId: ComMethodTargetInvocation

Он больше не сохраняет файл xlsx, но сохраняет файл HTM. Он явно что-то не затирает. Я даже перезапустил, чтобы убедиться.

Исключение, вызывающее «SaveAs» с аргументом (ами) «1»: «Microsoft Excel не может получить доступ к файлу 'C: // Folder / BlockedIP / HTML / 2014-07-08 / 0BCEF810'. Workbook.»
На C: \ Folder \ Scripts \ Get-IP.ps1: 160 символов: 5
+ $ b.SaveAs ("$ FileXML")
+ ~~~~~~~~~~~~~~~~~ ~~~~
+ CategoryInfo: NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId: ComMethodTargetInvocation

И, наконец, он больше не будет присылать мне электронные письма:

New-Object: исключение, вызывающее ".ctor" с аргументом (ами) "2": "Указанная строка не в форме, требуемой для адреса электронной почты".
В C: \ Folder \ Scripts \ Get- IP.ps1: 217 символов: 13
+ $ SMTP = New-Object System.Net.Mail.MailMessage ($ SMTP, 587)
+ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo: InvalidOperation: (:) [New-Object ], MethodInvocationException
+ FullyQualifiedErrorId: ConstructorInvokedThrowException, Microsoft.PowerShell.Commands.NewObjectCommand

Сценарий:

#Get current date
$Date = get-date -format yyyy-MM-dd

#Define all files/Paths.
$Path = "C:/Folder/BlockedIP"
md "$Path/HTML/$Date" -Force
    $path2 = "$Path/HTML/$Date"
$PathWeb = "/HTML/$Date"

#Define File's used or created in this script.
$File = "$Path/IP-$Date.txt"
    $FileHtml = "$Path2/IP-$Date.htm"
    $FileXML = "$Path2/IP-$Date.xlsx"
    $FileHTMLWeb = "$PathWeb/IP-$date.htm"

#Get content from given IP list.
$colComputers = @(get-content $File | Sort -unique)
   $count = $colComputers.Count
       write-output "$Count IP's detected."

#Define error actions.
#$erroractionpreference = "SilentlyContinue"

#Open Excel.
$a = New-Object -comobject Excel.Application

#Since we want this script to look like it's being used without excel I set it's visibility to false.
$a.visible = $True

#Disable excel confirmations.
$a.DisplayAlerts = $False

#Create sheets in Excel.
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)

#Create a Title for the first worksheet and adjust the font
$row = 1
$Column = 1
target="_parent">Creator'
$c.Cells.Item($row,$column)= "Blocked IP's $Date"
$c.Cells.Item($row,$column).Font.Size = 18
$c.Cells.Item($row,$column).Font.Bold=$True
$c.Cells.Item($row,$column).Font.Name = "Cambria"
$c.Cells.Item($row,$column).Font.ThemeFont = 1
$c.Cells.Item($row,$column).Font.ThemeColor = 4
$c.Cells.Item($row,$column).Font.ColorIndex = 55
$c.Cells.Item($row,$column).Font.Color = 8210719
$range = $c.Range("a1","e1")
$range.Merge() | Out-Null
$range.VerticalAlignment = -4160

#Define subjects.
$c.Name = "Blocked IP's ($Date)"
$c.Cells.Item(2,1) = "Given IP"
$c.Cells.Item(2,2) = "Resolved DNS"
$c.Cells.Item(2,3) = "Returned IP"
$c.Cells.Item(2,5) = "Company name"

#Define cell formatting from subjects.
$c.Range("A2:E2").Interior.ColorIndex = 6
$c.Range("A2:E2").font.size = 13
$c.Range("A2:E2").Font.ColorIndex = 1
$c.Range("A2:E2").Font.Bold = $True

#Define the usedrange for autofitting.
$d = $c.UsedRange

#Make everything fit in it's cell
$D.EntireColumn.AutoFit() | Out-Null

#Define html code for Excel save to .htm.
$xlExcelHTML = 44

#Define rows to alter in excel.
$iRow = 3
$intRow = 3

#Time to run the script.
foreach ($strComputer in $colComputers)
{
#Place IP's from text in the excel sheet
$c.Cells.Item($intRow, 1) = $strComputer.ToUpper()
$d.EntireColumn.AutoFit() | Out-Null

#Create a status bar for the script
$i = 1
Write-Progress -Activity `
"Creating a usable 'Blocked IP' list ($i/$count)" `
-PercentComplete ($i/$colComputers.Count*100) `
-Status "Please stand by"

try {
    $dnsresult = [System.Net.DNS]::GetHostEntry($strComputer)
    }
    catch {
          $dnsresult = "$null"
          }

#Clear screen on every checked IP to remove the 'True' statement.
#cls

#Do something with $dnsresults.

#Display information about host
#Give hostname Entry in Cell2
$c.Cells.Item($intRow,2) = $dnsresult.HostName

#IP listed in Cell 3
$c.Cells.Item($intRow,3) = $dnsresult.AddressList[0].IpAddressToString

#Make everything fit in it's cell.
$d.EntireColumn.AutoFit() | Out-Null

#Define row for the IP list.
$intRow = $intRow + 1

#Set background color for the IP list.
$d.Range("A$($iRow):E$($intRow)").interior.colorindex = 15

#Sort all IP's on resolved name.
$objWorksheet = $b.Worksheets.Item(1) 
$objRange = $objWorksheet.UsedRange 
$objRange2 = $objworksheet.Range("B3:B($Count)")  
[void] $objRange.Sort($objRange2) 

#Define borders here.
<# Insert script :D #>

#Define Filters here. (Picking out blank DNS and giving those a name)
<# Insert script :D #>

#Define Filters here. (Picking out specific DNS name and give them color code)
<# Insert script :D #>

#Make everything fit in it's cell.
$d.EntireColumn.AutoFit() | Out-Null



#Clear screen on every checked IP to remove the 'True' statement.
#cls
}
#Save the file as .xlsx on every placed IP to ensure the file is not lost due to any reason.
$b.SaveAs("$FileXML")

#Save final result as a .htm file
$b.SaveAs("$FileHTML",$xlExcelHTML)

#Close and quit Excel.
$b.Close()
get-process *Excel* | Stop-Process -force

#Move .txt file to the correct HTML folder.
move-item $file $path2 -Force

#Clear screen, again. (Let's keep things tidy.)
#cls

#Variables for public IP
# I am defining website url in a variable
$url = "http://checkip.dyndns.com" 
# Creating a new .Net Object names a System.Net.Webclient
$webclient = New-Object System.Net.WebClient
# In this new webdownlader object we are telling $webclient to download the
# url $url 
$IpPublic = $webclient.DownloadString($url)
# Just a simple text manuplation to get the ipadress form downloaded URL
# If you want to know what it contain try to see the variable $IpPublic
$IpPublic2 = $IpPublic.ToString()
$ipPublic3 = $IpPublic2.Split(" ")
$ipPublic4 = $ipPublic3[5]
$ipPublic5 = $ipPublic4.replace("</body>","")
$FinalIPAddress = $ipPublic5.replace("</html>","")

#Variables e-mail.
$From = "Blocked IP <##@g##.com>"
$To = "IT Dept <##@##.nl>"
$CC = "Someone <##r@##.nl"
$SMTP = "smtp.gmail.com"
$Subject = "Blocked IPs for $date ($Count Total)"
#The href should point to the htm file in your iis/apache folder.
$WebLink = $FinalIPAddress+$FileHtmlWeb
$here = "<a href='http://$Weblink'><b>Here</b></a>"
#Define the body of your e-mail, in this case it displays a message and shows the server it is send from with it's local IP.
#A link to the .htm file, how many IP's were blocked and the date of the message.
$Body = "This is an automated message generated by server: $env:COMPUTERNAME, $IP</br></br>
Please see the attachment or click $here to get the $Count blocked IP's of $date. </br>    </br></br>"

#Variables e-mail user.
$username = "##@##.com"
$password = "##"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$ip = (Get-WmiObject -class win32_NetworkAdapterConfiguration -Filter 'ipenabled = "true"').ipaddress[0]

#Clear screen, again. (Let's keep things tidy.)
#cls

#Send output as e-mail.
$SMTP = New-Object System.Net.Mail.MailMessage($SMTP, 587) 
$SMTP.EnableSsl = $true 
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$username", "$password"); 
$SMTP.isbodyhtml= $true
$SMTP.Send($From, $To, $Subject, $FileXML, $Body)

send-mailmessage -BodyAsHtml -from $From -to $To -cc $CC -subject $Subject -Attachments     $FileXML -body $Body -priority High -smtpServer $SMTP -credential ($cred) -usessl


#Create a function to relase Com object at end of script.
function Release-Ref ($ref) { 
    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( 
    [System.__ComObject]$ref) -gt 0) 
    [System.GC]::Collect() 
    [System.GC]::WaitForPendingFinalizers() 
                            }

#Release COM Object
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$a) |     Out-Null

#Clear screen for the final time. (Let's keep things tidy.)
#cls

#Exit powershell 
exit

Любая помощь будет оценена!


person Remy van Tour    schedule 08.07.2014    source источник
comment
Определить застрял. Что именно не работает? Поиск DNS? Заполнение листа Excel? Отправляете почту? Каковы ожидаемые результаты и чем они отличаются от фактических результатов? Вы получаете сообщение об ошибке? Если да, то что там написано?   -  person Ansgar Wiechers    schedule 08.07.2014
comment
Выполнено. :-) Есть мысли?   -  person Remy van Tour    schedule 08.07.2014
comment
Как насчет строки target="_parent">Creator', которая не является допустимой строкой? Кроме того, $objRange2 = $objworksheet.Range("B3:B($Count)") избавьтесь от () вокруг $Count. И что-то насчет определения $ SMTP впервые и ссылки на себя не кажутся правильными.   -  person TheMadTechnician    schedule 08.07.2014


Ответы (2)


Исключение, вызывающее "Сортировка" с аргументом (-ами) "1": "Ссылка на сортировку недействительна. Убедитесь, что она находится в пределах данных, которые вы хотите отсортировать, а первое поле" Сортировать по "не то же самое или пустое. . "

Еще раз проверьте, что $objRange и $objRange2 ссылаются на правильные диапазоны:

$objRange.Address()
$objRange2.Address()

Я не могу больше сказать вам здесь, не увидев ваших фактических данных.


Исключение, вызывающее "SaveAs" с аргументом (ами) "1": "Microsoft Excel не может получить доступ к файлу 'C: // Folder / BlockedIP / HTML / 2014-07-08 / 0BCEF810'. workbook."

Если бы путь действительно был C://Folder/..., вы бы получили другое исключение. Пожалуйста, не придумывайте сообщения об ошибках.


New-Object: исключение, вызывающее ".ctor" с аргументом (ами) "2": "Указанная строка не находится в форме, требуемой для адреса электронной почты."

Вы путаете MailMessage и SmtpClient. Не говоря уже о том, что они вам даже не нужны, так как вы все равно используете Send-MailMessage. Просто удалите следующие 5 строк:

$SMTP = New-Object System.Net.Mail.MailMessage($SMTP, 587) 
$SMTP.EnableSsl = $true 
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$username", "$password"); 
$SMTP.isbodyhtml= $true
$SMTP.Send($From, $To, $Subject, $FileXML, $Body)
person Ansgar Wiechers    schedule 08.07.2014
comment
Я тоже видел эти три вещи. Он явно изменил вещи для публикации, поскольку номера его строк в его ошибках не совпадают с его кодом, который он опубликовал. Спасибо, что написали это так красноречиво, что ваш ответ намного легче читать, он имеет больше смысла и более подробен, чем мой бессвязный небольшой комментарий. - person TheMadTechnician; 08.07.2014

Решил проблему сортировки, изменив код на:

$objRange = $c.Range("A$($iRow):E$($intRow)")
$objRange2 = $c.Range("B$($iRow):B$($intRow)")
[void] $objRange.Sort($objRange2) 

Оказывается, он застрял в заголовке в XML-файле.

Заменена рассылка на:

$From = "Blocked IP <##@##.##>"
$To = "IT Dept <##@##.##>"
$CC = "Someone <##@##.##"
$Subject = "Blocked IPs for $date ($Count Total)"
#The href should point to the htm file in your iis/apache folder.
$WebLink = $FinalIPAddress+$FileHtmlWeb
$here = "<a href='http://$Weblink'><b>Here</b></a>"
#Define the body of your e-mail, in this case it displays a message and shows the server it is send from with it's local IP.
#A link to the .htm file, how many IP's were blocked and the date of the message.
$body = "Dear <font color=black>$to</font>,<br><br>"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "##@gmail.com"
$Password = "##"
$message = New-Object System.Net.Mail.MailMessage
$message.IsBodyHTML = $true
$message.ReplyTo = $From
$message.Sender = $From
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($MailXML)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)

Сохранение файла оказалось ошибочным путем. Поскольку лист Excel был создан из folder1, он не будет сразу сохраняться в папке 2, поскольку его временный файл сохранения останется в folder1.

person Remy van Tour    schedule 09.07.2014