1

What is the difference between calling a powershell script like this:

powershell.exe -file "myfile.ps1"

and like this (which also works):

powershell.exe -command "myfile.ps1"

thanks, robert

2
  • Did you take a look at powershell.exe -? help? It explains the main differences. If you are interested in subtle differences then this is not clear from the question. Commented May 21, 2015 at 12:03
  • Of course i looked into the help. I was suprised "-command" even works in the way i wrote above, because it is not documented. The question is, is there any difference in how the script is executed. For example it seems, terminating errors do not work as expected in the second case. But i am not sure. I can not ask any more detailed because i dont know any more details. :) Commented May 21, 2015 at 12:59

2 Answers 2

5

Running powershell.exe -File will return the exit code set by the script, whereas running powershell.exe -Command will return 1 if the script terminated with a non-zero exit code, or 0 otherwise.

C:\>type "C:\path\to\test.ps1"
exit 5

C:\>powershell.exe -command "C:\path\to\test.ps1"

C:\>echo %errorlevel%
1

C:\>powershell.exe -file "C:\path\to\test.ps1"

C:\>echo %errorlevel%
5
Sign up to request clarification or add additional context in comments.

1 Comment

Added this to PowerShellTraps as Exit-code-5-with-File-1-with-Command
2

powershell.exe -file "myfile.ps1" — that means: start PowerShell and execute file myfile.ps1 (file name considered to be relative to current directory) in global scope.
powershell.exe -command "myfile.ps1" — that means: start PowerShell and execute command myfile.ps1, and PowerShell allows you to execute script files by typing their names in command line.

Differences:

  1. In absence of dot source operator . myfile.ps1 PowerShell create new scope when command resolved to be script file.
  2. PowerShell does not look in current directory as source of commands. So if file myfile.ps1 resides in current directory, and current directory not in PATH environment variable, then PowerShell fail to find myfile.ps1 command.
  3. If file myfile.ps1 can be found in any directory mentioned in PATH environment variable before current directory, then myfile.ps1 command will be resolved to that file rather then to file myfile.ps1 in current directory.
  4. You can create alias in you profile like New-Alias myfile.ps1 DoSomethingElse, and in this case myfile.ps1 command will be considered as reference to that alias rather then to myfile.ps1 file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.