2

I am wondering how to get the location of the script I am running or writing. We have a set of .NET assemblies placed in the same directory as the current PowerShell script, and we want load them from the script. Right now I am using a fixed path to locate assemblies, but we want to load them from the current file location.

[System.Reflection.Assembly]::LoadFrom
("C:\Work\Scripts\Assemblies\DynamicOps.ManagementModel.Client.dll")

[System.Reflection.Assembly]::LoadFrom
("C:\Work\Scripts\Assemblies\DynamicOps.Repository.dll")
1

2 Answers 2

12
$MyInvocation

Contains an object with information about the current command, such as a script, function, or script block. You can use the information in the object, such as the path and file name of the script ($myinvocation.mycommand.path) or the name of a function ($myinvocation.mycommand.name) to identify the current command. This is particularly useful for finding the name of the script that is running. You'll get full help on automatic varible with about_Automatic_Variables :

get-help about_Automatic_Variables -full

(Edited) To get current directory you've got the CmdLet Get-Location

Sign up to request clarification or add additional context in comments.

3 Comments

thanks JPBlanc! I tried with split-Path and it worked. $currentFileLocation = Split-Path $MyInvocation.MyCommand.Path
I moved $currentFileLocation = Split-Path $MyInvocation.MyCommand.Path line of code to function and it does not work. It throws an error while running a script , any suggestions? PS C:\Windows\system32> C:\Work\Scripts\GetVirtualMachineProvisiongGroup.ps1 Write-Error : Cannot bind argument to parameter 'Path' because it is null.
$MyInvocation is an automatic variable. If you write a function to do this, you need to grab the $MyInvocation from the parent scope. Read this article (blogs.msdn.com/b/powershell/archive/2007/06/19/…).
2

$MyInvocation.MyCommand.Path maybe?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.