【发布时间】:2021-04-07 14:44:11
【问题描述】:
我有 DHCP 脚本,可以在 DHCP 服务器上的所有范围内查找匹配的主机名
- 我首先获取所有 DHCP 服务器并导入主机名 .txt
$list = Get-Content C:\script\HostNameList.txt #Defines content it pulls as list
$DHServers = Get-DhcpServerInDC #gives variable name for loop
# Gets all DHCP servers ands scopes
foreach ($Server in $DHServers){
$scopes = Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
}
- 我遍历主机名和范围列表以寻找匹配项。这里的某个地方是我的问题
$Output = foreach ($hostname in $list) { #Calls each item in list a hostname and sends to output
if (test-connection -count 1 -computername $hostname -quiet) #With 1 ping, check if hostname is online
{
foreach ($scope in $scopes){
if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$hostName*" ) #compares the hostname to lease to find which scope it is in
{ $scope.name } #return scope it found hostname in
}
[PSCustomObject]@{ #Rename varibles in data pull for output file
Asset = $hostname
Location = $scope.name #only want the name of the scope
Status = "Online"
}
}
else #statement if hostname is not online
{
Write-host "$hostname Is offline, only Last Location is known. $hostname was added to the output file." -BackgroundColor DarkRed
[PSCustomObject]@{
Asset = $hostname
Location = $scope.name #only want the name of the scope, since the name = Location
Status = "Offline"
}
}
}
$Output #show output in powershell
$Output | Export-Csv -Path C:\script\Asset_Result.csv -NoTypeInformation #outputs .csv
- 这就是它正在做的事情,输出重复 DHCP 作用域列表中的最后一项。
Asset Location Status
----- -------- ------
A847 Public Internet Online
A261 Public Internet Offline
A201 Public Internet Online
- 这是应该做的
Asset Location Status
----- -------- ------
A847 FLoor 1 Online
A261 West 1st FL Offline
A201 Floor 3 Online
我怎样才能在我的
if($scope | ... 语句在每次迭代后转到我的 PSCustomObject?
【问题讨论】:
-
您是否必须将其放入您找到的匹配项中?含义:
if($scope | Get-DhcpServerV4Lease -ComputerName $server.dnsname | Where-Object HostName -like "$hostName*" ) { $scope.name; [PSCustomObject]@{...
标签: powershell foreach scope iteration dhcp