如果找不到指定的进程,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
声明。
答案 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..."
}