You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Get-PrinterPort查询无效及Substring调用异常技术求助

Troubleshooting Get-PrinterPort Errors & Substring Method Exceptions

Let’s break down and fix the two issues you’re running into with your PowerShell script.

First: Fixing the "Get-PrinterPort : Invalid query" Error

This error (HRESULT 0x80041017) is a WMI/CIM invalid query issue, almost always tied to the input you’re passing to the -Name parameter. Here’s how to resolve it:

  • Verify your $test variable: Make sure the port name stored in $test is exactly correct and exists on your system. Run this command to list all active printer ports and confirm your target port is present:
    Get-PrinterPort | Select-Object Name, DeviceURL
    
    If $test is empty, contains unescaped special characters (like slashes or quotes), or references a port that doesn’t exist, the cmdlet will throw this error.
  • Repair WMI repository (if needed): Corrupted WMI data can cause this issue too. Run these commands as Administrator to check and fix the repository:
    winmgmt /verifyrepository
    winmgmt /salvagerepository
    
  • Use wildcards for partial matches: If you’re unsure of the exact port name, use a wildcard to avoid typos (e.g., Get-PrinterPort -Name "*$test*"), but note this may return multiple results.

Second: Fixing the Substring Method Exception

This error happens when you try to extract a substring from a string that’s shorter than the start index or length you specified. For example, if DeviceURL is only 6 characters long and you call Substring(3,4), it’ll fail because there aren’t enough characters left.

  • Add validation before calling Substring: Always check the string length first. Here’s a safe example:
    $printerPort = Get-PrinterPort -Name $test
    if ($printerPort.DeviceURL) {
        $urlString = $printerPort.DeviceURL.ToString()
        # Adjust the numbers below to match your actual substring needs
        if ($urlString.Length -ge 10) {
            $extractedPart = $urlString.Substring(2,8)
            Write-Host "Extracted value: $extractedPart"
        } else {
            Write-Warning "DeviceURL for port $test is too short to extract the desired substring"
        }
    } else {
        Write-Warning "No DeviceURL found for port $test"
    }
    
  • Use pattern-based extraction instead: If your DeviceURL follows a consistent format (like http://printer.example.com), use regex or Split() to avoid relying on fixed indices:
    $hostName = $printerPort.DeviceURL -replace "^http://(.*?)/.*", '$1'
    

Revised Script with Error Prevention

Here’s a complete, safe version of your code that handles both issues:

$test = "YourTargetPortName" # Replace with your actual port name

# Check if the port exists
$printerPort = Get-PrinterPort -Name $test -ErrorAction SilentlyContinue
if (-not $printerPort) {
    Write-Error "Printer port '$test' does not exist on this system"
    exit 1
}

# Extract substring safely
if ($printerPort.DeviceURL) {
    $url = $printerPort.DeviceURL.ToString()
    # Customize these values to match your substring requirements
    $startIndex = 0
    $subLength = 10

    if ($url.Length -ge ($startIndex + $subLength)) {
        $result = $url.Substring($startIndex, $subLength)
        Write-Host "Extracted substring: $result"
    } else {
        Write-Warning "DeviceURL is only $($url.Length) characters long — not enough for the requested substring"
    }
} else {
    Write-Warning "The port '$test' has no DeviceURL configured"
}

内容的提问来源于stack exchange,提问作者Robby1212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:43