Skip to content

Instantly share code, notes, and snippets.

@Froosh
Created May 30, 2017 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Froosh/e13a878bf9a4dc5d91acbb4ae052fa7f to your computer and use it in GitHub Desktop.
Save Froosh/e13a878bf9a4dc5d91acbb4ae052fa7f to your computer and use it in GitHub Desktop.
Get the computer name of the local computer
<#
.SYNOPSIS
Get the computer name of the local computer
.DESCRIPTION
Return the configured cluster or local computer name of the specified type
.PARAMETER NameFormat
One of: NetBIOS, DnsHostname, DnsDomain, DnsFullyQualified, PhysicalNetBIOS, PhysicalDnsHostname, PhysicalDnsDomain, PhysicalDnsFullyQualified
[COMPUTER_NAME_FORMAT] Definitions: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724224(v=vs.85).aspx
.EXAMPLE
Get-ComputerName -NameFormat PhysicalDnsFullyQualified
#>
function Get-ComputerName {
[CmdletBinding()]
[OutputType([string])]
Param (
[Parameter()]
[ValidateSet(
"NetBIOS",
"DnsHostname",
"DnsDomain",
"DnsFullyQualified",
"PhysicalNetBIOS",
"PhysicalDnsHostname",
"PhysicalDnsDomain",
"PhysicalDnsFullyQualified"
)]
[string]
$NameFormat = "DnsFullyQualified"
)
Begin {
$Kernel32Definition = '
public enum COMPUTER_NAME_FORMAT {
NetBIOS,
DnsHostname,
DnsDomain,
DnsFullyQualified,
PhysicalNetBIOS,
PhysicalDnsHostname,
PhysicalDnsDomain,
PhysicalDnsFullyQualified
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT nameType, System.Text.StringBuilder buffer, ref uint size);
'
if (-not ('WinAPI.Kernel32' -as [type])) {
Add-Type -Namespace "WinAPI" -Name "Kernel32" -MemberDefinition $Kernel32Definition
}
}
Process {
$ComputerNameBuffer = New-Object -TypeName System.Text.StringBuilder -ArgumentList 256
$BufferSize = $ComputerNameBuffer.Capacity
$Result = [WinAPI.Kernel32]::GetComputerNameEx($NameFormat, $ComputerNameBuffer, [ref] $BufferSize)
if ($Result -eq $False) {
# An error occured. Display the Win32 error set
throw (New-Object -TypeName ComponentModel.Win32Exception)
} else {
return $ComputerNameBuffer.ToString()
}
}
End {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment