Anybody discovered anyway to make this happen. I want to have a cmdlet that creates output from a database. There is no concrete schema, each 'row' can have different fields. In something like javascript this would be no problem, each object would have whatever properties it needs; but powershell isnt like that.
I tried a naive implementation but all I got was an enumeration of the Key, Value dictionary that expandos pretend to be.
Expanding the question.
What object should the get-datarows cmdlet push down the pipe (it accepts arbitrary queries). I dont know what object types to instantiate and push. A db query could return a row with User=dave,Age=12, then another row with User=pete, Favcol = red. Next time I run the cmdlet a query might return something totally different (Type=shoe, color=red,use=dancing). Being able to instantiate a pipe of expandos works perfectly here (except it doesn't)
My best go so far is to generate a type on the fly using reflection.emit, but this requires me to know the schema of the objects. I could do 开发者_开发知识库it by looking at the first object returned by the db query but that might not have all possible attributes (as in the first 2 user rows above). I could read all the way to the end; make the type, rewind and the push instances of the dynamically created type, but thats not very efficient
EDIT2:even more clarification
I am coding in c#
I want to be able to do
mycmdlet -query "users" | ft
or
mycmdlet -query "products;type=shoe,size>1" | make-pretty
I dont want the user to have to do a whole bunch of data shaping; that's the whole purpose of the cmdlet
I figured it out. powershell has its own expandos; psobject. This is what is actaully pushed by WriteObject. But you can make your own
So do
var obj = new PSObject();
obj.properties.add(new PSNoteProperty("foo", 42));
obj.properties.add(new PSNoteProperty("bar", "xxxx"));
WriteObject(obj);
There isn't any reason you can't have objects with different sets of properties in the pipeline. It should work fine. I do this all the time.
Can you be more specific about what isn't working? Perhaps an example of what you're trying to do?
I'm either misunderstanding your question, or I do it all the time. My code is all at work, but in psuedo-
$results = Get-ResultSet...
$columns = @{}
foreach ($column in $results.Columns)
{
columns.Add($column.Name,$column.Index)
}
foreach ($row in results)
{
$return = New-Object PSObject
foreach ($key in $columns.keys)
{
$return | Add-Member -MemberType NoteProperty -name $key $row[$columns[$key]]
}
$return
}
Your custom object will have as many properties as columns and each property will have the value you want.
精彩评论