How to call a function in another file ?

Welcome Forums General PowerShell Q&A How to call a function in another file ?

Viewing 4 reply threads
  • Author
    Posts
    • #208800
      Participant
      Topics: 8
      Replies: 8
      Points: 93
      Rank: Member
      # file library.ps1
      
      Function enviar {
      
      param($para)
      
      Write-Host $para
      
      }
      
      # file command.ps1
      
      enviar "Hello"
      • This topic was modified 2 months, 4 weeks ago by vpmaciel67.
    • #208809
      Participant
      Topics: 4
      Replies: 2248
      Points: 5,490
      Helping Hand
      Rank: Community MVP
      # file library.ps1
      
      Function enviar {
      
      param($para)
      
      Write-Host $para
      
      }
      
      # file command.ps1
      . .\library.ps1
      enviar "Hello"
    • #208815
      Participant
      Topics: 12
      Replies: 1623
      Points: 2,565
      Helping Hand
      Rank: Community Hero

      A “library” is a basically a Powershell module.

      https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_modules?view=powershell-7
      https://docs.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-script-module?view=powershell-7

      Another option is dot sourcing, like this

      # file enviar.ps1
      
      Function enviar {
      
      param($para)
      
      Write-Host $para
      
      }
      
      # file command.ps1
      
      .\enviar.ps1 "Hello"
      

      If it’s something that you use all of the time, you can also use a Powershell profile to keep common functions available when the Powershell session loads on you’re main computer.

      PowerShell Profiles

    • #208833
      Participant
      Topics: 4
      Replies: 2248
      Points: 5,490
      Helping Hand
      Rank: Community MVP

      Another option is dot sourcing, like this

      Are you sure that would work this way? I’d expect this way you provide the parameter to the script and not to the contained function.

    • #208866
      Participant
      Topics: 12
      Replies: 1623
      Points: 2,565
      Helping Hand
      Rank: Community Hero

      Are you sure that would work this way? Iā€™d expect this way you provide the parameter to the script and not to the contained function.

      @Olaf, I’m not sure I even be talking to you, I see above your thread has been reported šŸ˜‰

      You are correct, it would be more like this:

      # file enviar.ps1
      
      param($para)
      
      Write-Host $para
      
      
      # file command.ps1
      
      .\enviar.ps1 "Hello"
      

      I typically would still lean towards a Module, but you could load a script into memory to load functions.

Viewing 4 reply threads
  • You must be logged in to reply to this topic.