Get-PC/Private/Get-Hostname.ps1

51 lines
2.2 KiB
PowerShell
Raw Normal View History

function Get-Hostname ([string]$name) {
$errMsg = ''
2024-07-11 18:33:30 +00:00
if ($name.Length -eq 5) {
$res = Get-AssetConversion $name
if ($res) { return $res,'' }
try {
$cmdbData = Search-ISMBO -bo cis -filter "AssetTag eq '$name'" -RawFilter
} catch { $cmdbData = $null }
if ( $cmdbData ) { return $cmdbData.Name, '' }
2024-09-11 21:02:15 +00:00
else { $errMsg += "$name Asset Tag not in SMBIOS nor CMDB`n" }
2024-07-11 18:33:30 +00:00
}
# Regex to match IP Address brought to you by https://stackoverflow.com/a/36760050
if ($name -match "^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$") {
$res = Resolve-DnsName $name
if ($res -and $res.NameHost -and ($res.NameHost -match "([^.]*)\.int\.samhealth\.net")) {
return $Matches[0],''
} else {
2024-09-11 21:02:15 +00:00
$errMsg += "$name IP Address couldn't be resolved to hostname`n"
2024-07-11 18:33:30 +00:00
}
}
if ($name.Length -eq 7) {
$res = Get-ServiceTagConversion $name
if ($res) { return $res,'' }
try {
$cmdbData = Search-ISMBO -bo cis -filter "SerialNumber eq '$name'" -RawFilter
} catch { $cmdbData = $null }
if ( $cmdbData ) { return $cmdbData.Name, '' }
2024-09-11 21:02:15 +00:00
else { $errMsg += "$name Service Tag not found in SCCM nor CMDB`n"}
}
2024-07-11 18:33:30 +00:00
# Regex to match MAC Address brought to you by https://stackoverflow.com/a/4260512
if ($name -match "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$") {
$res = Get-SCCM_PCFromMAC $name
if ($res) { return $res,'' }
2024-09-11 21:02:15 +00:00
else { $errMsg += "$name MAC Address not found in SCCM`n"}
2024-07-11 18:33:30 +00:00
}
2024-09-11 21:02:15 +00:00
# Last resort checks
$sccmMatches = Get-SCCM_HostnameMatch $name
if ($SCCMMatches -and $SCCMMatches.Count -lt 2) {
2024-09-12 23:46:24 +00:00
return $SCCMMatches,''
2024-09-11 21:02:15 +00:00
} elseif (!$SCCMMatches) { $errMsg += "No SCCM match found`n" }
elseif ($SCCMMatches.Count -ge 2) { $errMsg += "Many SCCM matches found`n" }
$cmdbMatches = Find-ISMBO -bo cis -SearchQuery $name
if ($cmdbMatches -and $cmdbMatches.Count -lt 2) {
return $cmdbMatches.Name,''
2024-09-11 21:02:15 +00:00
} elseif (!$cmdbMatches) { $errMsg += "No CMDB match found`n" }
elseif ($cmdbMatches.Count -ge 2) { $errMsg += "Many CMDB matches found`n" }
return $name, $errMsg
2024-07-11 18:33:30 +00:00
}