I have a script with a number of functions (not just functions but also other code). I would like to create another script that uses one of the functions in the main script. Here is a sample of what I am trying to do. In my test.ps1 script:

function Test1 {Write-Host “This is test1”} function Test2 {Write-Host “This is test2”} Test1 Test2 

And inside of the testtest.ps1 script:

. ".\test.ps1" Test1 

When I run test.ps1, the output is:

This is test1 This is test2 

When I run testtest.ps1, the output is:

This is test1 This is test2 This is test1 

All I want to do is to call the Test1 function in my test.ps1 script from my testtest.ps1 script. One of my conditions is that we not change the test.ps1 script (due to permission issues, read versus write folder access) and I don't want to duplicate script code (which is why I'm trying to reuse code).

I can't find the solution that I need, everyone talks about dot-sourcing with PowerShell. So is dot-sourcing the proper way to do this or is there some other way to use (only) a function from another PowerShell script without running the remaining code in that script?

Thanks

7

1 Answer

I figured out a way to do this so I'll post it in case it helps anyone else. Granted I did have to edit the original PS script but the changes made are negligible and they don't impact the primary processing of the script at all.

Contents of the test.ps1 script:

Param ([int]$Local) function Test1 {Write-Host “This is test1”} function Test2 {Write-Host “This is test2”} If ($Local -eq 1) {Exit} Test1 Test2 

Contents of the testtest.ps1 script:

. ".\test.ps1" -Local 1 Test1 

When I run test.ps1, I get:

This is test1 This is test2 

But now (with the changes made), when I run testtest.ps1, I get:

This is test1 

This way, the script has loaded the functions from test.ps1 into memory (so that they can be used) but it doesn't process any part of the remainder of the script (because we Exit). Now I can use the functions located in this script if I want without affecting the processing of the original source script.

Thanks to all for the feedback!!

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy