Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell alias inside function not available outside

I have a powershell function inside a file myfunc.ps1

function Set-Util ($utilPath ) {

    if(Test-Path($utilPath) ){
      $fullPath = Join-Path -Path $utilPath "util.exe"
      set-alias MyUtil $fullPath
      #echo  "Path set to $fullPath"
    }else {
        throw  (" Error: File not found! File path '$fullPath' does not exist.")
    }
}

and I dot call it from command line with

. .\myfunc.ps1

then call

Set-Util somedirectory

The alias is being set correctly in the function, but I can't access it out here with

MyUtil

Should I export the alias because the scope is only in the method? I tried doing so with Export-ModuleMember but got an error saying the cmdlet can only be called from insdie a module.

like image 227
Vort3x Avatar asked Nov 28 '25 22:11

Vort3x


1 Answers

You can't do that because the alias won’t be set until the function is called, and when the function is called the alias is scoped to the function scope, so when the function finishes running - the alias is gone.

If you want the alias to survive, specify use scope parameter with a value of 'global'

like image 84
Shay Levy Avatar answered Dec 01 '25 19:12

Shay Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!