0

I have a script where i define the following variable for a build script:

$globalExcludePath = @('obj', 'App_Data', 'Properties' )

I'd like to remove an item in a specific function but the remove function doesn't exist and i couldn't find any pointer on how to do it.

$customExcludePath = $globalExcludePath
$customExcludePath.Remove('App_Data') # fails

Any idea on how to do it?

2 Answers 2

1

Simple Array are size fixed. You can do this:

$customExcludePath = $globalExcludePath | ? { $_ -ne 'App_Data' }

or use [list]

[System.Collections.Generic.List[string]]$customExcludePath = $globalExcludePath
$customExcludePath.Remove('App_Data')
True
$customExcludePath
obj
Properties
Sign up to request clarification or add additional context in comments.

Comments

1

Arrays don't have a Remove method. You can put it into a generic collection that does.

One option is to explicitly load it into a specific collection type, like arralylist

$globalExcludePath = [collections.arraylist]('obj', 'App_Data', 'Properties' )
$globalExcludePath.Remove('App_Data')
$globalExcludePath

Another option is to use the scriptblock .invoke() method, which returns a collection of generic powershell objects:

$globalExcludePath = {'obj', 'App_Data', 'Properties'}.Invoke()
$globalExcludePath.Remove('App_Data') > $nul
$globalExcludePath

The remove method on that type returns True or False depending on whether the remove operation was successful, and you probably want to redirect that to $nul so it doesn't pollute the pipeline.

3 Comments

The invoke trick is neat but i find the where selection proposed by CB. nicer.
There's usually multiple ways to solve any problem in Powershell, and it's good to have choices. Using a collection and doing a .remove() is faster than the Where-Object filter, and if you were doing a lot of removes on a large collection the run time difference could be substantial and you'd want to use that instead. It just depends on your application. Pick whatever works best for the problem at hand :).
I completely understand, and in fact the "surface area" of choices in powershell is really intimidating (between aliases and alternatives, the same objective can be fulfilled in a myriad of ways). Thanks about the performance; although it is not an issue in this case since the list is to prepare file and directory copying i'll keep it in mind

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.