简体   繁体   中英

Powershell Get-PrinterPort Invalid Query

Having trouble with this function something with the Get-PrinterPort erroring out.

Error Message(s) below

Get-PrinterPort : Invalid query 
At line:10 char:16
+     $printer = Get-PrinterPort -Name $test | ft DeviceURL | out-strin ...
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_PrinterPort:ROOT/StandardCimv2/MSFT_PrinterPort) [Get-PrinterPort], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041017,Get-PrinterPort`

Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.
Parameter name: length"
At line:16 char:5
+     $printhostname = $printer.Substring(0, $pos)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException`

This is the code, I've narrowed it down to a suspected issue with the Get-PrinterPort -Name part, the guides say it takes a string[] but doesn't like the output from out-string. Any tips or blinding errors?

function Get-HostNameFromPrinterName {
$servername = Read-Host -Prompt "Enter the name of the Printer"

$WSD = (Get-WmiObject -class Win32_Printer | where Name -match $servername | select PortName) | out-string

$pos = $WSD.IndexOf("W")
$WSD = $WSD.Substring($pos)
$pos = $WSD.IndexOf("`n")
$WSD = $WSD.Substring(0, $pos)

$printer = Get-PrinterPort -Name $WSD | ft DeviceURL | out-string
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printer = $printer.Substring($pos+1)
$pos = $printer.IndexOf("/")
$printhostname = $printer.Substring(0, $pos)
write-host $printhostname
}

Also please forgive any formatting errors :p

EDIT: After testing the variable type returns system.string

This program does the same thing however it works fine.

function Get-HostNameFromWSD {
  $WSD = Read-Host -Prompt 'Input WSD'

  $printer = Get-PrinterPort -name $WSD | ft DeviceURL | out-string
  $pos = $printer.IndexOf("/")
  $printer = $printer.Substring($pos+1)
  $pos = $printer.IndexOf("/")
  $printer = $printer.Substring($pos+1)
  $pos = $printer.IndexOf("/")
  $printhostname = $printer.Substring(0, $pos)
  write-host $printhostname
}

This variable also returns system.string. Not sure where the error lies.

Asked the same question over on Technet, this answer worked for me. Get-WmiObject Win32_Printer |?{$_.portname -match '^WSD'}|select PortName,SystemName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM