Today I needed to call another script file in the same folder as the main script. After a little searching on the web I found "$MyInvocation.MyCommand.Path". "$MyInvocation.MyCommand.Path" returns the path to the current script, With that I was able to get the current folder using Get-Item. This is my test scripts:
ToRun.ps1:
Write-Host $MyInvocation.MyCommand.Path
$scriptDirectory = (Get-Item $MyInvocation.MyCommand.Path).DirectoryName
$scriptName = "HelloWorld.ps1"
Write-Host calling $scriptName in $scriptDirectory
& ($scriptDirectory + '\' + $scriptName)
HelloWorld.ps1:
Write-Host "Hello word"
After running the script the output was:
calling HelloWorld.ps1 in C:\scriptFun
Hello word
Simple but useful.
ToRun.ps1:
Write-Host $MyInvocation.MyCommand.Path
$scriptDirectory = (Get-Item $MyInvocation.MyCommand.Path).DirectoryName
$scriptName = "HelloWorld.ps1"
Write-Host calling $scriptName in $scriptDirectory
& ($scriptDirectory + '\' + $scriptName)
HelloWorld.ps1:
Write-Host "Hello word"
After running the script the output was:
calling HelloWorld.ps1 in C:\scriptFun
Hello word
Simple but useful.
Comments