CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Automatic Variables – $HOST, $HOME, $PWD and $ERROR

PowerShell provides another set of Automatic variables to allow us to get the information about the home directory, present working directory, host details, and error details. In this article, we will discuss these variables.

The $HOST Automatic Variable

This variable contains the current host application object for PowerShell. Below displays the details of the host application; like UI, host application Version, etc. We can also change the properties of the host application, using this variable.

PS C:\> $HOST

Name : ConsoleHost
Version : 4.0
InstanceId : 2a8d8964-2096-4e25-a68f-0a246a0d451e
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace

Here it displays the properties of the host application. Let’s deeply look into UI property to use some of its properties. To display its properties it; we can use Get-Member cmdlet, like below.

PS C:\> $HOST.UI | Get-Member

   TypeName: System.Management.Automation.Internal.Host.InternalHostUserInterface

Name                   MemberType Definition
----                   ---------- ----------
Equals                 Method     bool Equals(System.Object obj)
GetHashCode            Method     int GetHashCode()
GetType                Method     type GetType()
Prompt                 Method     System.Collections.Generic.Dictionary[string,psobject] Prompt(string caption, string message, System.Collections.ObjectModel.Collection[System.Management.Automati...
PromptForChoice        Method     int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] choices, int de...
PromptForCredential    Method     pscredential PromptForCredential(string caption, string message, string userName, string targetName), pscredential PromptForCredential(string caption, string mess...
ReadLine               Method     string ReadLine()
ReadLineAsSecureString Method     securestring ReadLineAsSecureString()
ToString               Method     string ToString()
Write                  Method     void Write(string value), void Write(System.ConsoleColor foregroundColor, System.ConsoleColor backgroundColor, string value)
WriteDebugLine         Method     void WriteDebugLine(string message)
WriteErrorLine         Method     void WriteErrorLine(string value)
WriteLine              Method     void WriteLine(), void WriteLine(string value), void WriteLine(System.ConsoleColor foregroundColor, System.ConsoleColor backgroundColor, string value)
WriteProgress          Method     void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
WriteVerboseLine       Method     void WriteVerboseLine(string message)
WriteWarningLine       Method     void WriteWarningLine(string message)
RawUI                  Property   System.Management.Automation.Host.PSHostRawUserInterface RawUI {get;}

We can use these properties of UI, directly. Let’s use WriteLine method to display some text on the screen.

PS C:\> $HOST.UI.WriteLine("Hello, World!")
Hello, World!

Let’s look at another property; RawUI. This has the property to change the display color.

PS C:\PowerShell> $HOST.UI.RawUI

ForegroundColor       : Gray
BackgroundColor       : Black
CursorPosition        : 0,52
WindowPosition        : 0,0
CursorSize            : 25
BufferSize            : 200,80
WindowSize            : 197,66
MaxWindowSize         : 200,69
MaxPhysicalWindowSize : 200,69
KeyAvailable          : False
WindowTitle           : Administrator: Windows PowerShell

What we do now? Change the Background color and Window title and observe the UI appearance.

PS C:\> $HOST.UI.RawUI.BackgroundColor = "Blue"
PS C:\> $HOST.UI.RawUI.WindowTitle = "CodeSteps - Host Variable demonstration"
PS C:\> $HOST.UI.RawUI

ForegroundColor       : Gray
BackgroundColor       : Blue
CursorPosition        : 0,3
WindowPosition        : 0,0
CursorSize            : 25
BufferSize            : 200,80
WindowSize            : 82,31
MaxWindowSize         : 200,69
MaxPhysicalWindowSize : 200,69
KeyAvailable          : False
WindowTitle           : CodeSteps - Host Variable demonstration

Here is the screenshot with the applied changes:

PowerShell - Host variable demo
PowerShell – Host variable demo

The $HOME Automatic Variable

This variable contains the complete path of the User’s home directory.

PS C:\> $HOME
C:\Users\david

The $PWD Automatic Variable

This variable contains the current working directory information.

PS C:\PowerShell> $PWD

Path
----
C:\PowerShell

The $ERROR Automatic Variable

This variable contains error details. Each generated error will be stored in this variable; that means, it holds an array of error objects. The most recent error will be displayed first.

PS C:\PowerShell> ll
ll : The term 'll' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ ll
+ ~~
    + CategoryInfo          : ObjectNotFound: (ll:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\PowerShell> Get-Number
Get-Number : The term 'Get-Number' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:1 char:1
+ Get-Number
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-Number:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\PowerShell> $ERROR
Get-Number : The term 'Get-Number' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:1 char:1
+ Get-Number
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-Number:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

ll : The term 'll' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ ll
+ ~~
    + CategoryInfo          : ObjectNotFound: (ll:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\PowerShell>

We can also access specific error object details using its entry index. For example, to display the most recent error, we can use this variable using index value as $ERROR[0].

Note that, these variables are specific to the session. Once you closed the PowerShell session; the values will be reset to its default values.

We will discuss more topics as we go.

[..] David

PowerShell – Automatic Variables – $HOST, $HOME, $PWD and $ERROR

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top