PowerShell中使用Test-Path命令检查文件或文件夹路径是否存在示例
检查文件或文件夹路径是否存在,在编程中是经常用到的功能。PowerShell对于这个需求提供了一个非常便捷的cmdlet,那就是Test-Path!呵呵,看个名字,你就明白它有多么专业了。看看关于它的基本介绍先:
Test-Path,检查路径是否存在。
语法:Test-Path<路径>
说明:这里的路径可以是:文件、文件夹、HKLM路径、环境变量env:路径
下面来举一些例子,让大家更方便懂:
Test-PathD:\q.txt Test-PathC:\Scripts\Archive-pathTypecontainer Test-Path"HKCU:\Software\Microsoft\DriverSigning" Test-PathAlias:\gci Test-PathEnv:\username Test-PathC:\Scripts\Archive-pathTypeleaf Test-PathC:\Scripts\Archive\*.ps1 Test-PathC:\Scripts\Archive\*-include*.ps1,*.vbs Test-PathC:\Scripts\Archive\*-includeTest*.ps1,Test*.vbs Test-PathC:\Scripts\Archive\*-exclude*.ps1 Test-PathC:\Scripts\Archive\*-exclude*.gif,*.jpg Test-PathD:\网站备份\2013-04-*\cnsm*#检查2013-04开头的目录下有没有cnsm开头的项目
看完之后,冰雪聪明的你,是不是觉得这玩意儿太TM的强大了?唉,这是它为什么叫PowerShell的原因了。
说说返回值,Test-Path的返回值为True或False,所以,你可以把它放到if语句中,效果是非常好的。