如果它没有找到指定的进程,则获取进程输出值

时间:2016-05-19 21:59:39

标签: powershell outlook

如果找不到指定的进程,Get-Process输出值是多少?例如,我正在检查Outlook是否已关闭,如果是,我将备份PST文件。这是我的代码:

$source = "C:\Users\----\AppData\Local\Microsoft\Outlook\Outlook.pst"
$destination = "\\----\users\----\outlook"

$isOutlookOpen = Get-Process outlook*
$isOutlookOpen
if($isOutlookOpen = $true){
    # Outlook is already closed:
    Copy-Item -Path $source -Destination $destination
    $messageParameters = @{
        Subject = "Daily Outlook Backup Report computer"
        Body = "Outlook was closed. Backup was complete."
        From = "---"
        To = "---"
        SmtpServer = "---"
        Port = ---
    }
    Send-MailMessage @messageParameters -BodyAsHtml
} else {
    $messageParameters = @{
        Subject = "Daily Outlook Backup Report computer"
        Body = "Outlook was not closed. Backup was not initiated."
        From = "---"
        To = "---"
        SmtpServer = "---"
        Port = ---
    }
    Send-MailMessage @messageParameters -BodyAsHtml
}

总是转到else声明。

2 个答案:

答案 0 :(得分:1)

您在条件中使用assignment operator=),因此它将始终评估为$true。 PowerShell中的等级comparison operator-eq

话虽如此,你首先不需要那里的运营商。 Get-Process会返回System.Diagnostics.Process个对象的列表(如果找不到匹配的进程,则返回$null)。您可以使用变量$isOutlookOpen的值作为布尔值,因为PowerShell将interpret非空数组作为布尔值$true$null作为布尔值$false

这应该有效:

$isOutlookOpen = Get-Process outlook*
if($isOutlookOpen) {
    # ...
} else {
    # ...
}

答案 1 :(得分:0)

在您的代码中,您正在检查某些内容是否为$ true,因为它的值将是该过程的详细信息:

$isOutlookOpen = Get-Process outlook*
$isOutlookOpen
if($isOutlookOpen = $true){

即使它确实给出了真或假的响应,您实际上在if语句中赋值$ true。它应该是:

if ($isOutlookOpen -eq $true)

更好的方法是将它放在try和catch块中:

try {
 get-process outlook* -errorAction stop
}
catch {
 write-host "Outlook not running..."
}