首页 > 解决方案 > 是否有一个简单的 powershell 脚本可以根据 PnPDeviceID 重命名 NetConnectionID?如果 PnPDeviceID 为“PCI\VEN”,则将 NIC 重命名为“Internet”

问题描述

我需要根据许多一致的 PnPDeviceID 重命名 NIC 卡。

到目前为止,下面的代码是我能得到的最接近的代码。但它只显示 NetConnectionID 和 PnPDeviceID,而不能用它来操作 NetConnectionID。

$interfaces = Get-WmiObject Win32_NetworkAdapter
$interfaces | foreach {
$name = $_ | Select-Object -ExpandProperty NetConnectionID
if ($name) {
$id = $_.GetRelated("Win32_PnPEntity") | Select-Object -ExpandProperty DeviceID
Write-Output "$name - $id"
}
}

我希望这可以是一个简单的脚本,可以成功地重命名网卡。

标签: powershell

解决方案


我会使用 Get-NetAdapter 和 Rename-NetAdapter,而不是使用 Get-WmiObject。

https://docs.microsoft.com/en-us/powershell/module/netadapter/get-netadapter?view=win10-ps

https://docs.microsoft.com/en-us/powershell/module/netadapter/rename-netadapter?view=win10-ps

The Get-NetAdapter cmdlet gets the basic network adapter properties. By default only visible adapters are returned.

The Rename-NetAdapter cmdlet renames a network adapter. Only the name, or interface alias can be changed.

#Create your array of adapters
$netAdapters = Get-NetAdapter 

#loop through all adapters
foreach($adapter in $netAdapters)
{

    #Set the requirements that need to be met in order to change the adapter name
    $PnPIDs2Change = "PCI\VEN_8086&DEV_1539&SUBSYS_15391849&REV_03\7085C2FFFFBA0CFC00","PCI\VEN_8086&DEV_1539&SUBSYS_15391849&REV_03\7085C2FFFFBA0CFC01","PCI\VEN_8086&DEV_1539&SUBSYS_15391849&REV_03\7085C2FFFFBA0CFC02","PCI\VEN_8086&DEV_1539&SUBSYS_15391849&REV_03\7085C2FFFFBA0CFC03","PCI\VEN_8086&DEV_1539&SUBSYS_15391849&REV_03\7085C2FFFFBA0CFC04"

    #Since you have "many consistent PnPDeviceID's" you need to loop through each of those PnPIDs and check them against the adapter in question
    foreach($ID in $PnPIDs2Change)
    {

        #If adapter meets the requirements, change the name 
        if($adapter.PnPDeviceID -eq "$ID")
        {
            #Take note of the old name and ID
            $oldName = $adapter.Name
            $adapterPnPID = $adapter.PnPDeviceID
            #Uncomment the 2 lines below in order to actually rename the adapter(set $newName to what you actually want it set to)
            #$newName = "Public - VLAN 1"
            #Rename-NetAdapter -Name $adapter.Name -NewName $newName
            Write-Output "$oldName - $adapterPnPID"
        }
    }
}

推荐阅读