Why are functions not available locally until the first launch?

I have two questions: why the following function in the script is not recognized when the script runs:

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 an error message:

 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 download and run it in Windows PowerShell ISE, it will give me an error for the first time, and then it will act as if it "registered" this function and works after that.

And in case this is a procedural problem, I tried to list the function at the top, not good luck.

Note I tried simple functions such as:

 Write-host "Say " Hello function Hello { Write-host "hello" } 

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

In addition, still not everyone works only with running a script in powershell (only in ISE after the first initial attempt).

+4
source share
1 answer

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

When you load it into PowerShell ISE, it will know what Select-Folder means when it first starts, and it will still know that the second time you try to start it (so you won’t get an error at that time).

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 

which should work every time it starts.

+12
source

Source: https://habr.com/ru/post/1386834/


All Articles