Skip to content

Instantly share code, notes, and snippets.

@ssfang
Created April 22, 2016 14:52
Show Gist options
  • Save ssfang/6b801b9e201b27f75a54e6a4ed253e67 to your computer and use it in GitHub Desktop.
Save ssfang/6b801b9e201b27f75a54e6a4ed253e67 to your computer and use it in GitHub Desktop.
PowerShell on Windows
  • Powershell脚本的扩展名为“.ps1”

一个获取文件列表并修改文件时间属性的用法:

<#
文件:touch.ps1
用途:用于修改已存在文件时间属性的功能脚本
创建:2016-02-22,ss
修改:2016-02-22,ss
#>

# 获取命令行参数
param($path, [string]$time)

# 获取文件的cmdlet,此处用 Get-ChildItem ,别名有ls, dir, gci。
$files = Get-ChildItem $path -recurse -force
$ctime=$(Get-Date "2016-02-22 22:22:22")
foreach($f in $files)
{
	$f.LastAccessTime=$ctime
	$f.LastWriteTime=$ctime
	$f.CreationTime=$ctime
}

查看帮助,如man Get-ChildItem打印名字,语法,别名,备注。不够详细,备注说明:

备注
    Get-Help 在此计算机上找不到该 cmdlet 的帮助文件。它仅显示部分帮助。
        -- 若要下载并安装包含此 cmdlet 的模块的帮助文件,请使用 Update-Help。
        -- 若要联机查看此 cmdlet 的帮助主题,请键入: "Get-Help Get-ChildItem -Online" 或
           转到 http://go.microsoft.com/fwlink/?LinkID=113308。

PowerShell和C#有很大联系

从一个变量可以得到什么

#变量不用声明,直接使用,变量名字需要前缀美元符号$,此处cmdlet之dir是Get-ChildItem别名。
PS C:\Users\fang> $files=dir C:

# 判断是否一个数组
PS C:\Users\fang> $files -is [array]
True

# 数组的索引访问和属性(变量属性可以通过按Tab键进行提示)。多条命令后加分号进行分割。
PS C:\Users\fang> $files.length; $files[0].Attributes;
39
Directory

# 获取其类型,通过方法,可见其是C#里的东西。
PS C:\Users\fang> $files.gettype(); $files.gettype().gettype(); $files[0].gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
False    True     RuntimeType                              System.Reflection.TypeInfo
True     True     DirectoryInfo                            System.IO.FileSystemInfo

#类全名,类型可以通过[<Class>]方式引用,而String可以直接通过简单类名,而DirectoryInfo需要全名
PS C:\Users\fang> [String].FullName; $files[0].gettype().FullName
System.String
System.IO.DirectoryInfo

# 查看类的构造函数
PS C:\Users\fang> [String].GetConstructors() | foreach {$_.tostring()};
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)
PS C:\Users\fang> [System.IO.DirectoryInfo].GetConstructors() | % {$_.tostring()}
Void .ctor(System.String)

# 构造string类型变量,字符串需要引号
PS C:\Users\fang> $cpath="C:"; $cpath.GetType().FullName
System.String

# 变量强转
PS C:\Users\fang> ([System.IO.DirectoryInfo]"C:").GetType().FullName
System.IO.DirectoryInfo

# 构造System.IO.DirectoryInfo类型
PS C:\Users\fang> $dirInfo=New-Object System.IO.DirectoryInfo("C:\"); $dirInfo.FullName
C:\
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment