Get the Computer Name cross-platform using Powershell

Get the Computer Name cross-platform using Powershell

Table of Contents

A long time ago in a galaxy far, far away…

This post is over 24 months old, that is an lifetime in tech! Please be mindful of that when reading this post, young Padawan, as it could be outdated. I try to keep things up to date as much as possible. If you think something needs updating, please let me know in the comments.

Introduction

There are a few ways to get the computer name using Powershell. One way is to use the environment variable $env:COMPUTERNAME however, this doesn’t work on a Mac.

a screenshot of terminal in vscode with no value returned from the command

Other Options

Here are a few options to get the computer name using Powershell that work consistently on both Windows and Mac.

MachineName Property of the Environment Class

[Environment]::MachineName

GetHost() Method

[System.Net.Dns]::GetHostName()

Using the Output

Both of these options will return the computer name as a string allowing you to pass the value into a variable.

$name = [System.Net.Dns]::GetHostName()
Write-Host "Computer name is ${name}"
> Computer name is Justin-MacStudioM2.local
$name = [System.Net.Dns]::GetHostName()
Write-Host "Computer name is ${name}"
> Computer name is Justin-MacStudioM2.local

Comments

#mtfbwy