簡體   English   中英

如何在PowerShell中檢查文件是否在給定目錄下?

[英]How do I check if a file is under a given directory, in PowerShell?

我想從PowerShell檢查文件路徑是否在給定目錄(或其子目錄之一)中。

現在我正在做:

$file.StartsWith(  $directory, [StringComparison]::InvariantCultureIgnoreCase )

但我確信有更好的方法。

我可以拿$file.Directory並迭代所有.Parent s,但我希望更簡單。

編輯 :文件可能不存在; 我只是在看路徑。

簡單的事情怎么樣:

PS> gci . -r foo.txt

這隱式使用-filter參數(按位置)指定foo.txt作為過濾器。 您還可以指定* .txt或foo?.txt。 StartsWith的問題在於,當您處理不區分大小寫的比較時,仍然存在/和\\是PowerShell中的有效路徑分隔符的問題。

假設文件可能不存在且$ file和$ directory都是絕對路徑,您可以使用“PowerShell”方式執行此操作:

(Split-Path $file -Parent) -replace '/','\' -eq (Get-Item $directory).FullName

但這並不是很好,因為你仍然需要規范路徑/ - > \\但至少PowerShell字符串比較不區分大小寫。 另一個選擇是使用IO.Path規范化路徑,例如:

[io.path]::GetDirectoryName($file) -eq [io.path]::GetFullPath($directory)

與此一個問題是GetFullPath也將相對路徑基於進程的當前目錄的絕對路徑,這多不倍,是一樣的PowerShell的當前目錄。 所以只要確保$ directory是一個絕對路徑,即使你必須像“$ pwd \\ $ directory”那樣指定它。

由於路徑可能不存在,因此使用string.StartsWith可以進行此類測試(盡管OrdinalIgnoreCase可以更好地表示文件系統如何比較路徑 )。

唯一需要注意的是路徑需要采用規范形式。 否則, C:\\x\\..\\a\\b.txtC:/a/b.txt將失敗“這是在C:\\a\\目錄下”測試。 在執行測試之前,可以使用靜態Path.GetFullPath方法獲取路徑的全名:

function Test-SubPath( [string]$directory, [string]$subpath ) {
  $dPath = [IO.Path]::GetFullPath( $directory )
  $sPath = [IO.Path]::GetFullPath( $subpath )
  return $sPath.StartsWith( $dPath, [StringComparison]::OrdinalIgnoreCase )
}

另請注意,這不包括邏輯包含(例如,如果你有\\\\some\\network\\path\\映射到Z:\\path\\ ,測試\\\\some\\network\\path\\b.txt是否在Z:\\會失敗,即使可以通過Z:\\path\\b.txt訪問該文件。 如果您需要支持此行為, 這些問題可能會有所幫助。

真快的東西:

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

(在桌面上或桌面上的文件夾中創建新文件,並將其命名為“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

當然迭代仍在發生,但PS正在為你做這件事。 如果查找系統/隱藏文件,您也可能需要-force。

像這樣的東西?

Get-ChildItem -Recurse $directory | Where-Object { $_.PSIsContainer -and `
    $_.FullName -match "^$($file.Parent)" } | Select-Object -First 1

如果將輸入字符串轉換為DirectoryInfo和FileInfo,則字符串比較不會有任何問題。

function Test-FileInSubPath([System.IO.DirectoryInfo]$Dir,[System.IO.FileInfo]$File)
{
    $File.FullName.StartsWith($Dir.FullName)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM