Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach Property in Get-Member

I have the following snippet of code in my powershell script

    $sqlHDR = "SELECT * FROM OPENROWSET ('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=" + $dir + $m + ".xls;HDR=NO','SELECT * FROM [" + $y + "`$B1:Z1]')"
    $doHDR = invoke-sqlcmd -query $sqlHDR -ServerInstance $sqlserver -Database $db

    $doHDR | get-member -membertype properties

This is part of a loop that cycles through hundreds of Excel spreadsheets. The result is a dynamically changing set of columns from F1 through to F*n* (n being the unknown final column number) which have only one row, with a single value in each row.

I wondered if I could use get-member to somehow loop through the columns in the dataset to gain access to the values in field? Or am I going about this completely backwards, is there a better way to loop through the values in a single datarow?

Alternatively is there a way to loop through the property names themselves?

Many thanks!

like image 637
Ryan Gillies Avatar asked Nov 14 '13 01:11

Ryan Gillies


People also ask

What does get-Member cmdlet do?

The Get-Member cmdlet gets the members, the properties and methods, of objects. To specify the object, use the InputObject parameter or pipe an object to Get-Member . To get information about static members, the members of the class, not of the instance, use the Static parameter.

What is ForEach-object in PowerShell?

The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified using the InputObject parameter. Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-Object command. Script block.

Is an alias for ForEach-object?

The ForEach-Object (foreach alias) cmdlet is used in the pipeline. It is used to iterate through a collection of items, while being respectful of the PowerShell pipeline-which gets input, processes it, and passes it down the pipeline as objects are done processing.

How do you break a ForEach-object?

There is no way to stop or break a forEach() loop other than by throwing an exception.


2 Answers

Does this help any?

$doHDR.psobject.properties | 
 where {$_.name -like 'something*'} |
 foreach {set-variable -Name $_.name -Value $_.value}

Update with example foreach

like image 158
mjolinor Avatar answered Sep 28 '22 00:09

mjolinor


Wouldn't it be easier to just use Format-List?

$doHDR | FormatList F*
like image 44
Keith Hill Avatar answered Sep 27 '22 23:09

Keith Hill