0

I am using powershell code to first connect on a database and from the SELECT I am making, this output is then output :

NAME: %SERVERNAME1
NAME: %SERVERNAME2

Now I want to make a "foreach" loop where it will make a "get-childitem" on every %SERVERNAME to find every EXE files and output to out-gridview.

My foreach look like this but obviously it doesn't work :

$Connection.open()
Write-host "Database Connection $databasename = SUCCESSFULL : Searching role $Role in $palier ..." -foregroundcolor green -backgroundcolor black
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($Dataset)
$Connection.Close()
$Result = $Dataset.Tables[0]
$Result


Foreach ($name in $Result) 
{

$name = Get-ChildItem "\\$_\c$\" -recurse -filter *.exe

}

How this foreach could be done ?

P.S. : Didn't want to add to much info since the database connection is working, just want to understand where I am failing on the foreach side.

1 Answer 1

1

$Result is a collection of data rows, and foreach can't use $_ (that's only for pipelined objects). You need to loop through the results and grab the Name field from each row.

In your loop, you're overwriting $name on each iteration, so you'll only output the results of the last Get-ChildItem. You need to collect those results for output.

$ExeList = @();
Foreach ($Record in $Result) {
    $ExeList += Get-ChildItem -path \\$($Record.name)\c$\ -recurse -filter *.exe
}
$ExeList|out-gridview;
Sign up to request clarification or add additional context in comments.

2 Comments

It works like a charm ! Could you explain to me theses two parameters you've used : "@()" and "\\$($Record.name) " ? Why uses the dollar sign before the record name ?
@() creates an empty array to stuff the results of GCI into. $($Results.name) is how you get variable expansion for properties within a quoted string (yes, I realize I didn't quote it here - force of habit).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.