[英]New-Object fails on PowerShell 2 with Constructor not found error
I have the below script running fine on PowerShell 5 我在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 但是,它在PowerShell 2上失败,并出现以下与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?
PowerShell 2上的New-Object cmdlet有不同的语法吗?
Note: Our estate is still on PowerShell 2 hence this struggle. 注意:我们的财产仍然在PowerShell 2上,因此需要进行努力。 Thanks in advance
提前致谢
Steve 史蒂夫
In PS5 works this code: 在PS5中,此代码如下:
$NetworkChange = [System.Net.NetworkInformation.NetworkChange]::new()
PS2 says [System.Net.NetworkInformation.NetworkChange] doesn't contain a method named 'new'.
PS2说
[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.