Pergunta

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.

Foi útil?

Solução

$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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top