1908-powershell-array
1908-powershell-array¶
jupyter notebook¶
変数としてのarray の定義¶
Literalによる定義¶
In [1]:
$ary = @('power','shell')
In [2]:
$ary
power shell
In [3]:
$ary_empty = @()
空の配列
In [4]:
$ary_empty
In [5]:
$ary_other_def = 'power', 'shell', 'other', 'array'
In [6]:
$ary_other_def
power shell other array
$ary.GetType()¶
In [7]:
$ary.GetType() | Format-List
Module : CommonLanguageRuntimeLibrary Assembly : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 TypeHandle : System.RuntimeTypeHandle DeclaringMethod : BaseType : System.Array UnderlyingSystemType : System.Object[] FullName : System.Object[] AssemblyQualifiedName : System.Object[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Namespace : System GUID : 00000000-0000-0000-0000-000000000000 IsEnum : False GenericParameterAttributes : IsSecurityCritical : False IsSecuritySafeCritical : False IsSecurityTransparent : True IsGenericTypeDefinition : False IsGenericParameter : False GenericParameterPosition : IsGenericType : False IsConstructedGenericType : False ContainsGenericParameters : False StructLayoutAttribute : Name : Object[] MemberType : TypeInfo DeclaringType : ReflectedType : MetadataToken : 33554432 GenericTypeParameters : {} DeclaredConstructors : {Void .ctor(Int32)} DeclaredEvents : {} DeclaredFields : {} DeclaredMembers : {Void Set(Int32, System.Object), System.Object& Address(Int32), System.Object Get(Int32), Void .ctor(Int32)} DeclaredMethods : {Void Set(Int32, System.Object), System.Object& Address(Int32), System.Object Get(Int32)} DeclaredNestedTypes : {} DeclaredProperties : {} ImplementedInterfaces : {System.ICloneable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable...} TypeInitializer : IsNested : False Attributes : AutoLayout, AnsiClass, Class, Public, Sealed, Serializable IsVisible : True IsNotPublic : False IsPublic : True IsNestedPublic : False IsNestedPrivate : False IsNestedFamily : False IsNestedAssembly : False IsNestedFamANDAssem : False IsNestedFamORAssem : False IsAutoLayout : True IsLayoutSequential : False IsExplicitLayout : False IsClass : True IsInterface : False IsValueType : False IsAbstract : False IsSealed : True IsSpecialName : False IsImport : False IsSerializable : True IsAnsiClass : True IsUnicodeClass : False IsAutoClass : False IsArray : True IsByRef : False IsPointer : False IsPrimitive : False IsCOMObject : False HasElementType : True IsContextful : False IsMarshalByRef : False GenericTypeArguments : {} CustomAttributes : {[System.SerializableAttribute()]}
$ary | Get-Member¶
In [28]:
$ary | Get-Member | format-table Name, Definition
Name Definition ---- ---------- Clone System.Object Clone(), System.Object ICloneable.Clone() CompareTo int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.CompareTo(System.Ob... Contains bool Contains(string value) CopyTo void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) EndsWith bool EndsWith(string value), bool EndsWith(string value, System.StringComparison comparisonType), b... Equals bool Equals(System.Object obj), bool Equals(string value), bool Equals(string value, System.StringC... GetEnumerator System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEnumerator(), ... GetHashCode int GetHashCode() GetType type GetType() GetTypeCode System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() IndexOf int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf(char value, int start... IndexOfAny int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), int IndexOfAny(char[] a... Insert string Insert(int startIndex, string value) IsNormalized bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normalizationForm) LastIndexOf int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int LastIndexOf(char valu... LastIndexOfAny int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startIndex), int LastIndexOf... Normalize string Normalize(), string Normalize(System.Text.NormalizationForm normalizationForm) PadLeft string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar) PadRight string PadRight(int totalWidth), string PadRight(int totalWidth, char paddingChar) Remove string Remove(int startIndex, int count), string Remove(int startIndex) Replace string Replace(char oldChar, char newChar), string Replace(string oldValue, string newValue) Split string[] Split(Params char[] separator), string[] Split(char[] separator, int count), string[] Spli... StartsWith bool StartsWith(string value), bool StartsWith(string value, System.StringComparison comparisonType... Substring string Substring(int startIndex), string Substring(int startIndex, int length) ToBoolean bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte byte IConvertible.ToByte(System.IFormatProvider provider) ToChar char IConvertible.ToChar(System.IFormatProvider provider) ToCharArray char[] ToCharArray(), char[] ToCharArray(int startIndex, int length) ToDateTime datetime IConvertible.ToDateTime(System.IFormatProvider provider) ToDecimal decimal IConvertible.ToDecimal(System.IFormatProvider provider) ToDouble double IConvertible.ToDouble(System.IFormatProvider provider) ToInt16 int16 IConvertible.ToInt16(System.IFormatProvider provider) ToInt32 int IConvertible.ToInt32(System.IFormatProvider provider) ToInt64 long IConvertible.ToInt64(System.IFormatProvider provider) ToLower string ToLower(), string ToLower(cultureinfo culture) ToLowerInvariant string ToLowerInvariant() ToSByte sbyte IConvertible.ToSByte(System.IFormatProvider provider) ToSingle float IConvertible.ToSingle(System.IFormatProvider provider) ToString string ToString(), string ToString(System.IFormatProvider provider), string IConvertible.ToString(S... ToType System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider) ToUInt16 uint16 IConvertible.ToUInt16(System.IFormatProvider provider) ToUInt32 uint32 IConvertible.ToUInt32(System.IFormatProvider provider) ToUInt64 uint64 IConvertible.ToUInt64(System.IFormatProvider provider) ToUpper string ToUpper(), string ToUpper(cultureinfo culture) ToUpperInvariant string ToUpperInvariant() Trim string Trim(Params char[] trimChars), string Trim() TrimEnd string TrimEnd(Params char[] trimChars) TrimStart string TrimStart(Params char[] trimChars) Chars char Chars(int index) {get;} Length int Length {get;}
In [10]:
Get-Member -InputObject $ary -MemberType Method | format-table Name, Definition
Name Definition ---- ---------- Add int IList.Add(System.Object value) Address System.Object&, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Address(int ) Clear void IList.Clear() Clone System.Object Clone(), System.Object ICloneable.Clone() CompareTo int IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer) Contains bool IList.Contains(System.Object value) CopyTo void CopyTo(array array, int index), void CopyTo(array array, long index), void ICollection.CopyTo(arr... Equals bool Equals(System.Object obj), bool IStructuralEquatable.Equals(System.Object other, System.Collectio... Get System.Object Get(int ) GetEnumerator System.Collections.IEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEnumerat... GetHashCode int GetHashCode(), int IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer) GetLength int GetLength(int dimension) GetLongLength long GetLongLength(int dimension) GetLowerBound int GetLowerBound(int dimension) GetType type GetType() GetUpperBound int GetUpperBound(int dimension) GetValue System.Object GetValue(Params int[] indices), System.Object GetValue(int index), System.Object GetValu... IndexOf int IList.IndexOf(System.Object value) Initialize void Initialize() Insert void IList.Insert(int index, System.Object value) Remove void IList.Remove(System.Object value) RemoveAt void IList.RemoveAt(int index) Set void Set(int , System.Object ) SetValue void SetValue(System.Object value, int index), void SetValue(System.Object value, int index1, int inde... ToString string ToString()
In [11]:
$ary.Count
2
In [12]:
$ary.ToString()
System.Object[]
In [13]:
$ary.Add('Jupyter')
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size." At line:1 char:1 + $ary.Add('Jupyter') + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NotSupportedException
In [14]:
$ary += 'Jupyter'
In [15]:
Get-Member -InputObject $ary -MemberType Property | format-table Name, Definition
Name Definition ---- ---------- IsFixedSize bool IsFixedSize {get;} IsReadOnly bool IsReadOnly {get;} IsSynchronized bool IsSynchronized {get;} Length int Length {get;} LongLength long LongLength {get;} Rank int Rank {get;} SyncRoot System.Object SyncRoot {get;}
In [16]:
$ary
power shell Jupyter
In [34]:
$ary | out-Default
power shell Jupyter
In [17]:
$ary | foreach-object {$_.GetType().FullName; '>>' + $_}
System.String >>power System.String >>shell System.String >>Jupyter
In [18]:
foreach($ar in $ary)
{
$ar.GetType().FullName
'>>' + $ar
}
System.String >>power System.String >>shell System.String >>Jupyter
In [19]:
$ary.ToString()
System.Object[]
In [20]:
$ary | ConvertTo-Csv
#TYPE System.String "Length" "5" "5" "7"
In [21]:
$ary | ConvertTo-Csv -NoTypeInformation
"Length" "5" "5" "7"
In [22]:
ConvertTo-Csv -inputObject $ary -NoTypeInformation
"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized" "3","3","3","1","System.Object[]","False","True","False"
In [23]:
ConvertTo-Json -inputObject $ary
[ "power", "shell", "Jupyter" ]
In [24]:
$ary | Convertto-Json
[ "power", "shell", "Jupyter" ]
In [25]:
$ary -join ','
power,shell,Jupyter
In [26]:
Get-Help about_array
TOPIC about_Arrays SHORT DESCRIPTION Describes arrays, which are data structures designed to store collections of items. LONG DESCRIPTION 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. CREATING AND INITIALIZING AN ARRAY To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator (=). For example, to create an array named $A that contains the seven numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type: $A = 22,5,10,8,12,9,80 You can also create and initialize an array by using the range operator (..). For example, to create and initialize an array named "$B" that contains the values 5 through 8, type: $B = 5..8 As a result, $B contains four values: 5, 6, 7, and 8. When no data type is specified, Windows PowerShell creates each array as an object array (type: System.Object[]). To determine the data type of an array, use the GetType() method. For example, to determine the data type of the $a array, type: $a.GetType() To create a strongly typed array, that is, an array that can contain only values of a particular type, cast the variable as an array type, such as string[], long[], or int32[]. To cast an array, precede the variable name with an array type enclosed in brackets. For example, to create a 32-bit integer array named $ia containing four integers (1500, 2230, 3350, and 4000), type: [int32[]]$ia = 1500,2230,3350,4000 As a result, the $ia array can contain only integers. You can create arrays that are cast to any supported type in the Microsoft .NET Framework. For example, the objects that Get-Process retrieves to represent processes are of the System.Diagnostics.Process type. To create a strongly typed array of process objects, enter the following command: [Diagnostics.Process[]]$zz = Get-Process THE ARRAY SUB-EXPRESSION OPERATOR The array sub-expression operator creates an array, even if it contains zero or one object. The syntax of the array operator is as follows: @( ... ) You can use the array operator to create an array of zero or one object. PS C:\>$a = @("One") PS C:\>$a.Count 1 PS C:\>$b = @() PS C:\>$b.Count 0 The array operator is particularly useful in scripts when you are getting objects, but do not know how many objects you will get. PS C:\> $p = @(Get-Process Notepad) For more information about the array sub-expression operator, see about_Operators. READING AN ARRAY You can refer to an array by using its variable name. To display all the elements in the array, type the array name. For example: $a You can refer to the elements in an array by using an index, beginning at position 0. Enclose the index number in brackets. For example, to display the first element in the $a array, type: $a[0] To display the third element in the $a array, type: $a[2] Negative numbers count from the end of the array. For example, "-1" refers to the last element of the array. To display the last three elements of the array, type: $a[-3..-1] However, be cautious when using this notation. $a[0..-2] This command does not refer to all the elements of the array, except for the last one. It refers to the first, last, and second-to-last elements in the array. You can use the range operator to display a subset of all the values in an array. For example, to display the data elements at index position 1 through 3, type: $a[1..3] You can use the plus operator (+) to combine a range with a list of elements in an array. For example, to display the elements at index positions 0, 2, and 4 through 6, type: $a[0,2+4..6] To determine how many items are in an array, use the Length property or its Count alias. $a.Count You can also use looping constructs, such as ForEach, For, and While loops, to refer to the elements in an array. For example, to use a ForEach loop to display the elements in the $a array, type: foreach ($element in $a) {$element} The Foreach loop iterates through the array and returns each value in the array until reaching the end of the array. The For loop is useful when you are incrementing counters while examining the elements in an array. For example, to use a For loop to return every other value in an array, type: for ($i = 0; $i -le ($a.length - 1); $i += 2) {$a[$i]} You can use a While loop to display the elements in an array until a defined condition is no longer true. For example, to display the elements in the $a array while the array index is less than 4, type: $i=0 while($i -lt 4) {$a[$i]; $i++} GET THE MEMBERS OF AN ARRAY To get the properties and methods of an array, such as the Length property and the SetValue method, use the InputObject parameter of the Get-Member cmdlet. When you pipe an array to Get-Member, Windows PowerShell sends the items one at a time and Get-Member returns the type of each item in the array (ignoring duplicates). When you use the InputObject parameter, Get-Member returns the members of the array. For example, the following command gets the members of the array in the $a variable. Get-Member -InputObject $a You can also get the members of an array by typing a comma (,) before the value that is piped to the Get-Member cmdlet. The comma makes the array the second item in an array of arrays. Windows PowerShell pipes the arrays one at a time and Get-Member returns the members of the array. ,$a | Get-Member ,(1,2,3) | Get-Member MANIPULATING AN ARRAY You can change the elements in an array, add an element to an array, and combine the values from two arrays into a third array. To change the value of a particular element in an array, specify the array name and the index of the element that you want to change, and then use the assignment operator (=) to specify a new value for the element. For example, to change the value of the second item in the $a array (index position 1) to 10, type: $a[1] = 10 You can also use the SetValue method of an array to change a value. The following example changes the second value (index position 1) of the $a array to 500: $a.SetValue(500,1) You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type: $a += 200 It is not easy to delete elements from an array, but you can create a new array that contains only selected elements of an existing array. For example, to create the $t array with all the elements in the $a array except for the value at index position 2, type: $t = $a[0,1 + 3..($a.length - 1)] To combine two arrays into a single array, use the plus operator (+). The following example creates two arrays, combines them, and then displays the resulting combined array. $x = 1,3 $y = 5,9 $z = $x + $y As a result, the $z array contains 1, 3, 5, and 9. To delete an array, assign a value of $null to the array. The following command deletes the array in the $a variable. $a = $null You can also use the Remove-Item cmdlet, but assigning a value of $null is faster, especially for large arrays. ARRAYS OF ZERO OR ONE Beginning in Windows PowerShell 3.0, a collection of zero or one object has the Count and Length property. Also, you can index into an array of one object. This feature helps you to avoid scripting errors that occur when a command that expects a collection gets fewer than two items. The following examples demonstrate this feature. #Zero objects $a = $null $a.Count 0 $a.Length 0 #One object $a = 4 $a.Count 1 $a.Length 1 $a[0] 4 $a[-1] 4 SEE ALSO about_Assignment_Operators about_Hash_Tables about_Operators about_For about_Foreach about_While
reference¶
- How do I convert an array object to a string in PowerShell?
In [ ]:
</div>
Quote saved.
Login to quote this blog
Failed to save quote. Please try again later.
You cannot quote because this article is private.