获取网络适配器的 IP 并显示在消息框中...连接不活动时出现错误

Get IP of network adapters and display in messagebox...gets errors when connection is not active

我试图在用户单击桌面图标时弹出一个框...这将为他们提供用户名、计算机名称、连接的网络 IP 和其他附加信息...代码工作正常,但是如果网络连接未激活,Powershell window 中会显示错误。我想知道是否有人可以提供帮助?基本上,如果没有连接,则不显示任何内容……如果有连接,则显示 IP。在 运行 时不打开 powershell window 也很好......我认为这可以用 VBS 完成吗?提前谢谢你。

Add-Type -AssemblyName System.Windows.Forms
$ethAddress = (Get-NetIPConfiguration -InterfaceAlias 'Ethernet' | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress
$wiAddress = (Get-NetIPConfiguration -InterfaceAlias 'Wi-Fi' | Where-Object {$_.IPv4DefaultGateway - ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress
$vpnAddress = (Get-NetIPConfiguration -InterfaceAlias 'VPN' | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress
$celAddress = (Get-NetIPConfiguration -InterfaceAlias 'Cellular' | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress
$pcname = [System.Net.Dns]::GetHostName()
$userName = $env:UserName
$serialNum = (gwmi win32_bios).SerialNumber
$model = (gwmi win32_computersystem).model
$manufacturer = (gwmi win32_computersystem).manufacturer
$buildNumber = (gwmi win32_operatingsystem).buildnumber
$releaseID = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseID).ReleaseID

[System.Windows.Forms.MessageBox]::Show("Please provide the following information for the IT  Technician.
`nUsername:`t$userName 
Computer Name:`t$pcname  
`nWired IP:`t`t$ethAddress
Wireless IP:`t$wiAddress
VPN IP:`t`t$vpnAddress 
Cellular IP:`t$celAddress
`nManufacturer:`t$manufacturer
 Model:`t`t$model
 Service Tag:`t$serialNum
 `nW10 Release ID:`t$releaseID
 W10 Build:`t$buildNumber",'PC Information','OK','Information')

您可以 redirect (>) 错误流 (2) 为空,然后检查变量的内容。然后你可以选择根据变量内容采取行动。这将起作用,因为默认情况下变量存储成功流 (1) 结果。

$ethAddress = (Get-NetIPConfiguration -InterfaceAlias 'Ethernet' |
    Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress 2>null
$wiAddress = (Get-NetIPConfiguration -InterfaceAlias 'Wi-Fi' |
    Where-Object {$_.IPv4DefaultGateway - ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress 2>null
$vpnAddress = (Get-NetIPConfiguration -InterfaceAlias 'VPN' |
    Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress 2>null
$celAddress = (Get-NetIPConfiguration -InterfaceAlias 'Cellular' |
    Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.ipAddress 2>null
if (!($ethAddress -and $wiAddress -and $celAddress -and $vpnAddress)) { exit }