pghtech
pghtech

Reputation: 3702

Why functions are not available locally until after first ran?

I have two questions here, why does the following function in a script not recognized when I run the script:

Script:

$pathN = Select-Folder
Write-Host "Path " $pathN

function Select-Folder($message='Select a folder', $path = 0) { 
  $object = New-Object -comObject Shell.Application  

  $folder = $object.BrowseForFolder(0, $message, 0, $path) 
    if ($folder -ne $null) { 
        $folder.self.Path 
    } 
} 

I get error:

The term 'Select-Folder' 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 aga

in.

But if I load and run it in the Windows Powershell ISE, it will give me the error the first time, and then act like it has "registered" the function and work after that.

And in case it is a procedural issue, I have tried listing the function at the top with no better luck.

Note I have tried simple functions like:

Write-host "Say "
Hello

function Hello {
  Write-host "hello"
}

With the same exact results/error, it complains that Hello is not function....

Also, it still won't every work just running the script in powershell (only in ISE after the first initial attempt).

Upvotes: 4

Views: 7449

Answers (1)

Wilka
Wilka

Reputation: 29593

You need to declare your Select-Folder function before you try to use it. The script is read from top to bottom, so on the first pass when you try to use Select-Folder it has no idea what that means.

When you load it into the Powershell ISE it'll find out what Select-Folder means on the first run, and it'll still know that the 2nd time you try to run it (so you won't get the error then).

So if you change your code to:

function Select-Folder($message='Select a folder', $path = 0) { 
  $object = New-Object -comObject Shell.Application  

  $folder = $object.BrowseForFolder(0, $message, 0, $path) 
    if ($folder -ne $null) { 
        $folder.self.Path 
    } 
} 

$pathN = Select-Folder
Write-Host "Path " $pathN

that should work each time you run it.

Upvotes: 13

Related Questions