Link to home
Start Free TrialLog in
Avatar of asantia
asantiaFlag for United States of America

asked on

PowerShell ForEach Loop Question

Need help writing a PowerShell loop.
I have the following code already, and it works except for the first item.  I end up with a "," (comma) to start, which I don't want.
Also there cannot be a "," (comma) at the end, the last path cannot have anything after it.

    ForEach ($tmp in $DependenciesList) {
		$Dependencies += "," + $tmp.FullName
        }

Open in new window


$DependenciesList is an array of file path objects obtained by code previously in my script that populates the array from what it finds.
$Dependencies becomes a string made up of these paths separated by a comma.

I need each path to be separated by a comma (no spacing) and no comma at the very end.
For example, I need the output to look something like this:
C:\Path1\SubPath1,C:\Path2\SubPath2,C:\Path3\SubPath3, ... ,C:\PathX\SubPathX

Open in new window


How can I modify this ForEach loop?
Avatar of Adam Brown
Adam Brown
Flag of United States of America image

    
$i =0
ForEach ($tmp in $DependenciesList) {
	if ($i -eq 0){$dependencies += $tmp.fullname}
       else{$Dependencies += "," + $tmp.FullName}
       $i++
        }

Open in new window


Should cover it.
Don't use a loop at all, there is a simple expression doing the necessary:
$Dependencies = $DependenciesList -join ','

Open in new window

Avatar of asantia

ASKER

Don't use a loop at all, there is a simple expression doing the necessary:

$Dependencies = $DependenciesList -join ','

Open in new window


Qlemo, that is a great suggestion....but I need the results to be the "FullName" property of each object in the array.
Hence the use of "$tmp.FullName" in the original code.

Any way to do this using your method?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of asantia

ASKER

Both solutions would solve my problem.
I went with the "-join" solution since it is simpler/modern code.

Thanks.