简体   繁体   中英

PowerShell PSObject confusion between -pass & -passthru

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

I am confused about the -pass & -passthru keys. What's the difference, and why does nothing get populated when -passthru is used for $Items1 ?

The issue is not with -pass or -passthru . The issue is that variables created inside a function are typically only available while that function is still running. From the help for about_Scopes :

Windows PowerShell protects access to variables, aliases, functions, and Windows PowerShell drives (PSDrives) by limiting where they can be read and changed.

If you call the function by using dot-source then you can keep the variables available for use in the New-Object command.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM