How to check if a file is in a given directory in PowerShell?

I want to check if the file path is in the given directory (or one of its subdirectories) from PowerShell.

Now I am doing:

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

but I'm sure there are better ways.

I could do $file.Directoryand iterate over all .Parents, but I was hoping for something simpler.

EDIT : file may not exist; I just look at the path.

+5
source share
5 answers

How about something simple:

PS> gci . -r foo.txt

-filter ( ), foo.txt . *.txt foo?.txt. StartsWith , , /\ PowerShell.

, , $file $ , "PowerShell":

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

, /- > \, , , PowerShell . - IO.Path , :

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

, GetFullPath , dir , , , dir PowerShell. , $ , "$ pwd\$directory".

+5

- :

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 | {$ _. Name -match "thisfiledoesnt.exist" }

14:50:55 PS > if ($ files) {write-host " -" } else {write-host "no it does not" } ,

( "thisfileexists.txt" )

14:51:03 PS > $files = Get-ChildItem $path -recurse | {$ _. Name -match "thisfileexists.txt" }

14:52:07 PS > if ($ files) {write-host " -" } else {write-host "no it does not" } -

, , PS . -force, / .

0

- ?

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

, string.StartsWith ( OrdinalIgnoreCase - , ).

, . , C:\x\..\a\b.txt C:/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). , .

0

If you convert your input strings to DirectoryInfo and FileInfo, you will not have problems comparing strings.

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

All Articles