• PowerShell之 文件系统:简介

 

在PowerShell控制台中,文件系统有很特别的重要性。一个明显的原因是管理员需要执行许多涉及文件系统的任务。另一个原因是文件系统是一个层次结构信息模型。在接下来的章节中,你还会看到PowerShell在此基础上控制其它层次信息系统。你可以非常容易的将PowerShell中学到的驱动器,目录和文件的知识点应用到其它地方,其中就包括注册表或者微软的Exchange。

在下面表格中列出的PowerShell命令中,其全名可能很少有人用到。大家更倾向与使用它们非常实用的别名,这些别名来自Windows和Unix系统。可以让初学者可以非常快速地找到合适的命令。

非常重要的文件系统命令概览

别名描述命令
cp, cpi复制文件或者目录Copy-Item
Dir, ls, gci列出目录的内容Get-Childitem
type, cat, gc基于文本行来读取内容Get-Content
gi获取指定的文件或者目录Get-Item
gp获取文件或目录的属性Get-ItemProperty
ii使用对应的默认windows程序运行文件或者目录Invoke-Item
连接两个路径为一个路径Join-Path
mi, mv, move移动文件或者目录Move-Item
ni创建新文件或者目录New-Item
ri, rm, rmdir,del, erase, rd删除空目录或者文件Remove-Item
rni, ren重命名文件或者路径Rename-Item
rvpa处理相对路径或者包含通配符的路径Resolve-Path
sp设置文件或路径的属性Set-ItemProperty
Cd,chdir, sl更改当前目录的位置Set-Location
提取路径的特定部分,例如父目录,驱动器,文件名Split-Path
测试指定的路径是否存在Test-Path
  • PowerShell之 文件系统:访问文件和目录

 

使用Get-ChildItem列出目录的内容。预定义的别名为Dirls,Get-ChildItem执行了一些很重要的任务:

  • 显示目录内容

  • 递归地搜索文件系统查找确定的文件

  • 获取文件和目录的对象

  • 把文件传递给其它命令,函数或者脚本

注意:因为Windows管理员一般在实践中,使用Get-ChildItem的别名Dir,所以接下来的例子都会使用Dir。另外ls(来自UNIX家族)也可以代替下面例子中的Dir或者Get-ChildItem。

列出目录的内容

一般情况下,你可能只想知道在一个确定的目录中有什么文件,如果你不指定其它参数。Dir会列出当前目录的内容。如果你在Dir后跟了一个目录,它的内容也会被列出来,如果你使用了-recurse参数,Dir会列出所有子目录的内容。当然,也允许使用通配符。

例如,你想列出当前目录下的所有PowerShell脚本,输入下面的命令:

1

Dir *.ps1

Dir甚至能支持数组,能让你一次性列出不同驱动器下的内容。下面的命令会同时列出PowerShell根目录下的PowerShell脚本和Windows根目录下的所有日志文件。

1

Dir $pshome\\*.ps1, $env:windir\\*.log

如果你只对一个目录下的项目名称感兴趣,使用-Name参数,Dir就不会获取对象(Files和directories),只会以纯文本的形式返回它们的名称。

1

Dir -name

注意:一些字符在PowerShell中有特殊的意义,比如方括号。方括号用来访问数组元素的。这也就是为什么使用文件的名称会引起歧义。当你使用-literalPath参数来指定文件的路径时,所有的特殊字符被视为路径片段,PowerShell解释器也不会处理。

荔非苔注:Dir 默认的参数为-Path。假如你当前文件夹下有个文件名为“.\\a[0].txt“,因为方括号是PowerShell中的特殊字符,会解释器被解析。为了能正确获取到”.\\a[0].txt”的文件信息,此时可以使用-LiteralPath参数,它会把你传进来的值当作纯文本。

PS> Get-ChildItem .\\a[0].txt
PS> Get-ChildItem -Path .\\a[0].txt
PS> Get-ChildItem -LiteralPath .\\a[0].txt

    Directory: C:\\Users\\mosser

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          2014/1/2     14:04      80370 a[0].txt

递归搜索整个文件系统

当你想搜索整个子目录时,可以使用-recurce参数。但是注意,下面例子执行时会失败。

1

Dir *.ps1 -recurse

你需要了解一点-recurse如何工作的细节来理解为什么会发生上面的情况。Dir总是会获取目录中的内容为文件对象或者目录对象。如果你设置了-recurse开关,Dir会递归遍历目录对象。但是你在上面的例子中使用的通配符只获取扩展名为ps1的文件,没有目录,所以-recurse会跳过。这个概念刚开始使用时可能有点费解,但是下面的使用通配符例子能够递归遍历子目录,正好解释了这点。

在这里,Dir获取了根目录下所有以字母“D”打头的项目。递归开关起了作用,那是因为这些项目中就包含了目录。

1

Dir $home\\d* -recurse

荔非苔注:原文的作者写这篇文章时,是基于PowerShell 2.0,在高版本中的PowerShell 中Dir *.ps1 -recurse也是可以工作的。

过滤和排除标准

现在回到刚开始问题,怎样递归列出同类型的所有文件,比如所有PowerShell scripts。答案是使用Dir完全列出所有目录内容,同时指定一个过滤条件。Dir现在可以过滤出你想要列出的文件了。

1

Dir $home -filter *.ps1 -recurse

除了-filter,还有一个参数乍一看和-filter使用起来很像: -include

1

Dir $home -include *.ps1 -recurse

你会看到这一戏剧性的变化,-filter的执行效率明显高于-include:

1

2

3

4

(Measure-Command {Dir $home -filter *.ps1 -recurse}).TotalSeconds

4,6830099

(Measure-Command {Dir $home -include *.ps1 -recurse}).TotalSeconds

28,1017376

其原因在于-include支持正则表达式,从内部实现上就更加复杂,而-filter只支持简单的模式匹配。这也就是为什么你可以使用-include进行更加复杂的过滤。比如下面的例子,搜索所有第一个字符为A-F的脚本文件,显然已经超出了-filter的能力范围。

1

2

3

4

# -filter 查询所有以 "[A-F]"打头的脚本文件,屁都没找到

Dir $home -filter [a-f]*.ps1 -recurse

# -include 能够识别正则表达式,所以可以获取a-f打头,以.ps1收尾的文件

Dir $home -include [a-f]*.ps1 -recurse

与-include相反的是-exclude。在你想排除特定文件时,可以使用-exclude。不像-filter,-include和-exclude还支持数组,能让你获取你的家目录下所有的图片文件。

1

Dir $home -recurse -include *.bmp,*.png,*.jpg, *.gif

做到一点即可:不要混淆了-filter 和 -include。选择这两个参数中的其中一个:具体为当你的过滤条件没有正则表达式时,使用-filter,可以显著提高效率

注意:你不能使用filters在Dir中,列出确定大小的文件列表。因为Dir的限制条件只在文件和目录的名称级别。如果你想使用其它标准来过滤文件,可以尝试第五章中讲到的Where-Object。

下面的例子会获取你家目录下比较大的文件,指定文件至少要100MB大小。

1

Dir $home -recurse | Where-Object { $_.length -gt 100MB }

如果你想知道Dir返回了多少个文件项,Dir会将结果保存为一个数组,你可以通过数组的的Count属性来读取。下面的命令会告诉你你的家目录下有多少图片文件(这个操作可能会比较耗时)。

获取文件和目录的内容

你可以使用Dir直接获取一个单独的文件,因为Dir会返回一个目录下所有的文件和目录对象。下面的例子会得到这个文件的FileInfo信息:

$file = Dir C:\\a.html
$file | Format-List *
PSPath            : Microsoft.PowerShell.Core\\FileSystem::C:\\a.html
PSParentPath      : Microsoft.PowerShell.Core\\FileSystem::C:\\
PSChildName       : a.html
PSDrive           : C
PSProvider        : Microsoft.PowerShell.Core\\FileSystem
PSIsContainer     : False
VersionInfo       : File:             C:\\a.html
                    InternalName:
                    OriginalFilename:
                    FileVersion:
                    FileDescription:
                    Product:
                    ProductVersion:
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:

BaseName          : a
Mode              : -a---
Name              : a.html
Length            : 227740
DirectoryName     : C:\\
Directory         : C:\\
IsReadOnly        : False
Exists            : True
FullName          : C:\\a.html
Extension         : .html
CreationTime      : 2013/11/12 19:29:16
CreationTimeUtc   : 2013/11/12 11:29:16
LastAccessTime    : 2013/11/12 19:29:16
LastAccessTimeUtc : 2013/11/12 11:29:16
LastWriteTime     : 2013/11/12 19:29:24
LastWriteTimeUtc  : 2013/11/12 11:29:24
Attributes        : Archive

你可以访问单个文件的属性,如果它们的属性支持更改,也可以更改。

PS> $file.Attributes
Archive
PS> $file.Mode
-a---

Get-Item是访问单个文件的另外一个途径, 下面的3条命令都会返回同样的结果:你指定的文件的文件对象。

1

2

3

$file = Dir c:\\autoexec.bat

$file = Get-Childitem c:\\autoexec.bat

$file = Get-Item c:\\autoexec.bat

但是在访问目录而不是文件时,Get-Childitem 和 Get-Item表现迥异。

1

2

3

4

# Dir 或者 Get-Childitem 获取 一个目录下的内容:

$directory = Dir c:\\windows

$directory = Get-Childitem c:\\windows

$directory

    Directory: C:\\windows

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         2013/8/22     23:36            addins
d----         2013/8/22     23:36            ADFS
d----         2013/8/22     23:36            AppCompat
d----        2013/11/22     19:13            apppatch
d----        2013/12/27     12:05            AppReadiness
d-r--        2013/12/17      3:44            assembly
d----         2013/9/16     10:11            AUInstallAgent
d----         2013/8/22     23:36            Boot
d----         2013/8/22     23:36            Branding
d----        2013/10/24     14:27            Camera

1

2

3

# Get-Item 获取的是目录对象本身:

$directory = Get-Item c:\\windows

$directory

    Directory: C:\\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2013/11/22     19:13            windows
PS> $directory | Format-List *

PSPath            : Microsoft.PowerShell.Core\\FileSystem::C:\\windows
PSParentPath      : Microsoft.PowerShell.Core\\FileSystem::C:\\
PSChildName       : windows
PSDrive           : C
PSProvider        : Microsoft.PowerShell.Core\\FileSystem
PSIsContainer     : True
BaseName          : windows
Mode              : d----
Name              : windows
Parent            :
Exists            : True
Root              : C:\\
FullName          : C:\\windows
Extension         :
CreationTime      : 2013/8/22 21:36:15
CreationTimeUtc   : 2013/8/22 13:36:15
LastAccessTime    : 2013/11/22 19:13:22
LastAccessTimeUtc : 2013/11/22 11:13:22
LastWriteTime     : 2013/11/22 19:13:22
LastWriteTimeUtc  : 2013/11/22 11:13:22
Attributes        : Directory

向命令,函数和文件脚本传递文件

因为Dir的结果中返回的是独立的文件或目录对象,Dir可以将这些对象直接交付给其它命令或者你自己定义的函数与脚本。这也使得Dir成为了一个非常重要的的选择命令。使用它你可以非常方便地在一个驱动盘下甚至多个驱动盘下递归查找特定类型的所有文件。

要做到这点,在管道中使用Where-Object来处理Dir返回的结果,然后再使用ForEach-Object(第五章),或者你自定义的管道过滤(第九章)。

小知识:你还可以将多个Dir 命令执行的结果结合起来。在下面的例子中,两个分开的Dir命令,产生两个分开的文件列表。然后PowerShell将它们结合起来发送给管道进行深度处理。这个例子获取Windows目录和安装程序目录下的所有的dll文件,然后返回这些dll文件的名称,版本,和描述:

1

2

3

4

5

6

7

8

9

$list1 = Dir $env:windir\\system32\\*.dll

$list2 = Dir $env:programfiles -recurse -filter *.dll

$totallist = $list1 + $list2

$totallist | ForEach-Object {

$info =

[system.diagnostics.fileversioninfo]::GetVersionInfo($_.FullName);

"{0,-30} {1,15} {2,-20}" -f $_.Name, `

$info.ProductVersion, $info.FileDescription

}

accessibilitycpl.dll            6.3.9600.16384 Ease of access  control panel
ACCTRES.dll                     6.3.9600.16384 Microsoft Internet Account Manager Resources
acledit.dll                     6.3.9600.16384 Access Control List Editor
aclui.dll                       6.3.9600.16384 Security Descriptor Editor
acppage.dll                     6.3.9600.16384 Compatibility Tab Shell Extension Library
acproxy.dll                     6.3.9600.16384 Autochk Proxy DLL
ActionCenter.dll                6.3.9600.16384 Action Center
ActionCenterCPL.dll             6.3.9600.16384 Action Center Control Panel
ActionQueue.dll                 6.3.9600.16384 Unattend Action Queue Generator / Executor
activeds.dll                    6.3.9600.16384 ADs Router Layer DLL
actxprxy.dll                    6.3.9600.16425 ActiveX Interface Marshaling Library
adhapi.dll                      6.3.9600.16384 AD harvest sites and subnets API
adhsvc.dll                      6.3.9600.16384 AD Harvest Sites and Subnets Service

因为Dir获取的文件和目录是一样的,有时限制结果中只包含文件或者只包含目录很重要。有很多途径可以做到这点。你可以验证返回对象的属性,PowerShell PSIsContainer属性,或者对象的类型。

1

2

3

4

5

6

7

8

# 只列出目录::

Dir | Where-Object { $_ -is [System.IO.DirectoryInfo] }

Dir | Where-Object { $_.PSIsContainer }

Dir | Where-Object { $_.Mode.Substring(0,1) -eq "d" }

# 只列出文件:

Dir | Where-Object { $_ -is [System.IO.FileInfo] }

Dir | Where-Object { $_.PSIsContainer -eq $false}

Dir | Where-Object { $_.Mode.Substring(0,1) -ne "d" }

前面的例子(识别对象类型)是目前速度最快的,而后面的(文本比较)比较复杂和低效。

Where-Object也可以根据其它属性来过滤。

比如下面的例子通过管道过滤2007年5月12日后更改过的文件:

1

Dir | Where-Object { $_.CreationTime -gt [datetime]::Parse("May 12, 2007") }

也可以使用相对时间获取2周以内更改过的文件:

1

Dir | Where-Object { $_.CreationTime -gt (Get-Date).AddDays(-14) }

  • PowerShell之 文件系统:导航文件系统

 

使用Get-Location命令获取当前工作的目录。

Get-Location
Path
----
C:\\Users\\Mosser Lee\\Sources

如果你想导航到文件系统的另外一个位置,可以使用Set-Location或者它的别名Cd

1

2

3

4

5

6

7

8

9

10

# 进入父目录 (相对路径):

Cd ..

# 进入当前盘的根目录 (相对路径):

Cd \\

# 进入指定目录 (绝对路径):

Cd c:\\windows

# 从环境变量中获取系统目录 (绝对路径):

Cd $env:windir

# 从普通变量中获取目录 (绝对路径):

Cd $home

相对路径和绝对路径

路径的指定可以是相对路径,也可以是绝对路径。在上面的最后一个例子中,兼而有之这两种路径。相对路径依赖你当前的路径,比如.\\test.txt文件总是指定的是当前目录中的test.txt文件,而..\\test.txt指定的是父目录的test.txt文件。相对路径通常比较实用,比如你想使用的脚本库位于当前工作目录,你就可以在不引入其它目录的情况下,直接工作。而绝对路径通常具有唯一性,并且独立于你当前的目录。

用于指定相对路径的四个重要的特殊字符

字符

意义示例示例描述

.

当前目录Ii .用资源浏览器打开当前目录

..

父目录Cd ..切换到父目录

\\

驱动器根目录Cd \\切换到驱动器的顶级根目录

~

家目录Cd ~切换到PowerShell初始化的目录
相对路径转换成绝对路径

当你使用相对路径时,PowerShell必须将这些相对转换成绝对路径。在你使用相对路径执行一个文件或者一条命令时,该转换会自动发生。你也可以自己使用Resolve-Path命令来处理。

PS C:\\Users\\Mosser> Resolve-Path .\\a.png

Path
----
C:\\Users\\Mosser\\a.png

然而,Resolve-Path命令只有在文件确实存在时,才会有效。如果你的当前文件夹中没有一个名为a.png的是,Resolve-Path名讳报错。

如果你指定的路径中包含了通配符,Resolve-Path还可以返回多个结果。下面的命令执行后,会获取PowerShell家目录下面的所有的ps1xml文件的名称。

PS> Resolve-Path $pshome\\*.ps1xml

Path
----
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Certificate.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Diagnostics.Format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\DotNetTypes.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Event.Format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\FileSystem.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\getevent.types.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Help.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\HelpV3.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShellCore.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShellTrace.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Registry.format.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\types.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\typesv3.ps1xml
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\WSMan.Format.ps1xml

像Dir一样,Resolve-Path可以在下行函数中扮演选择过滤器的的角色。下面的例子会演示在记事本中打开一个文件进行处理。命令调用记事本程序通过Resolve-Path打开这个文件。

1

notepad.exe (Resolve-Path $pshome\\types.ps1xml).providerpath

如果没有符合标准的文件,Resolve-Path会抛出一个异常,记录在$?变量中(第十一章),在错误发生时表达式!$?一直会统计,在True的情况下,代表可能没找到文件。

如果Resolve-Path找到了多个文件会把它保存在一个数组中,这样的化会有很多不期望的文件被打开。函数使用了第六章讲到的PowerShell 内部的函数PromptForChoice(),来请求用户做出选择。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

function edit-file([string]$path=$(Throw "请输入相对路径!"))

{

# 处理相对路径,并抑制错误

$files = Resolve-Path $path -ea SilentlyContinue

# 验证是否有错误产生:

if (!$?)

{

# 如果是,没有找到符合标准的文件,给出提醒并停止:

"没有找到符合标准的文件.";

break

}

# 如果返回结果为数组,表示有多个文件:

if ($files -is [array])

{

# 此种情况下,列出你想打开的文件:

Write-Host -foregroundColor "Red" -backgroundColor "White" `

"你想打开这些文件吗?"

foreach ($file in $files)

{

"- " + $file.Path

}

# 然后确认这些文件是否为用户想打开的:

$yes = ([System.Management.Automation.Host.ChoiceDescription]"&yes")

$no = ([System.Management.Automation.Host.ChoiceDescription]"&no")

$choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)

$result = $host.ui.PromptForChoice('Open files','Open these files?',$choices,1)

# 如果用户确认,使用"&"操作符启动所有的文件

if ($result -eq 0)

{

foreach ($file in $files)

{

& $file

}

}

}

else

{

# 如果是单个文件,可以直接使用"&"启动:

& $files

}

}

保存目录位置

当前的目录可以使用Push-Location命令保存到目录堆栈的顶部,每一个Push-Location都可以将新目录添加到堆栈的顶部。使用Pop-Location可以返回。

因此,如果你要运行一个任务,不得不离开当前目录,可以在运行任务前将用Push-Location存储当前路径,然后运行结束后再使用Pop-Location返回到当前目录。Cd $home总是会返回到你的家目录,Push-Location 和 Pop-Location支持堆栈参数。这使得你可以创建很多堆栈,比如一个任务,一个堆栈。Push-Location -stack job1会把当前目录保存到job1堆栈中,而不是标准堆栈中。当然在你想重新回到这个位置时,也需要在Pop-Location中指定这个参数-stack job1。

查找特殊的目录

Windows使用了很多特殊的目录,根据系统的安装,可能稍有不同。一些非常重要的目录的路径同时也保存在Windows环境变量中,这样PowerShell 可以非常方便和清晰的访问它们。你也可以使用.NET framework中的Environment类去访问其它特殊目录。

存储在环境变量中的Windows特殊目录

特殊目录

描述示例
Application data存储在本地机器上的应用程序数据$env:localappdata
User profile用户目录$env:userprofile
Data used incommon应用程序公有数据目录$env:commonprogramfiles
Public directory所有本地用户的公有目录$env:public
Program directory具体应用程序安装的目录$env:programfiles
Roaming Profiles漫游用户的应用程序数据$env:appdata
Temporary files(private)当前用户的临时目录$env:tmp
Temporary files公有临时文件目录$env:temp
Windows directoryWindows系统安装的目录$env:windir

环境变量返回的只是其中一部分,还不是全部的特殊目录。比如如果你想将某个文件放到一个用户的桌面,你需要的路径在环境变量中是无法获取的。但是你可以使用.NET的方法environment类下面的GetFolderPath()方法。下面会演示如何在桌面上创建一个快捷方式。

1

2

3

4

5

6

7

# 在桌面上创建一个快捷方式:

$path = [Environment]::GetFolderPath("Desktop") + "\\EditorStart.lnk"

$comobject = New-Object -comObject WScript.Shell

$link = $comobject.CreateShortcut($path)

$link.targetpath = "notepad.exe"

$link.IconLocation = "notepad.exe,0"

$link.Save()

GetFolderPath()目录的类型可以在枚举值SpecialFolder中找到。你可以使用下面一行脚本查看它的内容。

PS> [System.Environment+SpecialFolder] | Get-Member -static -memberType Property | select -ExpandPropert
y Name
AdminTools
ApplicationData
CDBurning
CommonAdminTools
CommonApplicationData
CommonDesktopDirectory
CommonDocuments
CommonMusic
CommonOemLinks
CommonPictures
CommonProgramFiles
CommonProgramFilesX86
CommonPrograms
CommonStartMenu
CommonStartup
CommonTemplates
CommonVideos
Cookies
Desktop
DesktopDirectory
Favorites
Fonts
History
InternetCache
LocalApplicationData
LocalizedResources
MyComputer
MyDocuments
MyMusic
MyPictures
MyVideos
NetworkShortcuts
Personal
PrinterShortcuts
ProgramFiles
ProgramFilesX86
Programs
Recent
Resources
SendTo
StartMenu
Startup
System
SystemX86
Templates
UserProfile
Windows

如果你想预览所有GetFolderPath()支持的目录内容,可以使用下面的例子:

[System.Environment+SpecialFolder] |
Get-Member -static -memberType Property |
ForEach-Object { "{0,-25}= {1}" -f $_.name, [Environment]::GetFolderPath($_.Name) 
}

AdminTools               = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tool
ApplicationData          = C:\\Users\\mosser\\AppData\\Roaming
CDBurning                = C:\\Users\\mosser\\AppData\\Local\\Microsoft\\Windows\\Burn\\Burn
CommonAdminTools         = C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools
CommonApplicationData    = C:\\ProgramData
CommonDesktopDirectory   = C:\\Users\\Public\\Desktop
CommonDocuments          = C:\\Users\\Public\\Documents
CommonMusic              = C:\\Users\\Public\\Music
CommonOemLinks           =
CommonPictures           = C:\\Users\\Public\\Pictures
CommonProgramFiles       = C:\\Program Files\\Common Files
CommonProgramFilesX86    = C:\\Program Files (x86)\\Common Files
CommonPrograms           = C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs
CommonStartMenu          = C:\\ProgramData\\Microsoft\\Windows\\Start Menu
CommonStartup            = C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup
CommonTemplates          = C:\\ProgramData\\Microsoft\\Windows\\Templates
CommonVideos             = C:\\Users\\Public\\Videos
Cookies                  = C:\\Users\\mosser\\AppData\\Local\\Microsoft\\Windows\\INetCookies
Desktop                  = C:\\Users\\mosser\\Desktop
DesktopDirectory         = C:\\Users\\mosser\\Desktop
Favorites                = C:\\Users\\mosser\\Favorites
Fonts                    = C:\\WINDOWS\\Fonts
History                  = C:\\Users\\mosser\\AppData\\Local\\Microsoft\\Windows\\History
InternetCache            = C:\\Users\\mosser\\AppData\\Local\\Microsoft\\Windows\\INetCache
LocalApplicationData     = C:\\Users\\mosser\\AppData\\Local
LocalizedResources       =
MyComputer               =
MyDocuments              = C:\\Users\\mosser\\Documents
MyMusic                  = C:\\Users\\mosser\\Music
MyPictures               = C:\\Users\\mosser\\Pictures
MyVideos                 = C:\\Users\\mosser\\Videos
NetworkShortcuts         = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Network Shortcuts
Personal                 = C:\\Users\\mosser\\Documents
PrinterShortcuts         = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Printer Shortcuts
ProgramFiles             = C:\\Program Files
ProgramFilesX86          = C:\\Program Files (x86)
Programs                 = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs
Recent                   = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Recent
Resources                = C:\\WINDOWS\\resources
SendTo                   = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\SendTo
StartMenu                = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu
Startup                  = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup
System                   = C:\\WINDOWS\\system32
SystemX86                = C:\\WINDOWS\\SysWOW64
Templates                = C:\\Users\\mosser\\AppData\\Roaming\\Microsoft\\Windows\\Templates
UserProfile              = C:\\Users\\mosser
Windows                  = C:\\WINDOWS

构造路径

路径名称由文本构成,能让你随心所欲地构造他们。你也应当看到了上面例子中构造用户桌面快捷方式的过程了:

path = [Environment]::GetFolderPath("Desktop") + "\\file.txt"
$path
C:\\Users\\mosser\\Desktop\\file.txt

一定要确保你的路径中的反斜杠个数正确。这也就是为什么前面的例子中在file.txt前面使用了一个反斜杠。还有一个更可靠的方式,就是使用命令 Join-Path方法,或者.NET中的Path静态类。

path = Join-Path ([Environment]::GetFolderPath("Desktop")) "test.txt"
$path
C:\\Users\\mosser\\Desktop\\test.txt
$path = [System.IO.Path]::Combine([Environment]::`
GetFolderPath("Desktop"), "test.txt")
$path
C:\\Users\\mosser\\Desktop\\test.txt

Path类还包含了许多用来合并或者获取目录特定信息的额外方法。你只需要在下面表格中列出的方法中前加[System.IO.Path]::,比如:

1

2

[System.IO.Path]::ChangeExtension("test.txt", "ps1")

test.ps1

构造路径的方法

方法描述示例
ChangeExtension()更改文件的扩展名ChangeExtension(“test.txt”, “ps1″)
Combine()拼接路径字符串; 对应Join-PathCombine(“C:\\test”, “test.txt”)
GetDirectoryName()返回目录对象:对应Split-Path -parentGetDirectoryName(“c:\\test\\file.txt”)
GetExtension()返回文件扩展名GetExtension(“c:\\test\\file.txt”)
GetFileName()返回文件名:对应Split-Path -leafGetFileName(“c:\\test\\file.txt”)
GetFileNameWithoutExtension()返回不带扩展名的文件名GetFileNameWithoutExtension(“c:\\test\\file.txt”)
GetFullPath()返回绝对路径GetFullPath(“.\\test.txt”)
GetInvalidFileNameChars()返回所有不允许出现在文件名中字符GetInvalidFileNameChars()
GetInvalidPathChars()返回所有不允许出现在路径中的字符GetInvalidPathChars()
GetPathRoot()返回根目录:对应Split-Path -qualifierGetPathRoot(“c:\\test\\file.txt”)
GetRandomFileName()返回一个随机的文件名GetRandomFileName()
GetTempFileName()在临时目录中返回一个临时文件名GetTempFileName()
GetTempPath()返回临时文件目录GetTempPath()
HasExtension()如果路径中包含了扩展名,则返回TrueHasExtension(“c:\\test\\file.txt”)
IsPathRooted()如果是绝对路径,返回为True; Split-Path -isAbsoluteIsPathRooted(“c:\\test\\file.txt”)