Sune
Sune

Reputation: 3270

How can I call a file from the same folder that I am in (in script)

I would like to call script B from script A without specifying the complete path. I've tried with

.\scriptb.ps1

but that doesn't work. Do I really have to specify the entire path?

(sorry for this quite basic question, but google couldn't help me!)

Upvotes: 32

Views: 58853

Answers (8)

Hoppjerka
Hoppjerka

Reputation: 206

You're almost there.

👎 What you did:

.\scriptb.ps1

👍 What will do:

. .\scriptb.ps1

Upvotes: 1

gryphonB
gryphonB

Reputation: 89

Payette's book Posh in Action says this works:${c:File.txt}

He describes it as:

“Return the contents of the file File.txt from the current working directory on the C: drive.”

In contrast, ${c:\File.txt} says,

“Get the file File.txt from the root of the C: drive.”

Which is fine for Windows. I'm on Linux & trying to find out how to turn the same trick.

So glad to have powershell back in my life.

Upvotes: 0

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

I have come upon this question, after I found out that executing a Powershell script from a batch file produced failure of "includes" like .\config.ps1.

One way to make it work is:

$configFullPath = "$($pwd)\config.ps1"
Write-Host "Config file full path = $configFullPath"

#force is required just to make sure that module is not used from cache
Import-Module -Force $configFullPath

Upvotes: 0

toshi
toshi

Reputation: 566

i use the powershell variable which has an easy name to remember what is it for.

$PSScriptRoot\scriptb.ps1

Upvotes: 36

superjos
superjos

Reputation: 12705

Inside your main script, script A:

$thisScriptDirectoryPath = Split-Path -parent $MyInvocation.MyCommand.Definition

$utilityScriptName = "ScriptB.ps1"
$utilityScript = (Join-Path $thisScriptDirectoryPath $utilityScriptName)

$result = . $utilityScript "SomeParameter"

Upvotes: 0

mjolinor
mjolinor

Reputation: 68283

How about this:

& $pwd\scriptb.ps1

Upvotes: 6

Tomas Panik
Tomas Panik

Reputation: 4609

it is possible using $MyInvocation as follows:

$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$scriptPath = Join-Path $executingScriptDirectory "scriptb.ps1"
Invoke-Expression ".\$scriptPath" 

Upvotes: 17

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

.\ is relative path. It's relative to where you currently are. For example, if you are in c:\, but calling script d:\1.ps1 then .\ will be drive c:

There're some more tricks to it. You can change your location from script, using cd for example

.\ will work like you want it to if you will go to location where the file physically is and run it from there.

Upvotes: 0

Related Questions