0

将打印机端口作为 WMI 对象删除时出现问题

这个

param(
[Parameter(Mandatory=$true)]
[string] $printerName
)

$printer=gwmi win32_Printer -filter "name='$printerName'"
$printer.Delete()
Write-Host $printer.portname


$port=gwmi win32_tcpipprinterport -filter "name='$($printer.portname)'" -EnableAllPrivileges
Write-host $port

$port.Delete() 

失败并出现以下情况:

Exception calling "Delete" with "0" argument(s): "Generic failure "
At line:14 char:1
+ $port.Delete()
+ ~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

但是,当在 10 秒之间添加睡眠时$printer.Delete$port=gwmi...它就可以工作了!

关于它可能是什么以及除了睡眠之外如何解决它的任何建议?

4

2 回答 2

0

您可以利用循环检查打印机,直到它停止存在,而不是在那里有硬编码的时间量:

Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [String]
    $PrinterName
)
$local:ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue

$Printer = Get-WmiObject -Class Win32_Printer -Filter "Name='$PrinterName'"
$Port = Get-WmiObject -Class Win32_TcpIpPrinterPort -Filter "Name='$($Printer.PortName)'" -EnableAllPrivileges

Write-Host $Printer.PortName
Write-Host $Port

If (-not $Printer) { Return }
$Printer.Delete()
Do
{
    Start-Sleep -Seconds 2
} While (Get-WmiObject -Class Win32_Printer -Filter "Name='$PrinterName'")

If (-not $Port) { Return }
$Port.Delete()
Do
{
    Start-Sleep -Seconds 2
} While (Get-WmiObject -Class Win32_TcpIpPrinterPort -Filter "Name='$($Printer.PortName)'" -EnableAllPrivileges)
于 2018-02-16T16:53:59.240 回答
0

这就是我最终修复它的方式:

param(
    [Parameter(Mandatory=$true)]
    [string] $printerName
    )

$printer=gwmi win32_Printer -filter "name='$printerName'"
$printer.Delete()
Write-Host $printer.portname

$port=gwmi win32_tcpipprinterport -filter "name='$($printer.portname)'" -EnableAllPrivileges



if(!$port){
    throw "Printer port could not be found, this printer may have not been 
removed correctly"
}

$unableToDeletePort = $true
$counter = 10

while($unableToDeletePort -and $counter -ge 0)
{
    try{
        $port.Delete()
        $unableToDeletePort = $false
        write-host "deleted port"
       }
     catch{
        $unableToDeletePort = $true
        write-host "didn't delete port"
}
    Start-Sleep -Seconds 2
    $counter-=1

    $port=gwmi win32_tcpipprinterport -filter "name='$($printer.portname)'" -EnableAllPrivileges
}



if($unableToDeletePort){
    Restart-Service "Spooler"

    $counter=5

    while($unableToDeletePort -and $counter -ge 0)
    {
        try{
            $port.Delete()
            $unableToDeletePort = $false
            write-host "deleted port"
            }
    catch{
        $unableToDeletePort = $true
        write-host "didn't delete port"
         }
    Start-Sleep -Seconds 2
    $counter-=1

    $port=gwmi win32_tcpipprinterport -filter "name='$($printer.portname)'" -EnableAllPrivileges
    }

    if($unableToDeletePort){
        throw "Unable to delete port"
    }
}
于 2018-02-21T11:03:03.617 回答