Doug Peters
Doug Peters

Reputation: 529

How to tell powershell dir command to look a folder up?

The folder structure is:

--root
--root\source-code\
--root\powershell-scripts\

I need the method below that is inside the \powershell-scripts folder to target files inside \source-code:

function Test($param)
{
    dir -Include ASourceCodeFile.txt -Recurse |
    % { SomeMethod $_ $param }
}

What am I missing?

Upvotes: 1

Views: 9392

Answers (4)

John Dietrich
John Dietrich

Reputation: 1

this was a trick that I used in vbs that I converted to PS...

$scriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent

$a = $scriptPath.split("``\``") for ($i = 0 ; $i -lt $a.count-1 ; $i++){  
    $parentDir = $parentDir + $a[$i] <br>
    if($i -lt $a.count-2){$parentDir = $parentDir + "``\``"}

}

Write-Output $parentDir

Upvotes: 0

D.Verhoeven
D.Verhoeven

Reputation: 41

A bit late, but maybe still helpful for someone:

Directory structure :

MyRoot\script\scriptrunning.ps1

config:

MyRoot\config.xml

to read the xml file from scriptrunning.ps1:

[xml]$Config = Get-Content -path "${PSScriptRoot}\..\config\config.xml"

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

The $PSScriptRoot automatic variable contains the path of the directory in which the current script is located. Use Split-Path to find its parent (your --root) and Join-Path to get the path to the source-code folder:

Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'source-code'

$PSScriptRoot was introduced in PowerShell 3.0

Upvotes: 2

Dane Boulton
Dane Boulton

Reputation: 1325

if you have a script in --root\powershell-scripts\ and you want to reference something in --root\source-code\ or say get-content you can do this:

cd --root\powershell-scripts\
get-content '..\source-code\someFile.txt'

The ..\ references the parent directory which contains \source-code\ and then you reference or pull in file or scripts from that directory.

Upvotes: 1

Related Questions