简体   繁体   English

-pass和-passthru之间的PowerShell PSObject混淆

[英]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. 我感到困惑的-pass-passthru键。 What's the difference, and why does nothing get populated when -passthru is used for $Items1 ? 有什么区别,为什么-passthru用于$Items1时为什么没有填充?

The issue is not with -pass or -passthru . 这个问题是不是-pass-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 : about_Scopes的帮助中:

Windows PowerShell protects access to variables, aliases, functions, and Windows PowerShell drives (PSDrives) by limiting where they can be read and changed. Windows PowerShell通过限制可以读取和更改的位置来保护对变量,别名,函数和Windows PowerShell驱动器(PSDrives)的访问。

If you call the function by using dot-source then you can keep the variables available for use in the New-Object command. 如果使用点源调用函数,则可以使变量在New-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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