asantia
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.
$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:
How can I modify this ForEach 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
}
$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
How can I modify this ForEach loop?
Don't use a loop at all, there is a simple expression doing the necessary:
$Dependencies = $DependenciesList -join ','
ASKER
Don't use a loop at all, there is a simple expression doing the necessary:
$Dependencies = $DependenciesList -join ','
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Both solutions would solve my problem.
I went with the "-join" solution since it is simpler/modern code.
Thanks.
I went with the "-join" solution since it is simpler/modern code.
Thanks.
Open in new window
Should cover it.