简体   繁体   English

将每一行 PowerShell 输出存储为相同的变量

[英]Store Each Line of PowerShell Output as same variable

So, I'm trying to remotely remove some manually added printer from a separate machine.所以,我试图从一台单独的机器上远程删除一些手动添加的打印机。 Problem is, I don't want to remove all of the printers, only ones that have "HJK" or "LSG" anywhere in the name.问题是,我不想删除所有打印机,只删除名称中有“HJK”“LSG”的打印机。

So, to get the list of names, I do:因此,要获取名称列表,我会这样做:

Invoke-Command AaronsComputer -ScriptBlock {get-printer | select name -expandproperty name}

and to delete the printer, I would do:要删除打印机,我会这样做:

Invoke-Command AaronsComputer -ScriptBlock {Remove-Printer -Name "Full Printer Name Here"}

I know I can export the results of get-printer as a CSV to work with it better but I'd rather not do that and have it all happen in Powershell.我知道我可以将 get-printer 的结果导出为 CSV 以更好地使用它,但我宁愿不这样做,而是让这一切发生在 Powershell 中。

I thought something along these lines would work but I don't think PowerShell intelligently sees each line as a variable.我认为沿着这些路线的东西会起作用,但我不认为 PowerShell 智能地将每一行视为一个变量。

$PrinterResults = Invoke-Command $Computer -ScriptBlock {get-printer | select name -expandproperty name}

foreach $PrinterResults

if ($PrinterResults -contains "HJK") { 
  Invoke-Command $Computer -ScriptBlock {Remove-Printer -Name "$PrinterResults"}
}

if ($PrinterResults -contains "LSG") { 
  Invoke-Command $Computer -ScriptBlock {Remove-Printer -Name "$PrinterResults"}
}

The end goal is that I can delete all printers that match the criteria in one go.最终目标是我可以一次性删除所有符合条件的打印机。

Managed to get this done in the end with the below:最终通过以下方式完成了这项工作:

Invoke-Command $Computer -ScriptBlock {
$Printers = get-printer | Where-Object {($_.name -like '*HJK*') -or ($_.name -like '*LSG*')} | Select Name -expandproperty name
foreach ($PrinterName in $Printers)
{
    printui.exe /dl /n $PrinterName
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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