[英]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.