Home > other >  Powershell - Adding arrays
Powershell - Adding arrays

Time:10-08

I am trying to list some files in a tree to work on them

$files_AppConfig = Get-ChildItem -Path .\App.config -Recurse
$files_WatcherConfig = Get-ChildItem -Path .\WatcherServiceConfig.xml -Recurse
$files_StrControles = Get-ChildItem -Path .\Web.config -Recurse
$files = $files_AppConfig   $files_WatcherConfig   $files_StrControles


ForEach($file in $files)
{   
#Do some stuff
}

But when called by visual studio in prebuild event, i have Method invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'

CodePudding user response:

only does array addition if the first operand ($files_AppConfig in this case) is already an array. If Get-ChildItem -Path .\App.config -Recurse only returns 1 file, that won't be the case.

You can either force the first operand to be an array by wrapping it in the array subexpression operator @():

$files = @($files_AppConfig)   $files_WatcherConfig   $files_StrControles

Or, my personal preference, wrap the array subexpression operator around multiple value statements to create one big flat array:

$files = @($files_AppConfig;$files_WatcherConfig;$files_StrControles)

If you know for certain that the variables contain only scalars, you can also use the , array operator:

$files = $files_AppConfig,$files_WatcherConfig,$files_StrControles
  • Related