Created
August 27, 2025 11:58
-
-
Save PanosGreg/656f180757db56ae326813c52f18693d to your computer and use it in GitHub Desktop.
All the different ways to get the Computer Name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ENV variable | |
$env:COMPUTERNAME | |
# Note: this is limited to 15 characters | |
# native C++ | |
hostname.exe | |
# Note: this shows the full name <<===== | |
# environment class | |
[System.Environment]::MachineName | |
# Note: this is limited to 15 characters | |
# WMI | |
(Get-CimInstance -ClassName Win32_ComputerSystem).Name | |
# Note: this is limited to 15 characters | |
(Get-CimInstance -ClassName Win32_ComputerSystem).DNSHostName | |
# Note: this shows the full name <<===== | |
# CIM | |
(Get-CIMInstance -ClassName CIM_ComputerSystem).Name | |
# Note: this is limited to 15 characters | |
# P/Invoke using KERNEL32.dll | |
$code = @' | |
using System.Runtime.InteropServices; | |
public class PInvokeKernel { | |
[DllImport("KERNEL32.dll", CharSet = CharSet.Auto, BestFitMapping = false)] | |
public extern static int GetComputerName([Out]System.Text.StringBuilder nameBuffer,ref int bufferSize); | |
} | |
'@ | |
Add-Type -TypeDefinition $code | |
[int]$Length = 0 | |
[PInvokeKernel]::GetComputerName($null,[ref]$Length) | Out-Null | |
$ComputerName = [System.Text.StringBuilder]::new($Length) | |
[PInvokeKernel]::GetComputerName($ComputerName,[ref]$Length) | Out-Null | |
$ComputerName.ToString() | |
# Note: this is limited to 15 characters | |
# P/Invoke using WSOCK32.DLL | |
$code = @' | |
using System.Runtime.InteropServices; | |
public class PInvokeSocket { | |
[DllImport("WSOCK32.DLL", SetLastError = true)] | |
public static extern long gethostname(System.Text.StringBuilder name, int nameLen); | |
} | |
'@ | |
Add-Type -TypeDefinition $code | |
$ComputerName = [System.Text.StringBuilder]::new(256) | |
[PInvokeSocket]::gethostname($ComputerName,256) | Out-Null | |
$ComputerName.ToString() | |
# Note: this ???? | |
# .NET DNS | |
[System.Net.Dns]::GetHostName() | |
# Note: this shows the full name <<===== | |
# Windows Forms | |
Add-Type -AssemblyName System.Windows.Forms | |
[System.Windows.Forms.SystemInformation]::ComputerName | |
# Note: this is limited to 15 characters | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment