3

I have the below script running fine on PowerShell 5

$NetworkChange = New-Object System.Net.NetworkInformation.networkchange

Register-ObjectEvent -InputObject $NetworkChange -EventName NetworkAddressChanged -SourceIdentifier "NetworkChanged" -Action {

    Write-Host "network switched"
    $LanConnected=@(Get-WmiObject win32_networkadapter -filter "netconnectionstatus = 2" | Where-Object {$_.netconnectionid -like "*Local Area Connection*"})

    If($LanConnected){
        Get-WmiObject win32_networkadapter -filter "netconnectionstatus = 2" | Where-Object {$_.netconnectionid -like "*Wireless Network Connection*"} | ForEach-Object {$_.disable()}
    }

    Else {
        Get-WmiObject win32_networkadapter | Where-Object {$_.netconnectionid -like "*Wireless Network Connection*"} | ForEach-Object {$_.enable()}
    }

}

However it fails on PowerShell 2 with the below error related to the New-Object cmdlet

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Net.NetworkInformation.networkchange.
At line:1 char:11
+ New-Object <<<<  System.Net.NetworkInformation.networkchange
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

Any idea why it fails? Is there a different syntax for the New-Object cmdlet on PowerShell 2?

Note: Our estate is still on PowerShell 2 hence this struggle. Thanks in advance

Steve

Steve
  • 337
  • 4
  • 11
  • Got it. It looks like in PowerShell 2 I have to directly pass the type to the object reference of Register-ObjectEvent. So the first 2 lines would be $NetworkChange = [System.Net.NetworkInformation.networkchange] Register-ObjectEvent -InputObject $NetworkChange -EventName NetworkAddressChanged -SourceIdentifier "NetworkChanged" -Action { – Steve Jul 12 '16 at 09:06

1 Answers1

0

In PS5 works this code:

$NetworkChange = [System.Net.NetworkInformation.NetworkChange]::new()

PS2 says [System.Net.NetworkInformation.NetworkChange] doesn't contain a method named 'new'. So we can go around it by creating a variable 'classic' way:

New-Variable -Name NetworkChange -Value ([System.Net.NetworkInformation.NetworkChange])
$NetworkChange
n01d
  • 1,047
  • 8
  • 22