1
function getinfo {
    $strComputer = "localhost"
    $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"
    $Items1 = $colItems | Select DHCPServer, Caption, DNSHostName, IPAddress
    $Items2 = $colItems | Select ServiceName, MacAddress, IPSubnet, InterfaceIndex
}
$objects = (New-Object PSObject |
               add-member -pass NoteProperty "DHCP Server" $Items1.DHCPServer |
               add-member -pass NoteProperty "IP Address" $Items1.IPAddress | 
               add-member -passthru NoteProperty "Mac Address" $Items2.MacAddress | 
               add-member -passthru NoteProperty "IP Subnet" $Items2.IPSubnet
                )
$objects | ConvertTo-Json

我对-pass&-passthru键感到困惑。-passthru有什么区别,为什么在用于时没有填充任何内容$Items1

4

1 回答 1

1

问题不在于-passor -passthru。问题是在函数内部创建的变量通常仅在该函数仍在运行时才可用。从about_Scopes的帮助中:

Windows PowerShell 通过限制可以读取和更改的位置来保护对变量、别名、函数和 Windows PowerShell 驱动器 (PSDrive) 的访问。

如果您使用 dot-sourceNew-Object调用该函数,那么您可以保持变量在命令中可用。

function getinfo {
    $strComputer = "localhost"
    $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"
    $Items1 = $colItems | Select DHCPServer, Caption, DNSHostName, IPAddress
    $Items2 = $colItems | Select ServiceName, MacAddress, IPSubnet, InterfaceIndex
}
. getinfo
$objects = (New-Object PSObject |
               add-member -pass NoteProperty "DHCP Server" $Items1.DHCPServer |
               add-member -pass NoteProperty "IP Address" $Items1.IPAddress | 
               add-member -passthru NoteProperty "Mac Address" $Items2.MacAddress | 
               add-member -passthru NoteProperty "IP Subnet" $Items2.IPSubnet
                )
$objects | ConvertTo-Json
于 2015-12-23T21:49:25.517 回答