每当变量$PrinterStatus返回任何数据时,我都试图打印这个变量,但正确的数据并不是来自于If else逻辑。
$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"
}
正如你的 $PrinterStatus
将是一个自定义打印作业对象的数组,你可以检查这个数组的长度。
$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"
我还清理了一下您的代码,修正了插入的 jobstatus
在您的自定义对象中。
打印机状态不会是一个字符串。我想你只是想对 $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"
}
我才注意到 你确实有你的 Get-Printer
命令在你的代码中的变量后面的同一行,不是吗?它不应该放在新的一行。
$PrinterStatus = Get-Printer -ComputerName "TGHYT-6578UT" | ...