If I do $myobjects = Get-Service in PowerShell 5.1
- Then
$myobjects | Set-Content test.txtyields a list of fully qualified class names. - Whereas
Set-Content test.txt $myobjectsyields a list of the names of the services. Set-Content test.txt $myobjects[0]gets a fully qualified class name.Set-Content test.txt @($myobjects[0])gets a name of the service.
I know, that Set-Content uses the .ToString() method, to represent complex objects in the file to write. Some classes have meaningful .ToString() methods, while other classes simply return their fully qualified class names. Fair enough.
I further know, that the pipeline makes Set-Content getting the elements of $myobjects one by one, and every time the .ToString() method of each element is called. Whereas in the second kind, Set-Content gets the array as a whole, and so, the .ToString() method of the array is called.
But: Doesn't the .ToString() method of the array fall back onto the .ToString() methods of each single element? So, where is the difference? According to the result of both commands, the array .ToString() method seems to be more "meaningful", than the .ToString() method of each single object of type [System.ServiceProcess.ServiceController]. But how can that be, if the array-toString just queries the .ToString() methods of the objects?
I think it might have something to do with the fact, that the .ToString() method of System.ServiceProcess.ServiceController is defined as ScriptMethod System.Object ToString() whereas normally the .ToString() method is defined as Method string ToString(). But where is the exact causality and what has that to do with arrays?
One additional question: Is it normal, that Set-Content automagically yields hashtable notations, if you try to write objects of the class [PSCustomObject] to a file, even though the .ToString() method of a PSCustomObject yields an empty string?
And the written hashtable notation is even wrong, because all quotations marks for the string literals are missing in the hashtable, what leads to reimport errors, if a string contains a comma or a semicolon, for example? This behavior seems nowhere described in the official documentation of the cmdlet.