Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a new powershell cmdlet?

Tags:

powershell

I have just downloaded the Register-TemporaryEvent cmdlet from http://poshcode.org/2205 and placed it in my powershell profile directory near the $profile script.

How do I create a new command Register-TemporaryEvent which would be bound to this script?

Thanks.

like image 421
mark Avatar asked Jan 24 '12 13:01

mark


People also ask

How do I import a new PowerShell module?

In PowerShell 2.0, you can import a newly-installed PowerShell module with a call to Import-Module cmdlet. In PowerShell 3.0, PowerShell is able to implicitly import a module when one of the functions or cmdlets in the module is called by a user.

How do I manually import a PowerShell module?

To install PowerShell modules manually, you first need to determine your current PowerShell module directory path, download your new module to that path, and invoke the import-module command to let windows know it's there.

How do I run a cmdlet in PowerShell?

You can run it by typing powershell_iseor ise in the command line or by launching the Windows PowerShell ISE tool in the Server Manager.


2 Answers

With PowerShell, you can execute scripts as commands if they are placed in directories contained in the 'PATH' environment variable. To see what directories are in the Path, you can use:

$env:Path -split ';'| sort

You could modify the path permanently from Windows' System Properties to include the location of your scripts, or you could temporarily modify the path from within your profile or script. In your particular case, you could add the following to your profile to add the profile directory to the path:

$ScriptRoot = Split-Path $SCRIPT:MyInvocation.MyCommand.Path

if(($env:Path -split ';') -notcontains $ScriptRoot) {
    $env:Path += ';' + $ScriptRoot
}

You can then run the command as:

PS >$timer = New-Object Timers.Timer
PS >Register-TemporaryEvent $timer Disposed { [Console]::Beep(100,100) }

Note: When tab completing, it will complete as Register-TemporaryEvent.ps1, but you can remove the '.ps1' and it will still work.

like image 183
Rynant Avatar answered Sep 30 '22 07:09

Rynant


You can get the content of the script file, enclose it in a function and invoke the code to create the function.

$sb = Get-Content .\script.ps1 | Out-String
Invoke-Expression "function Register-TemporaryEvent {`n $sb `n} "
like image 22
Shay Levy Avatar answered Sep 30 '22 06:09

Shay Levy