locked
Running a function from a powershell script from the command line RRS feed

  • Question

  • Rather than creating several scripts each with one function, I have one script with has several functions.... I would like to call the script and select the function i want to use from the command line.

    so far, if i change directory to that of the script i can call the function by doing this:

    cd c:\myscripts

    . .\mytestscript.ps1; myfunction

    this works fine.... i have also tried, what I would like to achieve is calling it like this

    c:\myscripts\mytestscript.ps1; myfunction

    however, i am trying to run this as part of an MDT task sequence, my command line looks like this and using the ; myfunction at the end doesn't work.

    powershell.exe -ExecutionPolicy Bypass %SCRIPTROOT%\CustomScripts\mytestscript.ps1; myfunction

    how can i adapt my command line so that it will successfully call the function within my script?

    thanks

    Steve

    • Moved by Bill_Stewart Monday, October 27, 2014 3:58 PM Abandoned
    Sunday, August 17, 2014 3:14 PM

All replies

  • You could need to dot-source the function:

    powershell.exe -ExecutionPolicy Bypass -Command ". '%SCRIPTROOT%\CustomScripts\mytestscript.ps1'; myfunction"

    The quotation marks I added are just to make sure everything works properly even with paths that contain spaces, etc. It's the period operator at the beginning of the command that is most important

    Sunday, August 17, 2014 3:38 PM
  • this is strange, what you suggested works for a UNC referenced script, but in the actual command line i need to use it in as above, it does not.

    any other suggestions to how I can do this? perhaps there is another way to construct the command line?

    thank you

    Steve

    Sunday, August 17, 2014 5:11 PM
  • Rename the file from ps1 to psm1 and create a powershell module that contain multiple functions. A module will autoload like the built-in modules.

    Placement of the psm1 file is important for Powershell to find and autoload it.

    The file name and folder name must be the same, for example MyModule.psm1 should be in the folder:

    user\documents\windowspowershell\modules\mymodule

    Windows PowerShell Modules
    http://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx


    PS C:\> get-childItem env:PSModulePath
    
    Name                           Value                                                                                                   
    ----                           -----                                                                                                   
    PSModulePath                   C:\Users\User\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\   
    



    Sunday, August 17, 2014 11:00 PM
  • T import module "MyModule" from an arbitrary path:

    Import-Module -Name c:\scripts\MyModule.psm1


    ¯\_(ツ)_/¯

    Sunday, August 17, 2014 11:13 PM