PowerShell - Arrays
PowerShell - Arrays
How to declare or create and operate an Array
# Creating Array using Array Operator
$fruits = @("Apple","Orange","KiWi")
$fruits
$Numbers = @(1..12)
$Numbers
$Services = @(Get-Service)
$Services
# Creating PowerShell Array by Simple assigning comma seperated Value to a Variable
$Multi = "A","B","C"
$Multi
$Single = ,"white"
$Single
# How Indexing works for an PowerShell Array
# How access elements of an Powershell Array
$Numbers
$Numbers[0]
$Numbers[-1]
$Numbers[3..6]
$Numbers[1,2+7..9]
# Create Strongly Typed PowerShell Array
$normal = 1, "a", 222, "c"
$normal
$normal.GetType()
[int[]]$strong = 1,4,2
$strong.GetType()
Get-Process | Get-Member
Get-Process|gm
[System.Diagnostics.Process[]]$Processes = Get-Service
[System.Diagnostics.Process[]]$Processes = Get-Process
$Processes
# PowerShell Operators working with Powershell Arrays
#Join Operator
$Numbers
$Numbers -join, "-"
-join $Numbers
#Replace Operator
$fruits
$fruits -replace "Kiwi", "TV"
#Contains Operator
$fruits -contains "Kiwi"
#In Operator
"kiwi" -in $fruits
# Propeties and Methods of an Powershell Array
$Numbers.Length
$Numbers.Count
$Numbers
$Numbers.Clear()
$Numbers
$Numbers | % {$_ -eq $null}
# Foreach Method
$Numbers = 1..12
$Numbers.ForEach({$_ * 2})
$fruits
$fruits.ForEach("ToUpper")
$fruits.ForEach("ToLower")
# Where Method
$Numbers.Where({$_ -lt 8})
('Yellow', '', 'Black').Where({$_.Length})
$Numbers.Where({$_ -lt 8}, "first",4)
$Numbers.Where({$_ -lt 8}, "last",3)
$Numbers.Where({$_ -gt 8}, "SkipUntil",4)
$Numbers.Where({$_ -gt 8}, "Until",2)
$running, $stopped = (Get-Service).Where({$_.Status -eq 'Running'}, 'Split')
$running
$stopped
# Manipulating the Array
$Numbers
$Numbers += 14
$Numbers[-1] = 16
$Numbers.SetValue(18,1)
$Numbers.RemoveAt(1)
$Numbers.IsFixedSize
$Numbers.GetType()
[System.Collections.ArrayList]$NewNumbers = 1..5
$NewNumbers
$NewNumbers.IsFixedSize
$NewNumbers.Remove(4)
$NewNumbers
$NewNumbers.RemoveAt(1)
$NewNumbers
$NewNumbers.Add(100)
$NewNumbers
# Iterating through elements of Array
$NewNumbers
foreach ($Number in $NewNumbers)
{$Number * 4}
for ($i = 0; $i -le $NewNumbers.Count; $i++)
{$NewNumbers[$i] * 5}
相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。