Jay*_*uzi 6 directory powershell file contains
我想从PowerShell检查文件路径是否在给定目录(或其子目录之一)中.
现在我正在做:
$file.StartsWith( $directory, [StringComparison]::InvariantCultureIgnoreCase )
Run Code Online (Sandbox Code Playgroud)
但我确信有更好的方法.
我可以采取$file.Directory并迭代所有.Parents,但我希望更简单的东西.
编辑:文件可能不存在; 我只是在看路径.
简单的事情怎么样:
PS> gci . -r foo.txt
Run Code Online (Sandbox Code Playgroud)
这隐式使用-filter参数(按位置)指定foo.txt作为过滤器.您还可以指定*.txt或foo?.txt.StartsWith的问题在于,当您处理不区分大小写的比较时,仍然存在/和\是PowerShell中的有效路径分隔符的问题.
假设文件可能不存在且$ file和$ directory都是绝对路径,您可以使用"PowerShell"方式执行此操作:
(Split-Path $file -Parent) -replace '/','\' -eq (Get-Item $directory).FullName
Run Code Online (Sandbox Code Playgroud)
但这并不是很好,因为你仍然需要规范路径/ - > \但至少PowerShell字符串比较不区分大小写.另一个选择是使用IO.Path规范化路径,例如:
[io.path]::GetDirectoryName($file) -eq [io.path]::GetFullPath($directory)
Run Code Online (Sandbox Code Playgroud)
与此一个问题是GetFullPath也将相对路径基于进程的当前目录的绝对路径,这多不倍,是不一样的PowerShell的当前目录.所以只要确保$ directory是一个绝对路径,即使你必须像"$ pwd\$ directory"那样指定它.
事情真的很快:
14:47:28 PS>pwd
C:\Documents and Settings\me\Desktop
14:47:30 PS>$path = pwd
14:48:03 PS>$path
C:\Documents and Settings\me\Desktop
14:48:16 PS>$files = Get-ChildItem $path -recurse |
Where {$_.Name -match "thisfiledoesnt.exist"}
14:50:55 PS>if ($files) {write-host "the file exists in this path somewhere"
} else {write-host "no it doesn't"}
no it doesn't
Run Code Online (Sandbox Code Playgroud)
(在桌面上或桌面上的文件夹中创建新文件并将其命名为“thisfileexists.txt”)
14:51:03 PS>$files = Get-ChildItem $path -recurse |
Where {$_.Name -match "thisfileexists.txt"}
14:52:07 PS>if($files) {write-host "the file exists in this path somewhere"
} else {write-host "no it doesn't"}
the file exists in this path somewhere
Run Code Online (Sandbox Code Playgroud)
当然,迭代仍在发生,但 PS 正在为你做这件事。如果查找系统/隐藏文件,您可能还需要 -force。
| 归档时间: |
|
| 查看次数: |
6239 次 |
| 最近记录: |