【问题标题】:IF statement + send-mailmessage confusedIF 语句 + send-mailmessage 混淆
【发布时间】:2017-02-04 22:41:45
【问题描述】:

快速提问; 我想记录服务器上发生的坏事,但这不是问题。

日志应该在发送时被删除,如果在脚本运行时没有日志,它应该发送不同的消息,不带附件。

这是目前为止的脚本:

        <#
Set-ExecutionPolicy unrestricted -Force
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
cinst BetterCredentials
#>

Import-Module BetterCredentials
$Mailcred = Get-Credential -user user@gmail.com -pass 12345password
Try{
$File = C:/path/errorfile.log
}
Catch [System.Management.Automation.PSArgumentException]
 {
  "invalid object"
 }
 Catch [system.exception]
 {
  "caught a system exception"
 }
Finally
 {
If ($File -eq ){
    then (send-mailmessage -ErrorAction SilentlyContinue -from "Server         <Server@company.com>" -to "IT Dept. <Itdept@company.com>" -subject "Log of the day." -body             "Good Morning,

    Fortuneatly, nothing bad to report today!" -priority High -dno onSuccess, onFailure      -smtpServer smtp.company.com -credential ($Mailcred) -usessl)

        else (send-mailmessage -ErrorAction SilentlyContinue -from "Servers     <Server@company.com>" -to "IT Dept. <ITDept@company.com>" -subject "Log of the day." -body     "Good Morning,

        Here is your daily report." -Attachments $File -priority High -dno onSuccess,     onFailure  -smtpServer smtp.company.com -credential ($Mailcred) -usessl)
        }
}

我在这里做错了什么?

【问题讨论】:

    标签: powershell if-statement powershell-4.0


    【解决方案1】:

    您的代码的某些部分没有任何意义。让我们回顾一下。

    $File = C:/path/errorfile.log
    ...
    If ($File -eq ){
    

    第一部分是关于分配的。为了找出errorfile.log 是否存在,像这样使用Test-Path cmdlet,

    $File = test-path 'C:/path/errorfile.log'
    

    始终在文件名周围使用引号。如果路径中有空格,则未加引号的路径不起作用。

    第二部分是实际测试。

    If ($File){
    ... # file was on disk, send alert and delete it
    } else {
    ... # no file found, send ok 
    }
    

    【讨论】:

    • 这就像一个魅力!太感谢了。确实需要几分钟才能确定为文件路径分配一个新的 arg 以发送实际附件。 :-0 但是,您是救生员!谢谢你。也删除了 Try、Catch、Final 行
    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多