简体   繁体   中英

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

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

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

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