简体   繁体   中英

Execute a powershell function directly in powershell command prompt

How can i execute a powershell function directly in a powershell command prompt as follow

>>PS C:\Users\tijo.scaria> Function Test-Demo
>> {
>> Param ($Param1)
>> Begin{ write-host "Starting"}
>> Process{ write-host "processing" $_ for $Param1}
>> End{write-host "Ending"}
>> }

How can i call this function. i tied by pressing CNTRL+C and get out of the function and tried following command

>>PS C:\Users\tijo.scaria> Echo Testing1, Testing2 | Test-Demo Sample

but i got the following error

Test-Demo : The term 'Test-Demo' is not recognized as the name of a cmdlet, function, script file, or operableprogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:27+ Echo Testing1, Testing2 |Test-Demo Sample

How can i execute a function directly from Command window

Your problem was pressing control-C to abort the function definition instead of completing it by pressing return:

PS C:\Windows\system32> function Test-Demo
>> {
>> Param ($Param1)
>> Begin { Write-Host "Starting" }
>> Process { Write-Host "Processing" $_ for $Param1 }
>> End { Write-Host "Ending" }
>> }
>>
PS C:\Windows\system32> Test-Demo "Hello"
Starting
Processing  for Hello
Ending

If you want to play with function definitions interactively though you should use Powershell ISE v3 or later. It makes these things much easier (in ISE you can enter multi-line commands with shift-return and then pull them back as a single coherent command, edit, insert and delete lines) or just type in the file window and execute any selected group of lines).

So in Powershell ISE v3:

PS C:\> function Test-Demo
{
 Param ($Param1)
 Begin { Write-Host "Starting" }
 Process { Write-Host "Processing" $_ for $Param1 }
 End { Write-Host "Ending" }
}

PS C:\> Test-Demo "Hello"
Starting
Processing  for Hello
Ending

PS C:\> 

and then up-arrow twice brings back the entire function definition.

I think you must create a PS1 file that contains that function. Then simply load that file and call the function you developed:

. "FunctionFile.ps1"
Test-Demo "Testing1"

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