Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are PowerShell Arrays just .NET Arrays?

I am creating an array of string objects in PowerShell which needs to be passed into an Xceed zip library method which expects a string[], but I get an error everytime. It makes me wonder if the PowerShell array is something other than a .NET array. Here is some code:

$string_list = @()
foreach($f in $file_list)
{
    $string_list += $f.FullName
}
[Xceed.Zip.QuickZip]::Zip("C:\new.zip", $true, $false, $false, $string_list)

The error I get says "An error occurred while adding files to the zip file." If I hard code in values like this it works:

[Xceed.Zip.QuickZip]::Zip("C:\new.zip", $true, $false, $false, "test.txt", "test2.txt", "test3.txt")

Can someone help me figure this out? I can't understand what the difference would be...

EDIT: I have tested and confirmed that my $string_list array is composed of System.String objects

like image 408
JimDaniel Avatar asked Aug 26 '09 22:08

JimDaniel


People also ask

What are arrays in PowerShell?

An array is a data structure that is designed to store a collection of items. The items can be the same type or different types. Beginning in Windows PowerShell 3.0, a collection of zero or one object has some properties of arrays.

Does PowerShell have arrays?

PowerShell ArraysArrays in PowerShell can contain one or more items. An item can be a string, an integer, an object, or even another array, and one array can contain any combination of these items. Each of these items has an index, which always starts (sometimes confusingly) at 0.

How do I declare an array in PowerShell?

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

Do PowerShell arrays start at 0 or 1?

A common programming error is created because arrays start at index 0. Off-by-one errors can be introduced in two ways.


1 Answers

When you specify:

$string_list = @()

You have given PowerShell no type info so it creates an array of System.Object which is an array that can hold any object:

PS> ,$string_list | Get-Member

   TypeName: System.Object[]

Try specifying a specific array type (string array) like so:

PS> [string[]]$string_list = @()
PS> ,$string_list | Get-Member


   TypeName: System.String[]
like image 105
Keith Hill Avatar answered Sep 27 '22 21:09

Keith Hill