Powershell: output object [] to file
I would like to get the content of a file, filter and modify it, and write the result back to the file. I'm doing it:
PS C:\code> "test1" >> test.txt
PS C:\code> "test2" >> test.txt
PS C:\code> $testContents = Get-Content test.txt
PS C:\code> $newTestContents = $testContents | Select-Object {"abc -" + $_}
PS C:\code> $newTestContents >> output.txt
output.txt contains
"abc -" + $_
------------
abc -test1
abc -test2
What does this first line give? It's almost like foreach returns IEnumerable, but $ newTestContents.GetType () shows it's an array of objects. So what gives? How can I get the array to output usually without the weird header.
Also bonus points if you can tell me why $ newTestContents [0] .ToString () is an empty string
source to share
Also bonus points if you can tell me why $ newTestContents [0] .ToString () is an empty string
If you look at its type, it is PSCustomObject for example.
PS> $newTestContents[0].GetType().FullName
System.Management.Automation.PSCustomObject
If you look at the PSCustomObject ToString () in Reflector, you will see this:
public override string ToString()
{
return "";
}
Why he does this, I do not know. However, it's probably better to use string coercion in PowerShell like:
PS> [string]$newTestContents[0]
@{"abc -" + $_=abc -test1}
You may have been looking for this result:
PS> $newTestContents | %{$_.{"abc -" + $_}}
abc -test1
abc -test2
This demonstrates that when using Select-Object with a simple scriptblock, the contents of that scriptblock form the new property name in the PSCustomObject that is being created. In general, Nestor's approach is the way to go, but in the future, if you need to synthesize properties like this, then use a hash table like this:
PS> $newTestContents = $testContents | Select @{n='MyName';e={"abc -" + $_}}
PS> $newTestContents
MyName
------
abc -test1
abc -test2
PS> $newTestContents[0].MyName
abc -test1
source to share