Home > OS >  Not able to use a function from another powershell file
Not able to use a function from another powershell file

Time:03-15

I have the main.ps1 file where I am importing another file $dirpath\new.ps1 as below:

Import-module $dirpath\new.ps1 -force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
try {
    $getval = invoke-command -cn $host -Credential $cred -ScriptBlock {
    param($name)    
    get-myfunc $name
    } -ArgumentList $name
    
} catch { 
    ...
    }

Both main.ps1 file and new.ps1 are existing under the same directory - $dirpath.

The new.ps1 looks as below:

Function global:get-myfunc{
PARAM(
    [Parameter(Mandatory=$true,Position=0)][STRING]$name
)
    write-host "$name"

}

Now, the main.ps1 file is throwing below error:

      $getval = invoke-command -cn $host -Credential $cred -S ...
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (get-myfunc:String) [], CommandNotFoundException
      FullyQualifiedErrorId : CommandNotFoundException

I have tried renaming new.ps1 as new.psm1 then importing module as Import-module $dirpath\new.psm1 but it is still failing with same error.

I am using poweshell 5

CodePudding user response:

First issue

The new.ps1 file isn't a module, just a regular script, so you can't/shouldn't use Import-Module for that.

Modules are not simply scripts with a different extension. For more information, see:

If you want to keep the current setup, dot source the script by replacing the Import-Module line with:

. $dirpath\new.ps1

This will execute the script and make define the function in the current scope.

If the script is located in the same folder as the calling script, you can further simplify the statement by using $PSScriptRoot:

. $PSScriptRoot\new.ps1

Second issue

Invoke-Command means you're running a scriptblock on a different host, which implies that it uses a different scope. That's why it can't find the get-myfunc function.

The modifying your statement to:

Invoke-Command 
    -ComputerName $host `
    -Credential $cred `
    -ScriptBlock ${Function:get-myfunc} `
    -ArgumentList $name

For a more detailed explanation, see Run Local Functions Remotely in PowerShell.

CodePudding user response:

That Won't work, because you are importing that Module into your local machine. But, the below command is executing in remote machine. That means you need install that module in remote machine and then you can use that module in the remote machine.

$getval = invoke-command -cn $host -Credential $cred -ScriptBlock { param($name)
get-myfunc $name

Please follow below link for the solution

  • Related