Using a Helper Library from a powershell script that will be running via a SQl Agent job

  • Hi

    I am having a Powershell Script, A.ps1 that calls some functions from a Helper script HelperFunctions.ps1. In order to execute A.ps1 from console I make sure I have the helper script imported. I use the following code.

    .".\HelperFunctions.ps1"

    But my actual requirement is that the script A.ps1 be executed from a SQL Agent job. I execute it as an Operating system step:

    C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoProfile -WindowStyle Hidden -Command C:\Users\querty\Desktop\Scripts\A.ps1

    When I run the script via SQL Agent job, then referencing the helper library as .".\HelperFunctions.ps1" throws an error and I need to use the full path of the helper function(even if the main script and the helper are in the same location).

    Now, my problem is this SQL Agent job will be running in multiple production servers. I do not know where the actual scripts will be placed and so I cannot hardcode and mention it inside the main script.

    I want a way to reference the helper script in the main script without mentioning the full path as this might change from server to server.

    One way of doing it is by passing it as a parameter but I want to keep it as a last option. Any other way I can reference the helper script directly from the main without caring about the actual path?

    Thanks and Regards

    Saptarshi Chaudhuri

  • Replying to my own question. Basically this can be done the following way:

    <#--Get the path where the script is running--#>

    $scriptRoot = Split-Path (Resolve-Path $myInvocation.MyCommand.Path)

    <#--Assuming all the common helper libraries are in the same folder as the main script, do the following--#>

    <#--DatacenterHealthCommonLibrary is just an example library--#>

    $common = join-path $scriptRoot "DatacenterHealthCommonLibrary.ps1";

    <#--Reference it--#>

    .$common;

    There are other ways to do it as well as I found upon investigation. One being convert the library to a script module and then import it using the import-Module. Obviously this would require an additional module installation step before 🙂

    Cheers 😀

    Saptarshi

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply