powershell ip地址csv文件



我正试图将仅活动适配器的内容转储到csv文件中,以便稍后导入。

问题是$_的使用。在下面

$colNicConfigs = Get-WMIObject Win32_NetworkAdapterConfiguration | where { $_.IPEnabled -eq "TRUE" }
#loop over each adapter
foreach ($objNicConfig in $colNicConfigs) 
{ 
$objnic=Get-WMIObject Win32_NetworkAdapter | where {$_.deviceID -eq "$objNicConfig.Index" }
#$strname=$objnicconfig.description.split(":")[0]
#replace strname above when testing against actual server since no dot1q defined on my wks
$strname="MGMT:Something"
$connid=$_.NetworkConnectionID
$ipaddr=$_.IPAddress(0)
$ipsm=$_.IPSubnet(0)
$dg=$_.DefaultIPGateway
}
# create dictionary entries
$report = @()
$report += New-Object psobject -Property @{Name=$strname;ConnID=$connid;IP=$ipaddr;SM=$ipsm;DG=$dg}
$report | export-csv .nic.csv

您最初的问题是在foreach循环中使用"$underliner"。若您想引用$objNicConfig的属性,您将使用它来代替"$下划线"。所以你应该使用$connid=$objNicConfig.networkConnectionID 而不是$connid=$_.networkConnectionID

此外,IpAddress and IPSubnet不是方法,而是属性,因此删除(0)将返回写信息。如果你的NIC有多个IP,我无法证明这将如何显示,因为我的机器没有,我正在测试。

我看到的其他事情是,您需要在其中嵌套另一个foreach循环,以便同时引用WMI命名空间。。。所以类似于:


$colNicConfigs = Get-WMIObject Win32_NetworkAdapterConfiguration | where { $_.IPEnabled -eq "TRUE" }
foreach ($objNicConfig in $colNicConfigs) 
{
    foreach($objnic in (gwmi win32_networkadapter | where {$_.DeviceID -eq $objNicConfig.Index}))
    {
        $strName = "MGMT:Something"
        $objNicConfig.NetworkConnectionID
        $objNicConfig.IpAddress
        $objNic.IPSubnet
        $objNicConfig.DefaultIPGateway
    }
}

上面的代码是我用来返回计算机NIC信息的代码。

现在是"字典条目"部分。您将无法以添加psobject的方式引用foreach循环中的变量。您将只捕获在foreach循环代码中找到的最后一个。如果您想首先在foreach循环中收集信息,然后在稍后的脚本中使用它,我建议查看hash tables

最新更新