powershell-简要知识和用法

  基础
============= 比较运算
Powershell 中的比较运算符
-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含
-notcontains :不包含
求反
求反运算符为-not ” ! “ 也支持求反。
布尔运算
-and :和
-or :或
-xor :异或
-not :逆

=============删除列出的指定文件,利用了管道
> ls -Name "*.jpg" | Remove-Item -Path {$_}

=============时间:
日期和时间
1、获取系统时间
Get-Date
Get-Date -displayhint time
Get-Date -displayhint date
也可以把Get-Date赋给变量:
$A = Get-Date 5/1/2012
$B = Get-Date "5/1/2012 8:00 AM" # 指定值初始化时间
Get-Date还包括一些方法:
AddSeconds,如Get-Date.AddSeconds(10)
AddMinutes #添加分钟
AddHours #添加小时
AddDays #添加天
AddMonths #添加月
AddYears #添加年
2、设置系统时间
Set-Date -date "11/21/2012"
Set-Date -date "11/21/2012 8:30 AM"
Set-Date -date "11/21/2012 14:25"
Set-Date (Get-Date).AddDays(2)
Set-Date (Get-Date).AddHours(-1)
Set-Date -adjust 1:30:0 将系统时间向前调1个小时
3、时间运算
New-Timespan
如下:
New-Timespan $(Get-Date) $(Get-Date -month 12 -day 31 -year -hour 22 -minute 20 2012)
将返回两个日期相差的天数、小时数、分钟数、秒数
4、时间格式化
Get-Date -Format ‘yyyyMMddHHmmssffff’
yyyy 年
M 月
d 日
h 小时(12小时制)
H 小时(24小时制)
m 分钟
s 秒
f 秒以下毫秒


==========执行输出到文件
方法1:
Start-Transcript 和 Stop-Transcript
ps> Start-Transcript ‘D:\log.txt’ -Append -Force

==========输出重定向
‘>’为覆盖 ’>>’追加
> ls > log.txt
> ls >> log.txt

=============命令管道
“ | ” 符号 将执行结果管道到下一个命令
> ls | sort -Descending Name | Format-Table Name,Mode

=============输出循环转换成值的内容,而非数据类型
查找dll文件排序,选择性显示(Name)
$file_list = ls F:\ -Name "*.dll" | sort -Descending Name | Format-Table Name
接下来如果循环此数组输出每项会输出 其对象类型名 而非其实际值。如下改写可输出其值
$file_list = ls F:\ -Name "*.dll" | sort -Descending Name | Format-Table Name | ForEach-Object { $_ | Out-String }
注意后面,循环每个obj $_ 送入 管道 | 再 Out-String
也可以:
foreach($i in $dll_list){
$x = $i | Out-String #每个单独 out-string
#...
}
out-string输出时会带上一个 换行(`r`n),用:$x -replace "`n", "" -replace "`r", "" 替换掉(大坑,不只有`n)


=============调用.Net系统的方法
====调用类的静态方法
用中括号把类的名称括起来,然后输入两个冒号,然后再输入方法名,最后是方法的参数。语法如下:
[类名]::方法名(参数列表):> [System.Diagnostics.Process]::GetProcessById(0)
====访问类的静态属性
要访问.NET类的静态属性,可以使用中括号把类的名称括起来,然后输入两个冒号,然后再输入属性名。语法如下:
[类名]::属性名:> [System.DateTime]::Now
====调用对象的方法
在对象变量之后使用点(.)作为成员变量符,然后加上方法名,和方法参数即可。语法如下:
$对象变量.方法(参数列表):
$process = Get-Process notepad
$process.WaitForExit()
====访问对象的属性
在对象变量之后使用点(.)作为成员变量符,然后加上属性名即可。语法如下:
$对象变量.属性名:
$a=1,2,3
$a.count
====引用dll,并初始化实例
1. [void][reflection.assembly]::LoadFile("G:/Math2.dll") #导入某个dll
Add-Type -AssemblyName mscorlib #导入核心模块
Add-Type -AssemblyName System.Linq #导入System.Linq
Add-Type –Path “D:\PowerShellDemo\PowerShellDemo.dll” #这也可导入dll
New-Object 'System.Collections.Generic.Dictionary[[string],[string]]' #创建泛型
New-Object 'System.Collections.Generic.Dictionary[string,string]' #创建泛型
4. [System.Math]::CompareI(10,2) #调用静态
5. $a=New-Object Math.Methods #创建新对象
6. $a.CompareII(2,3) #调用对象方法
下面是一个实践的写法:
[System.String]
::Format("public {0} {1} {{get; set;}}", $type_name, $i.Name) # 用.net函数

=========================================技巧:

====不输出如下错误。执行正确输出字符串会被powershell获取打印并报下面类似错误
+ CategoryInfo : NotSpecified: (fatal: ................... :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
用如下方法
git.exe --% pull --progress -v --no-rebase "origin" 2>&1 | % { $_.ToString() }


成品:
# git自动pull 文档

$path_array = "F:\vsp\QJW.Document","F:\vsp\AMPS.Documents"

$path_array2 = ,"F:\vsp\QJW.Repair.Soa","F:\vsp\QJW.Manage",
"F:\vsp\QJW.Repair.Merchant",
"F:\vsp\QJW.Repair.Platform",
"F:\vsp\QJW.Repair.User",
"F:\vsp\QJW.Web"

$OFS = "`r`n" #定义换行符
$log_file_path = "F:\vsp\shell_script\git_auto_pull_log\" #定义日志文件路径
$log_date = Get-Date -Format 'yyyyMMddHHmm' #日志文件名时间部分,格式化
$log_file = "$($log_file_path)log_$log_date.log" #定义日志文件路径和名字
foreach($p in $path_array){
$now = Get-Date -Format 'yyyyMMddHHmmss'
cd $p
$info = "==== [$now]:启动 GIT PULL - [$p] ===="
echo $info | Out-File -Append $log_file -Encoding utf8
git.exe pull --progress -v --no-rebase "origin" 2>&1 | % { $_.ToString() } | Out-File -Append $log_file -Encoding utf8
echo $OFS | Out-File -Append $log_file -Encoding utf8
}
================用ps读取dll并生成代码

# 读取dll并生成c#代码

$dll_path="F:\vsp\××××\bin\×××.API.dll"
Add-Type -AssemblyName mscorlib
Add-Type -AssemblyName System.Linq
[void][reflection.assembly]::LoadFile($dll_path)
$obj = New-Object ×××.API.Models.Output.***ObjName
$type = $obj.GetType()
$ps = $type.GetProperties()

#
function MakeProperties($propertyType) {
    $type_name = $propertyType.PropertyType.Name
    if($propertyType.PropertyType.Name -eq "Int32"){
        $type_name = "int"
    }
    if($propertyType.PropertyType.Name -eq "Int64"){
        $type_name = "long"
    }
    if($propertyType.PropertyType.Name -eq "String"){
        $type_name = "string"
    }
    $template = [System.String]::Format("public {0} {1} {{get; set;}}", $type_name, $i.Name)
    return $template
}

function MakeTransObj($propertyType, $sourceObjName, $targetObjName){
    $template = [System.String]::Format("{1} = {0}.{1},", $sourceObjName, $propertyType.Name)
    return $template
}

foreach ($i in $ps){
    $temp = MakeTransObj $i "s" ""
    #$temp = MakeProperties $i
    Write-Output $temp
}








 

猜你喜欢

转载自my.oschina.net/raddleoj/blog/1818011