作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个管道,它在 PowerShell 控制台中工作:
Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne 'Disconnected' }
但是,当我使用
System.Management.Automation
在 .NET 中尝试它时它因此异常而失败:
System.Management.Automation.CommandNotFoundException
HResult=0x80131501
Message=The term 'Where-Object { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne 'Disconnected' }' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Source=System.Management.Automation
StackTrace:
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.Runspaces.Pipeline.Invoke()
at Duplexer.PowerShell.Engine.ExecutePipeline(PSCommand Command) in D:\Dev\Projects\Duplexer\Duplexer\Code\PowerShell\Engine.vb:line 80
at Duplexer.Main.GetSettings() in D:\Dev\Projects\Duplexer\Duplexer\Main.vb:line 84
at Duplexer.Tests.PowerShellTests.Can_Get_NIC_Settings() in D:\Dev\Projects\Duplexer\Duplexer.Tests\PowerShellTests.vb:line 6
这是我的 .NET 代码:
Public Sub GetSettings()
Dim oPipeline As PSCommand
Dim oResult As Collection(Of PSObject)
oPipeline = New PSCommand
oPipeline.
AddCommand(PowerShell.Commands.GetNetIPConfiguration).
AddCommand(PowerShell.Commands.WhereObject & " { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne 'Disconnected' }")
Using oPowerShell As New PowerShell.Engine
oPowerShell.ImportModules(PowerShell.Modules.NetAdapter, PowerShell.Modules.NetTCPIP)
oResult = oPowerShell.ExecutePipeline(oPipeline)
End Using
End Sub
如何配置此 PowerShell 命令以在 .NET 自动化中使用?
最佳答案
您需要单独提供参数参数(Where-Object
后面的脚本块)。改变这一行:
AddCommand(PowerShell.Commands.WhereObject & " { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne 'Disconnected' }")
到:
AddCommand(PowerShell.Commands.WhereObject).
AddArgument(ScriptBlock.Create("$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne 'Disconnected'"))
关于.net - 如何在 .NET PowerShell 自动化中使用 Where-Object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68720129/
我是一名优秀的程序员,十分优秀!