简体   繁体   中英

PowerShell Get-Netadapter hangs

I have a PowerShell script that is run at boot. It is designed for a small site server running on a Raspberry Pi3.

One of the things it does is reset the network settings. The following commands hang however in some situations.

$Adapter = Get-NetAdapter | ? {$_.Status -eq "up"}
$Interface = $Adapter | Get-NetIPInterface -AddressFamily "IPv4"
$Interface | Set-NetIPInterface -DHCP Enabled | Out-Null
$Interface | Set-DnsClientServerAddress -ResetServerAddresses | Out-Null

I was looking for any help as to why it might hang, a different way of coding resetting the Network Adaptor to DHCP or a way in which I can catch the hang (it does not error)

You didn't say what OS you are (were) running, but I'm going to assume Windows since you don't mention dotNet Core

This might be a CIM-vs-WMI issue, especially where you are querying hardware properties on the Pi. You might get better results using Get-WMIObject :

Get-WmiObject -Class "Win32_NetworkAdapter" -Filter "NetConnectionStatus=2"

Haven't tried this on a Raspberry Pi, but you could shift this logic into a ScriptBlock and run it as a Job (aka a child process) which you could monitor for completion and kill/retry if it takes too long.

Example code:

$ResetAdapter = {
    ... your code here ...
}

$job = Start-Job -Name ResetAdapter -ScriptBlock $ResetAdapter

do {
  Start-Sleep -Seconds 1

  $Elapsed = ((Get-Date)-$job.PSBeginTime).TotalSeconds
} while (($job.State -eq "Running") -and ($Elapsed -lt 60))

if($job.State -eq "Running"){
  Stop-Job $job
  Remove-Job $job

  # try again?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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