question

21065964 avatar image
0 Votes"
21065964 asked 21065964 edited

Duplication of actions on arrays

Good day!
I am writing a script to inventory computers according to different parameters. In one of the parts of the script, I need to add information about the territory from which the CSV-file was received.
To add a property to the beginning of each array, I wrote a function:

 function Add-LocationProperty ($Array, $LocationName)
 {
     $Array | ForEach-Object {$_ | Add-Member -MemberType NoteProperty -Name Location -Value "$LocationName"}
    
     $OrderSelection = @()
     $OrderSelection += $Array[0].PSObject.Properties.Name[-1]
     $OrderSelection += $Array[0].PSObject.Properties.Name | Select-Object -SkipLast 1
     $Array = $Array | Select-Object $OrderSelection
        
     Return $Array
 }
    
 $IpConfCSV = Add-LocationProperty -Array $IpConfCSV -LocationName $LocationName
 $OSCSV = Add-LocationProperty -Array $OSCSV -LocationName $Location.Name
 $SoftCSV = Add-LocationProperty -Array $SoftCSV -LocationName $LocationName
 $CPUcsv = Add-LocationProperty -Array $CPUcsv -LocationName $LocationName
 $RAMcsv = Add-LocationProperty -Array $RAMcsv -LocationName $LocationName
 $DiskCSV = Add-LocationProperty -Array $DiskCSV -LocationName $LocationName
 $SMBcsv = Add-LocationProperty -Array $SMBcsv -LocationName $LocationName

From the code you can see that I apply the same action to each array. Is there any way to shorten the code, for example, by using a loop?
The code below didn't work:

$IpConfCSV, $OSCSV, $SoftCSV, $CPUcsv, $RAMcsv, $DiskCSV, $SMBcsv | ForEach-Object {$ = Add-LocationProperty -Array $ -LocationName $LocationName}

windows-server-powershellwindows-10-network
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MotoX80 avatar image
0 Votes"
MotoX80 answered

You should add the tag windows-server-powershell to reach more forum users. This isn't a network question.

I noticed that all of your variables end in CSV. One option would be to get a list of array names and build the Add-LocationProperty command and then execute it using Invoke-Expression.

 $ar1csv = 1,2,3
 $ar2csv = 4,5,6
 $next = 7
    
 Get-Variable | Where-Object -property Name -Like '*csv' | foreach {
     $cmd = '${0} += $next' -f $_.name                      # build the command that we want to execute
     "Executing command...."
     $cmd
     Invoke-Expression $cmd  
     $next++
 }
    
 "Array 1"
 $ar1csv
 "Array 2"
 $ar2csv

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.