-1

I'm using PowerShell command prompt and I want to set a location to the folder "Folder". The thing is that folder can be everywhere.

I've tried the command Set-Location and Resolve-Path but I don't get it.

I want to do something like that:

$path = Resolve-Path ".*/Folder"
Set-Location $path

Where the .* can be all the parent folder

Any idea?

Robert Dyjas
  • 4,979
  • 3
  • 19
  • 34
BlueStraax
  • 103
  • 3
  • 11
  • 1
    How would you know if you want C:\win32\drivers, or C:\bluetooth\drivers, or any infinite possibility? Would you want the first one? The last one? Any of them? All of them? – Booga Roo Jun 17 '19 at 09:44

2 Answers2

1

Would try this:

Get-ChildItem -Path .\ -Name Folder -Recurse -Depth 10

Hope it helps. BR

Edit (see comments):

$array = Get-ChildItem -Path .\ -Name Ping -Recurse -Depth 10
if($array.Count -eq 0){
    #stay
}
if($array.Count -eq 1){
    Set-Location $array
}
else{
    $array | ForEach-Object{Write-Host $_}
}
  • It returns the all found folders whithin home directory with a depth of 10 layers. The rest of your code would work for setting it as the current location. BR – A guest who's called Redd Jun 17 '19 at 10:05
  • @robdy Actually a quit intressting question, regarding the `-Name` parameter it wouldn't say i mixed it up with `-filter`. Technically my idea was to check if there is an Item with the same name and iterate via `-Recurse`. How I'd use it I shall edit ;) – A guest who's called Redd Jun 17 '19 at 10:41
  • please see [this question](https://stackoverflow.com/q/56632954/9902555) for the explanation. – Robert Dyjas Jun 17 '19 at 14:04
0

Requires PowerShell v3 or higher, you can check using $PSVersionTable.*


$path = (Get-ChildItem . -Recurse -Directory | Where-Object { $_.Name -eq "Folder" }).FullName

This will give you all the directories named Folder in current directory and its subdirectories recursively.

The query, however, can return multiple results so if you want to choose the first one use [0]. Also, to cover the case when the query returns no results, enforce returned object to be an array using @( ... ) and check if it exists:

$f = @(Get-ChildItem . -Recurse -Directory | Where-Object { $_.Name -eq "Folder" })[0].FullName

if ( $f ) {
  cd $f
}
else {
  # Handle the error
}

cd is alias to Set-Location so you can use whichever you prefer. Important thing to remember is to use FullName property as it contains full path to the folder.


* For PowerShell versions lower than v3, use | Where-Object {$_.PSIsContainer -eq $true} instead of -Directory

Robert Dyjas
  • 4,979
  • 3
  • 19
  • 34