1.创建集合和泛型
a.创建List集合
#为了减少在同意命令空间的对象名的输入,可以使用-f操作符指定唯一的类名。
$namespace = "System.Collections.{0}";
$arrayList = New-Object ($namespace -f "ArrayList");
$queue = New-Object ($namespace -f "Queue");
$arrayList.Add("a");
$queue.Enqueue("b");
或者(使用ArrayList管理动态项的集合)
$arrayList = New-Object System.Collections.ArrayList;
[void]$arrayList.Add("a");
[void]$arrayList.Add(1);
[void]$arrayList.AddRange(("hello","world","china"));
b.创建泛型
$coll = New-Object 'System.Collections.ObjectModel.Collection`1[System.String]'
$coll.Add("aaaaaa");
$coll.Add($true);
$coll.get_Count();
c.创建一个HashSet的集合
Add-Type -ReferencedAssemblies System.Core @'
using System.Collections.Generic;
public class VirtualMachine {
public string Name;
public string HostName;
public HashSet
}
'@
$virtual = New-Object VirtualMachine;
$virtual.Dependencies.Add("a");
$virtual.Dependencies.Add("b");
$virtual.Dependencies.Add("a");#添加失败,不允许重复,返回False。
f.#在powershell中创建一个hashTable(不允许存放重复的值)
$hash = @{"key" = "value"};
或$has = @{key = 1;value = "aaaaa"};
$hash = @{}创建空哈希表
$hash.key1 = 1 将1赋给键key1
$hash.key1和$hash["key1"] 返回key1的值
$hash.Add(1,"aaa");
$hash.Add(2,"bbb");
$hash.Add(3,"ccc");
$hash.Add("ffff","ddd");
#使用foreach遍历keys/value
foreach($obj in $hash.Keys){
"key = " + $obj ;
" value = "+ $hash[$obj] ;
}
遍历的值:
key = 3
value = ccc
key = key
value = value
key = 2
value = bbb
key = 1
value = aaa
#使用enumerator遍历keys
[System.Collections.IEnumerator]$keys = $hash.Keys.GetEnumerator() ;
while($keys.MoveNext()){
"key = " + $keys.Key ;
" value = "+ $keys.Value ;
}
#使用hashtable的copyTo
[System.Object[]]$array=New-Object System.Object[] -ArgumentList $hash.Count;
$hash.CopyTo($array,0);
foreach($item in $array)
{
"key:"+$item.Key;
"value:"+$item.Value;
}
# discarding output using Out-Null输出重定向
dir | Out-Null
dir > $null # this is equivalent to the above
# Out-GridView uses a graphical interface to display the data
Get-Process *ss | Out-GridView
类似map集合
$a = [collections.generic.dictionary[string,int]] ;
$a.Set(1,"aaaa");
$a.Set(2,"bbbb");
$a.Set(3,"cccc");
$a.Set(2,"dddd");
$a.Get(2); ---->输出:dddd
2.创建一个多行或格式化的字符串
$myString = @'
this is the first line !
this is the second line !
this is the third line !
'@
b.使用here string 实现多行注释
$null = @'
function myTest
{
"this should not be considered a function" ;
}
'@
c.向字符串中插入动态信息
$header = "Report for Today"
$myString = "$header `n -------------"
$myString
d.向字符串中插入动态信息(使用powershell的格式化操作符)
$myString = "{0} `n {1}" -f $header , ('-' * $header.Length)
注意:字符串格式设置符(-f)使用与.NET框架中的String.Format()方法相同的字符串格式作为规则。
3.使用Get-Date命令的-Format参数
$getDate = Get-Date -Date '05/09/2012 1:23 PM' -Format 'dd-MM-yyyy hh:mm:ss'
使用字符串格式化(-f)运算符:
$date = [DateTime] '03/27/2021 1:19 PM';
$getDate = '{0: dd-MM-yyyy hh:mm:ss}' -f $date
对象的ToString()方法
$getDate = $date.ToString("dd-MM-yyyy hh:mm:ss");
4.将文本添加到字符串的结尾对与小型到中型字符串效果非常好,但是对较大的字符串会造成极大的性能问题
Measure-Command{
$output = New-Object System.Text.StringBuilder;
1..10000 | % { $output.Append("Hello World")}
}
TotalSeconds : 1.5562987
Measure-Command{
$output = ""
1..10000 | % { $output += "Hello World"}
}
TotalSeconds : 4.2449152
5.运算:powershell中两个整数相除,如果需要的话返回浮点型的结果。
将浮点型转换成整型需要"四舍五入"。
$a = 3/2 返回:1.5
$a = [int]3/2 返回:2
b.计算任意的根
function root ($number, $root){
[System.Math]::Exp($([Math]::Log($number)/$root));
}
root -number 125 -root 3
c.使用度而不是程序弧度为单位
function Convert-RadiansToDegrees($angle) {$angle/(2*[Math]::PI)*360 }
function Convert-DegreesToRadians($angle) { $angle/360 * (2*[Math]::PI) }
Convert-RadiansToDegrees([Math]::PI) 返回:180
Convert-DegreesToRadians -angle 360
[Math]::Tan([Math]::PI/4);
[Math]::Tan((Convert-DegreesToRadians -angle 45)) 返回1
6.在不同的进制间转换数字
a.直接输入一个十六进制数字,使用0x前缀:
$hexNumber = 0x1234 返回:4660
b.将数字转换为二进制表示,向[Convert]::ToString()方法提供2为基数
[Convert]::ToString(1234,2); 返回:10011010010
c.将二进制数字转换为十进制表示,向[Convert]::ToInt32()方法提供2为基数
[Convert]::ToInt32("10011010010",2); 返回:1234
d.将十六进制数转化为十进制表示形式,需要在数字前加入前缀0x
$myErrorCode = 0xFE4A 返回:65098
f.将数字转化为八进制表示形式,向[Convert]::ToInt32()方法提供参数8为基数。
[Convert]::ToInt32("1234",8); 返回:668
或[Convert]::ToString(1234,8); 返回:2322
g.将数字转换到十六进制表示形式,使用[Convert]类或powershell的格式运算符:
[Convert]::ToString(1234,16); 返回:4d2
"{0:X4}" -f 1234 ; 返回:04D2
7.(Measure-Object)度量一个列表的统计属性
默认情况下Measure-Object命令只统计它收到对象的个数,如果你要测量这些对象中的
其他属性(如最大值、最小值、平均值、总和、字符、单词或行),则需要命令提供选项。
-Property参数来测量得到要测量的属性。
例如:Get-ChildItem > output.txt
Get-Content output.txt | Measure-Object -Character -word -Line
Get-ChildItem | Measure-Object -Property Length -Max -Min -Average -Sum
8.编写脚本块:把不同的逻辑放到一个脚本块中,然后将脚本快作为一个参数传给需要它的代码,使用调用操 作符(&)来执行这个脚本块。
在管道中应用脚本块
Function Map-Object{
Param([ScriptBlock]$mapCommand)
Process
{
& $mapCommand
}
}
调用:1,2,3 | Map-Object { $_ * 2 } 返回2,4,6
注意:为了从一个脚本或函数返回数据,需要把改数据写入输出管道。但也可以使用传统的关键字return。如果不想该类的方法有返回值。可以在该方法前面加入[void]来避免返回值。
[void]$arrayList.Add("hello");
2.在脚本中若需要使用引用其他的脚本在这个脚本中使用".()"引入这个库文件。
例如:.(Join-Path $scriptDirectory test.ps1)
9.用命令关键字编写脚本
注:使用begin、process和end关键字,把你的脚本分成初始化、处理和清除几个区域。
Function Method{
begin{#初始化操作}
process{#处理操作}
end{#清理操作}
}