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

Welcome Forums General PowerShell Q&A How to load the PowerShell script that was in different directory while executin

This topic contains 5 replies, has 2 voices, and was last updated by

 
Participant
2 years, 3 months ago.

  • Author
    Posts
  • #51070

    Participant
    Points: 0
    Rank: Member

    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

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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"

The topic ‘How to load the PowerShell script that was in different directory while executin’ is closed to new replies.