Home > Net >  Remove the last comma from array
Remove the last comma from array

Time:10-27

Created the following code below, however, I am getting a comma on the last string in the array that I would like to remove. How do I either change the way I am adding the comma to the array or simply remove the last comma from the array?

clear
$dataOut = ''
$excludeList = 'choco*','kb*','dotnet*','netfx*','*.install*','*.portable*','vcredist*','packages*','lessmsi*'
$appsInstalled = Get-ChildItem -Exclude $excludeList -Recurse -Path "C:\ProgramData\chocolatey\lib\*.nuspec"

Foreach ($app in $appsInstalled) {
[xml]$XmlDocument = Get-Content $app.Fullname
#$appsInstalled = "$($XmlDocument.package.metadata.Title) v$($XmlDocument.package.metadata.Version)"   ", "
$appsInstalled = $XmlDocument.package.metadata.Title   " v"  $XmlDocument.package.metadata.Version   ", "
$dataOut = $dataOut   $appsInstalled
}
$dataOut

CodePudding user response:

What you are after is called trimming. There are three cases, trimming from left, right and both ends. That is, removing leading extra characters, trailing ones and from both directions.

The $dataOut is not an array but a string. One can use .Net's String class' .Trim() method. It will remove leading and trailing characters Like so,

$s = "foo,bar,zof, "
# Print trimmed string, pipes will show that space was removed too
"|{0}|" -f $s.trim(@(',', ' '))
|foo,bar,zof|
  • Related