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
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
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:
. myfile.ps1 PowerShell create new scope when command resolved to be script file.myfile.ps1 resides in current directory, and current directory not in PATH environment variable, then PowerShell fail to find myfile.ps1 command.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.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.
powershell.exe -?help? It explains the main differences. If you are interested in subtle differences then this is not clear from the question.