共有プリンターが存在する場合は削除する PowerShell スクリプト

共有プリンターが存在する場合は削除する PowerShell スクリプト

質問して申し訳ありませんが、これを解決するには助けが必要です。\server\printer のように、多くのコンピューターにプリンターがインストールされています。PowerShell スクリプトを使用してそれらを削除しようと思ったのですが、うまくいきません。次のようなことを考えていました。

$printers=Get-Printer | where { $_.Type -eq 'Connection'} | select name /* this part show me only \\server\printers */
$printers | ForEach-Object {
    if ($printers) {
            Remove-Printer -Name $printers -Confirm:$false
    }
}

皆様、事前に感謝します。

答え1

これは、Remove-Printer コマンドレットにプリンターのリスト全体を提供しているためです。一度に 1 つのプリンターを指定する必要があります。

[...]
Remove-Printer -Name $printers -Confirm:$false
# Error here------------/\
[...]

foreach ループ内にいる場合は、$PSItemまたは短縮エイリアスを使用して現在のプリンターを取得できます$_$PSItem(および$_) は「ForEach ループ内の現在のオブジェクト」を意味します。

これは動作するはずです:

$printers=Get-Printer | where { $_.Type -eq 'Connection'} | select name /* this part show me only \\server\printers */
$printers | ForEach-Object {
    if ($_) {
            Remove-Printer -Name $_.Name -Confirm:$false
    }
}

関連情報