Flayshon
Flayshon

Reputation: 373

How to create a cmd/PowerShell alias that can be used with arguments

I wanna be able to execute the following command without having to type that much

php E:\zftool\zftool.phar create project E:\test

So I created a zf.cmd file containing this

php E:\zftool\zftool.phar %1 %2 %3

But when I enter

zf create project E:\test

It only executes the alias

php E:\zftool\zftool.phar

Any ideas on how can I fix that? Thanks in advance.

================================================================================

[Edit]:

The solution proposed by JPBlanc solved my problem, but if you create the function at runtime you'll lost its definition after closing PowerShell window.

To make it persist for every session, you have to add that function to your profile:

  1. Open Windows PowerShell.

  2. Enter notepad $profile command. If it opens an empty unnamed file, then you should close it and create a new $profile with New-Item -path $profile -type file command.

  3. Paste your function code inside the file you've just created, save it and you're ready to go.

If receive any error messages like

"File cannot be loaded because the execution of scripts is disabled on this system"

that can be fixed by entering

Set-ExecutionPolicy Unrestricted or Set-ExecutionPolicy Unrestricted -Force

Upvotes: 2

Views: 1027

Answers (3)

Earl
Earl

Reputation: 1

There is one thing missing up there: the 'function' keyword that defines the code block as a function.

function zf ($p1, $p2, $p3) {
    #your code here
}

Upvotes: 0

Mark
Mark

Reputation: 3690

If that's the entirety of your batch file, it should work fine. What is the output on the command line? With echo on, it should display what it's trying to run.

My first thought, though, as to why it might not work is that perhaps when it's calling php, you have a php.cmd file in your path earlier than your php.exe, and that php.cmd only passes the first argument (i.e., it only has a line like php.exe %1).

In your batch file, try explicitly running php.exe and see if that helps.

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72630

In your case I would not use a .cmd file. I would create a PowerShell function zf with 3 parameters. The zf function will use Invoke-expression CmdLet or &.

zf ($p1, $p2, $p3)
{
  [string]$pathToPHPExe = "C:\PHP\PHP.exe"
  [string]$pathToFILE = "E:\zftool\zftool.phar"
  [Array]$arguments = $pathToFILE, $p1, $p2, $p3

  & $pathToPHPExe $arguments
}

Upvotes: 2

Related Questions