How to Call Selected Function From PowerShell File

There are two approaches

1st we can call from another .ps1 file

If we have PowerShellFile1.ps1 and it contains the definition of more than one function then we need to create another File PowerShellFile2.ps1 and we just call the selected function from it.

2nd we can call it from command line

We just have to Find that function and call it from the command line.

1st approach

Here is file FindandReplace.ps1 which contains many definitions of the functions and we just want to call one of the functions.

1.JPG

Now we have to create one more file to call the function. I have created a file call Function.ps1.

2.JPG

The code in the callFunctio.ps1 image is not readable so I have inserted the code here:

 .\FindandReplace.ps1

 $filepath ='abc.txt';

$findstr = 'StringtoFind';
$replacestr = 'StringtoReplace';
 MyFunction -fileName1 $filepath -findStr $findstr -replaceStr1 $replacestr // call the function 

 

2nd approach

We need to find our function so for that we can write this command "Dir Function:\m*"

3.JPG

If you are not able to find your function or you want to call the function then you need to load your .ps1 file which contains the definition of the function; try this command: ". Full path\filename.ps1".

4.JPG

Then search the function again; you will get that function in the results. To load this file we have to put '.' in the beginning of the fullpath and filename; see the above image. 

Now you just have to call the function. Try this command, you can declare the variable you want to pass to the function; see the image. In the following image I have created 3 variables to pass to the function:

1st  $filepath ='';

2nd $findstr ='';

3rd  $replacestr='';

Then I have call the function with the arguments.

To call the function with arguments we need to specify the variable name and then its value.

Syntax to call the function:

FunctionName -args1 $args1value  –args2  $args2value

To call the Function "MyFunction -fileName1 $filepath -findStr $findstr -replaceStr1 $replacestr"

5.JPG

Thank you. If you want the both .ps1 files then download the code.

Up Next
    Ebook Download
    View all
    Learn
    View all