如何解决在 PowerShell 中,组合这两个脚本,如果主机名 IP 与 DHCP 范围匹配,则附加 csv 输出
我有两个脚本。我想采用第一个脚本并添加一个条件,如果主机名 IP 与 ScopeIP 匹配,则将该范围的名称添加到 Results.csv
This is what I want my output to look like
我曾尝试导入两个输出 csv 文件,然后进行比较,但我不想输出多个 csv 文件。重新导入两个 csv 文件,然后比较两个 ScopeID 列,然后从单独的列中获取相应的范围名称似乎也太复杂了。
谢谢。
我的两个脚本:
$list = Get-Content C:\script\HostNames.txt #Defines content it pulls as list
$Output = foreach ($hostname in $list) #Calls each item in list a hostname and sends to output
{
if (test-connection -count 1 -computername $hostname -quiet) #checking if hostname is on line with 1 ping,If online run the following
{
$System = Get-WmiObject Win32_ComputerSystem -ComputerName $hostname | Select-Object -Property Name,Model
$BIOS = Get-WmiObject Win32_BIOS -ComputerName $hostname | Select-Object -Property SerialNumber
$User = get-childitem "C:\Users" | sort-object LastWriteTime -Descending | Select-Object -first 1
$mac = invoke-command -computername $hostname {(gwmi -class win32_networkadapterconfiguration).MacAddress | select -first 1}
$IpV = (test-connection -ComputerName $hostname -count 1 | select -expandproperty IPV4Address).IPaddresstostring
$parts = $IpV.Split(".") #converts the last octet into a zero
$parts[3] = "0"
$ip2 = [String]::Join(".",$parts)
}
else #statement if hostname is not online
{
write-host $hostname not online
}
[PSCustomObject]@{ #Rename varibles in data pull for output file
ComputerName = $hostname
Model = $System.Model
SerialNumber = $BIOS.SerialNumber
LastUser = $User
MacAddress = $mac
IpAddress = $IpV
IpScope = $ip2}
}
$Output
$Output | Export-Csv -Path C:\script\Result.csv -NoTypeinformation
$DHServers = Get-DhcpserverInDC
foreach ($Server in $DHServers)
{
$scopes = Get-DHcpserverv4Scope -ComputerName $Server.DnsName | Select-Object Name,ScopeID #only getting the Name and ScopeID
ForEach ($Address in $scopes)
{
$DHcpserver = $Server.DnsName
$Address | Export-Csv "C:\script\Results\ServerScopes.csv" -Append -NoTypeinformation
}
}
Here is what my DHCP scope names output looks like
解决方法
处理此问题的一种方法是获取第二个 CSV 数据并将其转换为哈希表。当然,我会在导出数据之前处理数据(或仍然可用),但会根据您的示例工作..
# Create a lookup table where the key is the ScopeID
$lookup = Import-Csv -Path "C:\script\Results\ServerScopes.csv" | Group-Object -Property ScopeID -AsHashTable
然后在你的第一个脚本中像这样在你的对象创建中添加一行
[PSCustomObject]@{ #Rename varibles in data pull for output file
ComputerName = $hostname
Model = $System.Model
SerialNumber = $BIOS.SerialNumber
LastUser = $User
MacAddress = $mac
IpAddress = $IpV
IpScope = $ip2
Name = $lookup[$ip2].name
}
,
import threading
...
...
...
self.start_loop_buuton = Button(text="Start Loop",command=threading.Thread(target=self.loop_func).start())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。