我有一个我写的脚本的问题,希望得到一些帮助。请注意,我是powershell的新手。
我写了一个脚本,它使用了一个包含域中远程计算机的txt文件,我看起来在某种程度上是在工作,但在机器脱机的情况下,我会得到错误,然后循环脚本。
$machines
$pcname
Name = 'Machine'
Expression = { $_.PsComputerName }
}
ForEach ($System in $Machines)
{
#Pings machine's found in text file
if (!(test-Connection -ComputerName $System -BufferSize 16 -Count 1 -ea 0 -Quiet))
{
Write-Output "$System Offline"
}
Else
{
#Providing the machine is reachable
#Checks installed programs for products that contain Kaspersky in the name
gwmi win32_product -Filter {Name like "%Kaspersky%"} -ComputerName $Machines | Select-Object -Property $pcname,Name,Version
}
}目前,它运行并输出如下所示:
Machine Name Version
UKTEST01 Kaspersky Security Center Network Agent 10.1.249
UKTEST02 Kaspersky Endpoint Security 10 for Windows 10.2.1.23但是,如果机器不可访问,则会给出以下错误:
gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\Scripts\Powershell\Kaspersky Endpoint Security 10\Script\New folder\Kaspersky Checker working v2.ps1:15 char:9
+ gwmi win32_product -Filter {Name like "%Kaspersky%"} -ComputerName $Mach ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand然后移动到列表中的下一台机器,然后再次从头开始重复。
我想让它简单地显示为:
UKTEST03 Offline并在txt文件中的最后一台机器完成后停止。
任何帮助或建议都将不胜感激。
发布于 2015-03-30 23:12:05
这是使用Try/Catch/Finally块的最佳时机。流程是这样的:尝试这里的代码块,如果遇到错误,隐藏消息并执行Catch块中的操作。
我对您的代码做了一些修改,因此只需复制整个代码块并将其放入其中,即可替换原始代码中的Else {scriptblock}。
Else
{
#Providing the machine is reachable
#Checks installed programs for products that contain Kaspersky in the name
Try {Get-WMIObject -Class win32_product -Filter {Name like "%Kaspersky%"} `
-ComputerName $Machines -ErrorAction STOP |
Select-Object -Property $pcname,Name,Version }
Catch {#If an error, do this instead
Write-Output "$system Offline }
}
}Your completed
我已经接受了您所要求的更改,使您的脚本不会像您希望的那样在$machines中的每台机器上运行,而不是在$system中运行。
ForEach ($System in $Machines){
#Pings machine's found in text file
if (!(test-Connection -ComputerName $System -BufferSize 16 -Count 1 -ea 0 -Quiet))
{
Write-Output "$System Offline"
}
Else
{
#Providing the machine is reachable
#Checks installed programs for products that contain Kaspersky in the name
Try {Get-WMIObject -Class win32_product -Filter {Name like "%Kaspersky%"} `
-ComputerName $System -ErrorAction STOP |
Select-Object -Property $pcname,Name,Version }
Catch {#If an error, do this instead
Write-Output "$system Offline "}
#EndofElse
}
#EndofForEach
}发布于 2015-03-31 14:13:51
你可以试试这个:
$machines=... # your machines' names
foreach ($machine in $machines)
{
trap{"$machine`: not reachable or not running WsMan";continue}
if(test-wsman -ComputerName $machine -ea stop){
gcim -Class CIM_Product -Filter 'Name like "%Kaspersky%"' |
select pscomputername,name,version
}
}我之所以使用gcim,是因为gwmi已被弃用。
更正:正确的名称是Kaspersky;我更正了它。
https://stackoverflow.com/questions/29348786
复制相似问题