Rob
Rob

Reputation: 421

Calling a Powershell script with the "-command" parameter instead of "-file"

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

Upvotes: 1

Views: 1609

Answers (2)

user4003407
user4003407

Reputation: 22122

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.

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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

Upvotes: 5

Related Questions