Reputation: 93
The function below returns a result, but when I specify the value in an IF statement, it just return "Yes" whatever I put in the -eq value.
function GetRemoteLogonStatus ($computer = 'localhost') {
if (Test-Connection $computer -Count 2 -Quiet) {
try {
$user = $null
$user = gwmi -Class win32_computersystem -ComputerName $computer | select -ExpandProperty username -ErrorAction Stop
}
catch { "Not logged on"; return }
try {
if ((Get-Process logonui -ComputerName $computer -ErrorAction Stop) -and ($user)) {
"Workstation locked by $user"
}
}
catch { if ($user) { "$user logged on" } }
}
else { "$computer Offline" }
}
if (getremotelogonstatus -eq "blah blah blah")
{
write-host "Yes"
}
Else
{
Write-Host "no"
}
Thanks
Upvotes: 1
Views: 152
Reputation: 437628
For output from a command (such as GetRemoteLogonStatus
) to participate in an expression, the command call (including its arguments, if any) must be enclosed in (...)
, the grouping operator:
if ((GetRemoteLogonStatus) -eq "blah blah blah") {
"Yes"
}
Else {
"No"
}
Note:
If the command outputs multiple objects, the -eq
operator will act as a filter and, instead of returning $true
or $false
, will return the subarray of matching elements - see the conceptual about_Comparison_Operators help topic.
To read more about PowerShell's two fundamental parsing modes - argument (command) mode vs. expression mode - see this answer.
Enclosure in (...)
is also needed for using a command's output as an argument to another command (the example is somewhat contrived in that explicit use of Write-Output
is rarely necessary):
# Pass the output from GetRemoteLogonStatus as an argument to Write-Output
Write-Output -InputObject (GetRemoteLogonStatus)
As for what you tried:
getremotelogonstatus -eq "blah blah blah"
Because this snippet is parsed in argument mode, it invokes command getremotelogonstatus
and passes -eq
and blah blah blah
as arguments to it.
Since your command neither formally declares parameters (with a param(...)
block) nor processes the automatic $args
variable containing unbound positional arguments, these arguments are effectively ignored.
Upvotes: 3