Get-Printer Powershell 脚本仍然显示列,即使它们已被排除

问题描述 投票:0回答:1

具有以下行,应仅使用 get-printer 输出名称端口和驱动程序:

Get-Printer | Select-Object Name, PortName, DriverName

问题是它还抛出 Status、PSComputerName 和 RunspaceId 列(如图所示),但这是不应该的。我尝试添加排除属性来停止状态列,但不添加其他两个属性

Get-Printer | Select-Object Name, PortName, DriverName -ExcludeProperty Status, PSComputerName, RunspaceId

不知所措,这到底是怎么回事。完整脚本供参考。

# Define the path to the text file
$filePath = "C:\powershell\complist.txt"

# Check if the file exists
if (Test-Path $filePath) {
    # Read the computer names from the file
    $computerNames = Get-Content $filePath

    # Loop through each computer name
    foreach ($computer in $computerNames) {
        try {
            # Use Invoke-Command to run Get-Printer on the remote computer
            $printerInfo = Invoke-Command -ComputerName $computer -ScriptBlock {
                Get-Printer | Select-Object Name, PortName, DriverName -ExcludeProperty Status, PSComputerName, RunspaceId
            }

            if ($printerInfo) {
                # Output the printer information
                Write-Host "Printers on $computer :"
                $printerInfo | Format-Table -AutoSize
            } else {
                Write-Host "No printers found on $computer."
            }
        } catch {
            Write-Host "Error retrieving printers from '$computer': $_"
        }
    }
} else {
    Write-Host "File not found: $filePath"
}

从 get-printer 命令输出信息,仅获取 Name、PortName 和 DriverName 列

powershell printers
1个回答
0
投票

我们首先检索所有打印机数据,而不是在远程会话 (ScriptBlock) 中使用 Select-Object。 然后,在检索数据后,我们在本地计算机上应用 Select-Object 以删除远程会话添加的额外属性(PSComputerName、RunspaceId)。

# Define the path to the text file
$filePath = "C:\powershell\complist.txt"

# Check if the file exists
if (Test-Path $filePath) {
    # Read the computer names from the file
    $computerNames = Get-Content $filePath

    # Loop through each computer name
    foreach ($computer in $computerNames) {
        try {
            # Use Invoke-Command to run Get-Printer on the remote computer
            $printerInfo = Invoke-Command -ComputerName $computer -ScriptBlock {
                Get-Printer
            }

            if ($printerInfo) {
                # Output the filtered printer information locally
                Write-Host "Printers on $computer :"
                $printerInfo | Select-Object Name, PortName, DriverName | Format-Table -AutoSize
            } else {
                Write-Host "No printers found on $computer."
            }
        } catch {
            Write-Host "Error retrieving printers from '$computer': $_"
        }
    }
} else {
    Write-Host "File not found: $filePath"
}

© www.soinside.com 2019 - 2024. All rights reserved.