New-Object fails on PowerShell 2 with Constructor not found error


hello,

i have 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 fails on powershell 2 below error related new-object cmdlet

new-object : constructor not found. cannot find appropriate constructor type system.net.networkinformation.networkchange.  @ line:1 char:11  + new-object <<<<  system.net.networkinformation.networkchange      + categoryinfo          : objectnotfound: (:) [new-object], psargumentexception      + fullyqualifiederrorid : cannotfindappropriatector,microsoft.powershell.commands.newobjectcommand

any idea why fails? there different syntax new-object cmdlet on powershell 2?

note: our estate still on powershell 2 hence struggle.

thanks in advance

steve

it looks have pass type of system.net.networkinformation.networkchange directly register-objectevent inputobject reference (instead of object new-object) works on both powershell 2 , 5.

so refined script is:

$networkchange = [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()}     }  }




Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Motherboard replacement

Cannot create Full Text Search catalog after upgrading to V12 - Database is not fully started up or it is not in an ONLINE state

Remote Desktop App - Error 0x207 or 0x607