Powershell超时两秒后

时间:2012-09-07 09:49:21

标签: powershell timeout uuid

我是PowerShell的新手。我在www.powershell.com上阅读了一些内容。现在我需要你的帮助才能解决问题。我想从网络中的客户端读取UUID。因此,我创建了一个文件“pcs.txt”,其中存储了所有PC。

$pc = Get-Content pcs.txt #Read content of file
$cred = Get-Credential “domain\user” 

for ($i=0; $i -lt $pc.length; $i++)     {

    $Result=test-connection -ComputerName $pc[$i] -Count 1 -Quiet
    If ($Result -eq 'True')
    { 
        $uuid = (Get-WmiObject Win32_ComputerSystemProduct -ComputerName $pc[$i] -Credential $cred).UUID 
        $Ausgabe=$pc[$i] + ';'+$uuid
        $Ausgabe  


    } 
    else
    {

        $Ausgabe=$pc[$i] + '; UUID nicht erhalten'
        $Ausgabe 
    }

}

首先我测试ping是否有效。当ping工作时,我尝试获取uuid。 即使ping工作,有时我也不会得到uuid。所以我想编写一个超时,即 - >如果你在2秒后没有使用uuid,请转到下一台电脑。

你能帮我吗?

2 个答案:

答案 0 :(得分:0)

唉,Get-WmiObject命令行开关没有超时参数。 MS Connect中有一项功能请求,但是从2011年开始,仍处于打开状态。

A workaround,我未使用System.Management进行测试。我会在这里复制并粘贴它,以防链接失效。 (我讨厌那些只包含可能存在或不存在的资源链接的答案......)

Function Get-WmiCustom([string]$computername,[string]$namespace,[string]$class,[int]$timeout=15){
$ConnectionOptions = new-object System.Management.ConnectionOptions
$EnumerationOptions = new-object System.Management.EnumerationOptions 

$timeoutseconds = new-timespan -seconds $timeout
$EnumerationOptions.set_timeout($timeoutseconds) 

$assembledpath = "\\" + $computername + "\" + $namespace
#write-host $assembledpath -foregroundcolor yellow 

$Scope = new-object System.Management.ManagementScope $assembledpath, $ConnectionOptions
$Scope.Connect() 

$querystring = "SELECT * FROM " + $class
#write-host $querystring 

$query = new-object System.Management.ObjectQuery $querystring
$searcher = new-object System.Management.ManagementObjectSearcher
$searcher.set_options($EnumerationOptions)
$searcher.Query = $querystring
$searcher.Scope = $Scope 

trap { $_ } $result = $searcher.get() 

return $result
}

答案 1 :(得分:0)

我找到了一个很好的解决方法!

http://theolddogscriptingblog.wordpress.com/2012/05/11/wmi-hangs-and-how-to-avoid-them/

这是我的工作代码:

$pc = Get-Content pcs.txt #FILE FROM THE HARDDISK
$cred = Get-Credential “DOMAIN\USER” #

for ($i=0; $i -lt $pc.length; $i++) 
{
$Result=test-connection -ComputerName $pc[$i] -Count 1 -Quiet 
If ($Result -eq 'True')
{ 
    $WMIJob = Get-WmiObject Win32_ComputerSystemProduct -ComputerName $pc[$i] -Credential $cred -AsJob     
    $Timeout=Wait-Job -ID $WMIJob.ID -Timeout 1 # the Job times out after 1 seconds.   
    $uuid = Receive-Job $WMIJob.ID

    if ($uuid -ne $null)
    {
        $Wert =$uuid.UUID 
        $Ausgabe=$pc[$i] + ';'+$Wert
        $Ausgabe  
    }

    else
    {
    <#$b = $error | select Exception       
    $E = $b -split (:)     
    $x = $E[1]   
    $Error.Clear()      #>
    $Ausgabe=$pc[$i] + '; got no uuid'
    $Ausgabe 
    }



} 
else
{
    $Ausgabe='PC not reached through ping.'
    $Ausgabe 
}


}

我希望我可以帮助那个人

相关问题