How to load the PowerShell script that was in different directory while executin

Tagged: 

This topic contains 5 replies, has 2 voices, and was last updated by  Krishna Chaitanya 1 year ago.

  • Author
    Posts
  • #51070

    Krishna Chaitanya
    Participant

    I am having my .ps1 saved in directory1 and mt .tests.ps1 in directory2 with in the same folder.
    Folder view
    In general we use to write the script as follows when the test file and script file are in the same folder

    $here = Split-Path -Parent $MyInvocation.MyCommand.Path
    $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
    . "$here\$sut"

    But I am having them in different folder, so how can I load the path so that the script file should get loaded

  • #51091

    Daniel Krebs
    Moderator

    Example of a solution for your question:

    $here = Split-Path -Parent $MyInvocation.MyCommand.Path
    $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace('.Tests.ps1','.ps1')
    . "$(Join-Path -Path $here -ChildPath "..\Pester\$sut" -Resolve)"
    
  • #51094

    Krishna Chaitanya
    Participant

    Getting the following error

    Join-Path : Cannot find path 'D:\PowerShell\Pester\TestPester\Pester\PowerShellTest1.tests.ps1' because it does not exist.
    At D:\PowerShell\Pester\TestPester\MyProject.Tests\PowerShellTest1.tests.ps1:3 char:6

  • #51098

    Daniel Krebs
    Moderator

    I'm sure you can find out yourself. The code is not really complex. Most likely the folder layout is different from what you've posted earlier or you've removed the .. in my example.

    Good luck.
    -Daniel

  • #51100

    Krishna Chaitanya
    Participant

    I have written as per you posted, My .ps1 is in A folder and my test script in B folder, I believe the code you have given is searching in current directory B instead of A

  • #51147

    Krishna Chaitanya
    Participant

    I have achieved as follows

    $project = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace(".Tests", "")
    $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".tests.", ".")
    . "$project\$sut"

You must be logged in to reply to this topic.