简体   繁体   中英

Run powershell script as custom command inside cmd

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.

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 $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.

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; ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM