Reputation: 538
What is the Get-Process
output value if it does not find a process specified? For example, I am checking if Outlook is closed and if it is, I back a PST file. Here is my code:
$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
}
It always goes to the else
statement.
Upvotes: 0
Views: 2561
Reputation: 200483
You use an assignment operator (=
) in the condition, so it will always evaluate to $true
. The equality comparison operator in PowerShell is -eq
.
With that said, you don't need an operator there in the first place. Get-Process
returns a list of System.Diagnostics.Process
objects (or $null
if no matching process is found). You can use the value of the variable $isOutlookOpen
like a boolean value, because PowerShell will interpret a non-empty array as a boolean value $true
and $null
as a boolean value $false
.
This should work:
$isOutlookOpen = Get-Process outlook*
if($isOutlookOpen) {
# ...
} else {
# ...
}
Upvotes: 1
Reputation: 218
In your code you are checking if something is $true when it's value would be the details of the process:
$isOutlookOpen = Get-Process outlook*
$isOutlookOpen
if($isOutlookOpen = $true){
Even if it did give a true or false response you are actually assigning a value of $true in your if statement. It should be:
if ($isOutlookOpen -eq $true)
A better way to do it would be to put it in a try and catch block:
try {
get-process outlook* -errorAction stop
}
catch {
write-host "Outlook not running..."
}
Upvotes: 0