Answer the question
In order to leave comments, you need to log in
Powershell, what's wrong with the encoding in a variable?
Good afternoon!
Necessary: on Windows, automate the sending of files by mail from a certain folder in separate letters, so that one letter is one file.
Of the nuances: The path to the folder contains Russian letters and square brackets.
A simple script was written on PS:
$filename = "sendmail.log"
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition #Директория где запущен скрипт, без последнего "\"
$path = $scriptPath + "\" + $filename
function logging ($LogMessage){
"$(Get-Date -UFormat "%d-%m-%Y %T") $LogMessage"|out-file $path -Append
}
function SendMailToUser($To,$ErrorTo) {
$From="[email protected]"
$Subject="Invoice"
$Body="Invoice"
$Password="12345"
$SecPassword=New-Object -TypeName System.Security.SecureString
$Password.ToCharArray() | foreach {$SecPassword.AppendChar($_)}
$Credintial=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $From,$SecPassword
$smtpServer="test.ru"
$encoding = [System.Text.Encoding]::UTF8
$InvoicesPath = 'B:\TEMP\рус[1]\*'
$invoices = Get-ChildItem $InvoicesPath | % { $_.FullName }
foreach ($invoice in $invoices)
{try{
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -Credential $Credintial -SmtpServer $smtpServer -Attachments $invoice -Encoding $encoding -ErrorAction Stop
logging -LogMessage "$Invoice sent successfully"
Remove-Item $invoice
logging -LogMessage "$Invoice cleared successfully"
}
catch{
$ErrorSubject="Error sending: $invoice"
$ErrorBody="$(Get-date)111 Error:$($Error[0])"
Send-MailMessage -From $From -To $ErrorTo -Subject $ErrorSubject -Body $ErrorBody -Credential $Credintial -SmtpServer $smtpServer -Encoding $encoding
logging -LogMessage "$Invoice was not send! Error:$($Error[0])"
}
}
}
SendMailToUser -To "[email protected]" -ErrorTo "[email protected]"
Get-ChildItem : Не удается найти путь "B:\TEMP\С?С?С?", так как он не существует.
C:\bin\sendmail.ps1:28 знак:17
+ $invoices = Get-ChildItem $InvoicesPath | % { $_.FullName }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (B:\TEMP\С?С?С?:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Answer the question
In order to leave comments, you need to log in
Most likely you have a script file in utf-8 or utf-16 encoding without BOM. Try resaving it in utf-8 encoding with BOM or in 1251
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question