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
时没有填充任何内容?
答案 0 :(得分:1)
问题不在于-pass
或-passthru
。问题是函数内部创建的变量通常仅在该函数仍在运行时才可用。来自about_Scopes的帮助:
Windows PowerShell保护对变量,别名,函数的访问, 和Windows PowerShell驱动器(PSDrives)通过限制它们的位置 阅读和更改。
如果您通过using dot-source调用该函数,则可以保留变量可用于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