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