4

Given the following say-hello.ps1 file on my file system:

function SayHello()
{
    return "Hello World!"
}

called on the command line like so (it will eventually run as a Windows Scheduled Task):

powershell -ExecutionPolicy unrestricted -command "& { c:\say-hello.ps1; SayHello }"

Why am I getting the following result?

SayHello : The term 'SayHello' 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.
At line:1 char:33
+ & { c:\say-hello.ps1; SayHello }
+                       ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (SayHello:String) [], CommandNot
   FoundException
    + FullyQualifiedErrorId : CommandNotFoundException

1 Answer 1

7

The scope of the script file c:\say-hello.ps1 ends when the script terminates. You can dot source the file (note the . before the PS1) if you would like its contents to run within the current scope -- the script block enclosed with curlies {...}:

powershell -ExecutionPolicy unrestricted -command "& { . c:\say-hello.ps1; SayHello }"
Sign up to request clarification or add additional context in comments.

3 Comments

I have a function calling from powershell like this: Expand-ZIPFile –File “E:\MYDOC.zip” –Destination “E:\New MYDOC” It's fine by powershell but while doing from command line by the above method it gives error "Missing expression after unary operator '_'. Any suggestion.
You seem to have both "prettified" dashes and quotes in your example: , , . I would try with cmd again using the ASCII - and ".
I have a function: function Expand-ZIPFile($file, $destination) { $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($item in $zip.items()) { $shell.Namespace($destination).copyhere($item) } }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.