My Technical Notes

Monday, 16 February 2015

PowerShell: Defining and Importing Modules

To define a module, we need to put it in a separate folder, within a modules directory. The modules directory is specified in the `$env:PSModulePath`:


PS C:\> $env:PSModulePath
C:\Users\Tahir\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\

For that matter, I keep my modules in the first directory. Below is a fictitious example of creating a module called `Clipboard`:

  • Go the the `Modules` directory and create a `Clipboard` folder and `Touch` (Touch definition) a module file with the same name, `Clipboard.psm1`:
    
    PS C:\> cd 'C:\Users\Tahir\Documents\WindowsPowerShell\Modules'
    PS C:\...\Modules>mkdir 'Clipboard'
    PS C:\...\Modules>cd 'Clipboard'
    PS C:\...\Modules\Clipboard>Touch 'Clipboard.psm1'
            
  • Paste the following code into the `Clipboard.psm1` file:
    
    function Get-ClipBoard {
        Add-Type -AssemblyName System.Windows.Forms
        $tb = New-Object System.Windows.Forms.TextBox
        $tb.Multiline = $true     
     $tb.Paste()
        $tb.Text
    }
    
    function Set-Clipboard {
        $str = $input | Out-String
        
        [Windows.Forms.Clipboard]::Clear();
    
        if ( ($str -ne $null) -and ($str -ne '') ) {
            [Windows.Forms.Clipboard]::SetText( $str )
        }
    }
    
    Export-ModuleMember -Function 'Get-Clipboard'
    Export-ModuleMember -Function 'Set-Clipboard'
    
  • Lastly, we add to our `$profile` file, a line of code to import this module:
    
    Import-Module 'Clipboard'
    

No comments: