我有一个脚本,假设要查找主机名所在的范围。
我的 PSCustomObjectLocation = $scope.name
正在获取整个范围数组而不是匹配项,如下所示。
Asset : U1087
Location : {bdg-213, Vo213, 0V-Gen-DH, 0-v734...}
Status : Online
Asset : U1281
Location : {bdg-213, Vo213, 0V-Gen-DH, 0-v734...}
Status : Offline
Asset : U1061
Location : {bdg-13, Vo213, 0V-Gen-DH, 0-v734...}
Status : Online
我导入一个名为 .txt 的主机名文件$list
。然后循环$list
并 $scopes
寻找匹配项。
$list = Get-Content C:\script\HostNameList.txt #Defines content it pulls as list
$DHServers = Get-DhcpServerInDC #gives variable name for loop
$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
[array] $scope =
foreach ($Server in $DHServers){
Get-DHCPServerv4Scope -ComputerName $Server.dnsname #get all scopes
$i = 0;
foreach ($scope in $scopes){
if($scope | Get-DhcpServerV4Lease -ComputerName $DHServers[$i++] | Where-Object HostName -like "$hostName*" ) #compares the hostname to lease to find which scope it is in`
{ $scopename} #return name of the scope it found hostname in. Name property is location in DHCP
}
}
[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
{
}
}
$Output #show output in powershell
$Output | Export-Csv -Path C:\script\Asset_Result.csv -NoTypeInformation #outputs .csv