2
votes

How can I run a PowerShell script as a custom command from cmd or powershell.

For example my script (CreateFile.ps1):

function CreateFile ($fileName) {
    New-Item -Name $fileName -ItemType "file"    
}

CreateFile($args[0])

I would like to use the script in cmd\powershell with a custom command (here as "CF"):

C:\some folder> CF testfile.txt

I added a new system environment variable with a link to my ps1 file. But it won't work, even after a reboot.

2

2 Answers

0
votes

If you want to use 'CF filename' in PowerShell and cmd I suggest you use in cmd a batch file placed somewhere in your path:

:: CF.cmd create file %1 with 0 length
@Type Nul >"%~1"

And put a function in one of your PowerShell profiles $PROFILE | Format-List -Force

function CF ($fileName) {
    New-Item -Name $fileName -ItemType "file"    
}

So you have the same command but executed in their respective environment.

0
votes

I added a new system environment variable with a link to my ps1 file.

From outside of PowerShell its scripts (*.ps1) are by design not directly executable (unlike batch files (*.cmd, *.bat), so making *.ps1 scripts available via $env:PATH is not sufficient if you want to call them from cmd.exe

However, you can write a simple, auxiliary wrapper batch file that invokes your script explicitly via powershell.exe:

In one of the folders listed in $env:PATH:

  • create batch file CF.cmd with the following content:

    @powershell.exe -NoProfile -File "%~dp0CreateFile.ps1" %*
    
  • copy CreateFile.ps1 to the same folder, but remove the function wrapper so that the calling the script invokes the functionality directly; i.e., make its content the following:

    param($FileName)
    
    New-Item -Name $FileName -ItemType File
    

You will then be able to call CF (CF.cmd) from both cmd.exe and PowerShell. From within PowerShell, however, calling CreateFile (CreateFile.ps1) directly is more efficient.