martin
martin

Reputation: 31

How can you run a powershell script if you do not know the location is will be run from?

I am new to powershell so this may just be me not understanding something.

I am writing a tool in powershell and have the tool working in c:\Users\Documents\WindowsPowerShell\Modules.

What I would like is the ability to copy the tool to a USB stick and run it from the USB stick.

How can I get the tool to run if its not in the PSModulePath environment variable path?

Or how can I add the USB stick added to the PSModulePath path?

Upvotes: 0

Views: 274

Answers (2)

codewario
codewario

Reputation: 21418

If you want your script to be portable, you will have to carry around the dependent module with you as well. However, in your script, you can make sure to add the full path to the module's parent directory on your USB to the PSModulePath as a process-level environment variable:

$portableModuleDirectory = [System.IO.DirectoryInfo]'./relative/path/to/dependent/module'
$env:PSModulePath += ";$(Split-Path -Parent $portableModuleDirectory.FullName)"
Import-Module ModuleName

However, this is cumbersome to have to do. The best solution here would be to host your own internal nuget feed to push your package to, so you can install the module on any machine you need it on from your network, if you can't upload it to the public PowerShell Gallery (which you should host your own feed/squid proxy for business needs).

Upvotes: 1

martin
martin

Reputation: 31

Thanks for the help. I have a solution that works by placing the following in a .ps1 script and using that to import the dependent modules and call the first function.

#find local directory 
$LocalDir = Split-Path $MyInvocation.MyCommand.Path -Parent

#prove correct directory found.
Write-Host "Starting module load: $($MyInvocation.MyCommand) in directory = $LocalDir"
#load modules
Import-Module $LocalDir/Module –Force

#call first function
firstfunction

I could not get $PSScriptRoot to work but the Split-Path $MyInvocation.MyCommand.Path –Parent code has the advantage in that it also works in ISE. I then placed the dependent modules in directories below the .ps1 script.

Upvotes: 1

Related Questions