问题描述:

I have a main script that I am running. What it does is read through a directory filled with other powershell scripts, dot includes them all and runs a predefined method in each made up of the first portion of the dot delimited file name. Example:

  1. Run master.ps1
  2. Master.ps1 dot sources .\resource\sub.ps1
  3. Sub.ps1 has defined a function called 'dosub'
  4. Master.ps1 runs 'dosub' using Invoke-Expression

Also defined in sub.ps1 is the function 'saysomething'. Implemented in'dosub' is a call to 'saysomething'.

My problem is I keep getting the error:

The term 'saysomething' is not recognized as the name of a cmdlet,

function, script file, or operable program. Check the spelling of the

name, or if a path was included, verify that the path is correct and

try again.

Why can't the method 'dosub' find the method 'saysomething' which is defined in the same file?

master.ps1:

$handlersDir = "handlers"

$handlers = @(Get-ChildItem $handlersDir)

foreach ( $handler in $handlers ) {

. .\$handlersDir\$handler

$fnParts = $handler.Name.split(".")

$exp = "do" + $fnParts[0]

Invoke-Expression $exp

}

sub.ps1:

function saysomething() {

Write-Host "I'm here to say something!"

}

function dosub() {

saysomething

Write-Host "In dosub!"

}

网友答案:

Your code works on my system. However you can simplify it a bit:

$handlersDir = "handlers"

$handlers = @(Get-ChildItem $handlersDir)
foreach ( $handler in $handlers ) 
{
    . .\$handlersDir\$handler

    $exp = "do" + $handler.BaseName
    Write-Host "Calling $exp"
    & $exp
}

Note the availability of the BaseName property. You also don't need to use Invoke-Expression. You can just call the named command ysing the call (&) operator.

网友答案:

What you have given works as needed. You probably don't have the directories etc proper on your machine. Or you are running something else and posting a different ( working!) code here.

You can also make following corrections:

. .\$handlersDir\$handler

instead of above you can do:

. $handler.fullname

Instead the splitting of the filename you can do:

$exp = "do" + $handler.basename
相关阅读:
Top