1
votes

I wrote my first cmdlet.

.\Scripts\Modules\NewShare\New-Share.psm1

When I add .\Modules to $env:PSModulePath and I import the module, then I can retrieve the help, but I am not able to execute it.

$evn:psmodulepath = C:\Users\bp\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;.\Modules;

When I run the script

New-Share -foldername 'C:\MyShare' -sharename 'MyShare'

I get the following standard error, as the module doesn't exist.

The term 'New-Share' is not recognized as the name of a cmdlet, function, script file, or operable program. 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:10 + New-Share <<<< -foldername 'C:\MyShare' -sharename 'MyShare' + CategoryInfo : ObjectNotFound: (New-Share:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

What is the problem?

My powershell module below.

function New-Share
{ 
    <#
        .Synopsis
        This function create a new share
        .Description
        This function creates a new share. If the specified folder does not exist, it will be created, and then shared with the specified share name.
        .Example
        New-Share -foldername 'C:\MyShare' -sharename 'MyShare'
        Creates the share with name 'MyShare' for folder 'C:\MyShare'.
        .Parameter foldername
        The folder that needs to be shared. Will be created if it does not exist.
        .Parameter sharename
        The name for the share.
        #Requires PowerShell 2.0
    #>
    [CmdletBinding()] 
     Param (
        [Parameter(Position=0, Mandatory=$True)] 
        [alias("fn")] 
        [string]$foldername, 
        [Parameter(Position=1, Mandatory=$True)] 
        [alias("sn")]
        [string]$sharename
        ) 

    if (!(test-path $foldername)) 
    { 
        new-item $foldername -type Directory 
    } 

    if (!(get-wmiObject Win32_Share -filter “name='$sharename'”)) 
    { 
        $shares = [WMICLASS]”WIN32_Share”

        if ($shares.Create($foldername, $sharename, 0).ReturnValue -ne 0) 
        {
            throw "Failed to create file share '$sharename'"
        }
    }
}
1

1 Answers

5
votes

If you downloaded the module from internet it should be placed in C:\Windows\System32\WindowsPowerShell\v1.0\Modules

  1. You should be able to locate it in your session.

    Get-Module -ListAvailable
    
  2. Then you can add the module.

    Import-Module newshare
    
  3. Verify the cmdlet is available

    Get-Command -Module newshare
    

The error happened because you didn't add the module.