问题
I am trying to print the variable whenever the variable $PrinterStatus is returning any data but the correct data is not coming with If else logic.
$CurrentTime = Get-Date
$PrinterStatus=
Get-Printer -ComputerName "TGHYT-6578UT" | Foreach-Object {
$Printer = $_
$Printer | Get-Printjob |
Where-Object {$_.jobstatus -ne "Normal" -and $_.SubmittedTime -le $CurrentTime.AddHours(-1) } |
Select-Object @{name="Printer Name";expression={$_.printerName}},
@{name="Submitted Time";expression={$_.SubmittedTime}},
jobstatus, @{name="Port";expression={$Printer.PortName}},
@{name="Document Name";expression={$_.documentname}},
@{n='Difference in Hours';e={[math]::Truncate(($CurrentTime - $_.SubmittedTime).TotalHours)}} |
Sort-Object -Property jobstatus -Descending
}
if([string]::IsNullOrEmpty($PrinterStatus))
{
Write-Output "Printers NOT Present"
$output = $PrinterStatus > "C:\Output.txt" #Shoud give blank txt file
}
else {
Write-Output "printers Present"
$output = $PrinterStatus > "C:\Output.txt"
}
回答1:
As your $PrinterStatus
will be an array of your custom print job objects, you can check the length of that array.
$CurrentTime = Get-Date
$PrinterStatus = @()
$PrinterStatus = Get-Printer -ComputerName "TGHYT-6578UT" | Foreach-Object {
Get-Printjob $_ |
Where-Object {$_.jobstatus -ne "Normal" -and $_.SubmittedTime -le $CurrentTime.AddHours(-1) } |
Select-Object @{name="Printer Name";expression={$_.printerName}}, @{name="Submitted Time";expression={$_.SubmittedTime}}, @{name="jobstatus";expression={$_.jobstatus}}, @{name="Port";expression={$Printer.PortName}}, @{name="Document Name";expression={$_.documentname}}, @{n='Difference in Hours';e={[math]::Truncate(($CurrentTime - $_.SubmittedTime).TotalHours)}} |
Sort-Object -Property jobstatus -Descending
}
if ($PrinterStatus.Count -eq 0) {
Write-Output "Printers NOT Present"
} else {
Write-Output "Printers Present"
}
$PrinterStatus > "C:\Output.txt"
I also cleaned up your code a little and fixed the insertion of jobstatus
in your custom object.
回答2:
Printer status won't be a string. I think you just want to evaluate against $null
.
if($null -eq $PrinterStatus) {
Write-Output "Printers NOT Present"
# Not sure why this is necessary $output = $PrinterStatus > "C:\Output.txt" #Shoud give blank txt file
}
else {
Write-Output "Printers Present"
$output = $PrinterStatus | Out-File -FilePath "C:\Output.txt"
}
I just noticed. You do have your Get-Printer
command on the same line following the variable in your code, don't you? It shouldn't be on a new line.
$PrinterStatus = Get-Printer -ComputerName "TGHYT-6578UT" | ...
来源:https://stackoverflow.com/questions/61575752/print-output-whenever-the-variable-returns-data-using-powershell