Good to remember:
Write-Host
converts the object to a string representation and then outputs it to the host (console). There’s two things to keep in mind here: (1) the output bypasses any pipelines etc and is sent directly to the host; (2) the object is converted to a string representation, using thetoString()
method (which is present in all classes), and so the string representation may not necessarily be what you expect.Case in hand:
123456789101112131415161718192021222324252627282930313233343536373839# define a hash tablePS> $table = @{ a = 1; b = 2 }# use write-host to output it. notice the output.PS> write-host $tableSystem.Collections.DictionaryEntry System.Collections.DictionaryEntry# enumerate the hash table and find the type of each element in it# notice the type name - it matches what we saw abovePS> $table.GetEnumerator() | %{ $_ | Get-Member }TypeName: System.Collections.DictionaryEntryName MemberType Definition---- ---------- ----------Name AliasProperty Name = KeyEquals Method bool Equals(System.Object obj)GetHashCode Method int GetHashCode()GetType Method type GetType()ToString Method string ToString()Key Property System.Object Key {get;set;}Value Property System.Object Value {get;set;}Name AliasProperty Name = KeyEquals Method bool Equals(System.Object obj)GetHashCode Method int GetHashCode()GetType Method type GetType()ToString Method string ToString()Key Property System.Object Key {get;set;}Value Property System.Object Value {get;set;}# notice what happens if we were to convert the hash table to a string directlyPS> "$table"System.Collections.Hashtable# now run the toString() method of that table and notice it's same as abovePS> $table.ToString()System.Collections.HashtableWrite-Output
is better in the sense that (1) it only passes the output to the next step of the pipeline (or to the host if we are at the end of the pipeline) and (2) no conversion happens, the object is output and formatted as it is.To give an example with the previously created table:
123456PS> Write-Output $tableName Value---- -----a 1b 2This is same as if you were to output the object directly:
123456PS> $tableName Value---- -----a 1b 2As previously mentioned the formatting of such output depends the
ps1xml
defintions for that object.