After reading some solutions on dot sourcing and relative paths, and trying these I thought of something that might also be a solution. Use a drive letter.
If your scripts are on a server and you can make a network driveletter then make it to the root of your module. I use P: for this. If you working local you can use the old subst cmd to map a drive letter to a local folder. Also still in Windows 11.
If you use this technique the only thing to worry about is making the drive letter of your choice link to the root of the desired project/script folder.
If you’re not looking for help you may use another category next time. I think “Open Discussions / shell-business“ would be a good fit for topics like this.
<just my 2 cents>
IMHO drive letters are among the top worst ideas MSFT ever had in its history.
What would be the benefit of using a drive letter? What issue does it solve? … especially when working with modules?
My suggestion would be to avoid loading modules from network shares at all. Instead install it properly on the machine you need it on.
Olaf, you’re definitely not wrong. While he didn’t come with a question per say. He did come with excitement about something he learned and wanted to share. I think as a community if we harbored more of that it would be a better place for everyone to learn. yes he posted in the help side and not the discussion side, yes you are the admin and I have no say. However, if it helps you, it is one of the reasons I hang out more on PowerShell Reddit or Stackoverflow. yes I know you are an admin to some degree on their too, but I don’t know something is different about this place since Don left.
first i’d heard of subst, but I have kind of an OCD when writing PowerShell and attempt to only use native PowerShell cmdlets/functions whenever possible.
I think I’m still trying to understand the use case you’re talking about here. You said
make it to the root of your module
Are we talking about an actual PowerShell module like with .psd1 and .psm1 files? If that’s the case I’m not sure I understand the need. If my module is called “ProtectStrings” then in my .psd1 for the “RootModule” key I put “ProtectStrings.psm1” and it works. I don’t have to specify $PSScriptRoot or .\ or anything like that.
For relative paths provided to a parameter input I’ve used this type of methodology before:
Param (
[Parameter(Position = 0, Mandatory = $true)]
[ValidateScript({
if ( -not ($_ | Test-Path) ) {
throw "specific file does not exist"
}
if (-not ( $_ | Test-Path -Pathtype Leaf)) {
throw "The -FilePath argument must be a file: $_"
}
if (-not ($_.Extension -eq ".csv")) {
throw "The -FilePath value must be a .csv file: $_"
}
return $true
})]
[System.Io.FileInfo]$FilePath
)
if (-not $FilePath.Exists) {
# this means we were given a relative path. Resolve it to its full path
$ResolvedPath = Resolve-Path -Path $FilePath | Select-Object -Expandproperty ProviderPath
if ($ResolvedPath) {
[System.IO.FileInfo]$FilePath = $ResolvedPath
}
}