PSSpecModule.psm1

$modulePath = Split-Path -Parent $MyInvocation.MyCommand.Definition
Import-Module "$modulePath\PSSpecCmdlets.dll"

# ///// Split the comment lines into 76 character long and add "///"
function Set-FirstLetterToUpper ($a)
{
    $a[0].ToString().ToUpper() + $a.Substring(1, $a.Length - 1)
}

function Get-FieldName($parameterName)
{
    $lowerParameterName=$parameterName.ToLower()
    $lowerParameterName 
}

function Get-CmdletTemplate
{
    [CmdletBinding(DefaultParameterSetName="ProjectId")]
    [OutputType([System.Array])]   
    param 
    ( 
        [parameter(Mandatory=$true)]
        [string] $CmdletName, 

        [parameter(Mandatory=$true, ParameterSetName="ProjectName")]
        [string] $ProjectName , 

        [parameter(ParameterSetName="ProjectName")]
        [string] $ProjectVersion = "1.0", 

        [parameter(Mandatory=$true, ParameterSetName="ProjectId")]
        [int] $ProjectId,

        [Parameter(Mandatory=$false)]
        [string] $ServiceUri = "http://cmdletdesigner/cmdletdesigner/CmdletDesignerService.svc"
    )    

$verbMapping = @{
    "Add" = "VerbsCommon.Add";
    "Clear" = "VerbsCommon.Clear";
    "Copy" = "VerbsCommon.Copy";
    "Get" = "VerbsCommon.Get";
    "Lock" = "VerbsCommon.Lock";
    "Move" = "VerbsCommon.Move";
    "New" = "VerbsCommon.New";
    "Remove" = "VerbsCommon.Remove";
    "Rename" = "VerbsCommon.Rename";
    "Set" = "VerbsCommon.Set";
    "Join" = "VerbsCommon.Join";
    "Split" = "VerbsCommon.Split";
    "Select" = "VerbsCommon.Select";
    "Unlock" = "VerbsCommon.Unlock";
    "Backup" = "VerbsData.Backup";
    "Checkpoint" = "VerbsData.Checkpoint";
    "Compare" = "VerbsData.Compare";
    "Convert" = "VerbsData.Convert";
    "ConvertFrom" = "VerbsData.ConvertFrom";
    "ConvertTo" = "VerbsData.ConvertTo";
    "Export" = "VerbsData.Export";
    "Import" = "VerbsData.Import";
    "Initialize" = "VerbsData.Initialize";
    "Limit" = "VerbsData.Limit";
    "Merge" = "VerbsData.Merge";
    "Restore" = "VerbsData.Restore";
    "Update" = "VerbsData.Update";
    "Mount" = "VerbsData.Mount";
    "Dismount" = "VerbsData.Dismount";
    "Out" = "VerbsData.Out";
    "Disable" = "VerbsLifecycle.Disable";
    "Enable" = "VerbsLifecycle.Enable";
    "Install" = "VerbsLifecycle.Install";
    "Restart" = "VerbsLifecycle.Restart";
    "Resume" = "VerbsLifecycle.Resume";
    "Start" = "VerbsLifecycle.Start";
    "Stop" = "VerbsLifecycle.Stop";
    "Suspend" = "VerbsLifecycle.Suspend";
    "Uninstall" = "VerbsLifecycle.Uninstall";
    "Debug" = "VerbsDiagnostic.Debug";
    "Measure" = "VerbsDiagnostic.Measure";
    "Ping" = "VerbsDiagnostic.Ping";
    "Resolve" = "VerbsDiagnostic.Resolve";
    "Test" = "VerbsDiagnostic.Test";
    "Trace" = "VerbsDiagnostic.Trace";
    "Send" = "VerbsCommunications.Send";
    "Receive" = "VerbsCommunications.Receive";
    "Connect" = "VerbsCommunications.Connect";
    "Disconnect" = "VerbsCommunications.Disconnect";
    "Write" = "VerbsCommunications.Write";
    "Read" = "VerbsCommunications.Read";
    "Grant" = "VerbsSecurity.Grant";
    "Revoke" = "VerbsSecurity.Revoke";
    "Block" = "VerbsSecurity.Block";
    "Unblock" = "VerbsSecurity.Unblock";
    "Use" = "VerbsOther.Use";
    }   

    # check to see if the Cmdlet record already exists.
    if([string]::IsNullOrEmpty($ProjectName))
    {
        $project = Get-PsSpecProject -ProjectId $ProjectId -ServiceUri $ServiceUri
    }
    else
    {
        $project = Get-PsSpecProject -Name $ProjectName -Version $ProjectVersion -ServiceUri $ServiceUri
    }

    if($null -eq $project)
    {
        return
    }

    $ProjectId=$project.ProjectId
    $ProjectName=$project.Name
    $ProjectVersion=$project.Version

    $cmdletRecords = @(Get-PsSpecCmdlet -ServiceUri $ServiceUri -Name $CmdletName -ProjectId $ProjectId -EA SilentlyContinue)    
    $scriptFileBuilder = new-object System.Text.StringBuilder
    
    if($cmdletRecords.Count -eq 0)
    {
        Write-Verbose -Message "This cmdlet does not exist"
        return
    }


    $projectNamespace = $ProjectName -replace ' ',''
    $projectNamespace = $projectNamespace -replace '-','_'

    $null = $scriptFileBuilder.AppendLine()
    

   ### We create the Cmdlet record here if one does not exit.
    foreach ($cmdletRecord in $cmdletRecords)
    {
    
        #$verb is Cmdlet verb
        $cmdletVerb = $cmdletRecord.Verb
        $verb = $verbMapping[$cmdletVerb]
    
        #Check if verbMapping returned a strongly typed verb. If not, just use the verb's name.
        if($null -eq $verb)
        {
            $verb = "`""+$cmdletRecord.Verb+"`"";
        }

        #$noun is Cmdlet noun
        $noun = $cmdletRecord.Noun

        #Check for ShouldProcess.
        if ($cmdletRecord.SupportsShouldProcess)
        {            
            $ShouldProcess = $cmdletRecord.SupportsShouldProcess.ToString().ToLower()    
            $scriptsupportShouldProcess = "SupportsShouldProcess=`$${ShouldProcess}"
        }
        else
        {
            $scriptsupportShouldProcess = "SupportsShouldProcess=`$false"
        }
    
        if ($null -ne $cmdletRecord.LongDescription)
        {            
            $scriptCmdletHelpDescription = $cmdletRecord.LongDescription            
        }
        else
        {
            $scriptCmdletHelpDescription = $null
        }

        $projectName = Set-FirstLetterToUpper $projectName 

        $scriptCmdletHeading = @"
        function $CmdletVerb-$noun
        {
        <#
            .SYNOPSIS
            $scriptCmdletHelpDescription
 
            .DESCRIPTION
              
 
            .EXAMPLE
 
 
            .LINK
        #>
 
        [CmdletBinding($scriptsupportShouldProcess)]
        param (
 
"@


        $null=$scriptFileBuilder.AppendLine($scriptCmdletHeading)

        $cmdletRecordName=$cmdletRecord.Verb+"-"+$cmdletRecord.Noun

        $project = Get-PsSpecProject -Name $projectName -Version $projectVersion -ServiceUri $ServiceUri
        $Entries = @(Get-PsSpecCmdletParameterSetEntry -ServiceUri $ServiceUri -CmdletName $cmdletRecordName -ProjectId $project.ProjectId | Sort-Object ParameterName)
        $Params = @(Get-PsSpecCmdletParameter -ServiceUri $ServiceUri -CmdletName $cmdletRecordName -ProjectId $project.ProjectId)
            
        $allParameterCount =  $Params.Count
        $parameterIndex = 0

        foreach ($param in $Params) 
        {
                $FirstParamEntry = $null
                $scriptHeading = New-Object "System.Collections.ObjectModel.Collection``1[[System.String]]"

                Foreach ($entry in $Entries) 
                        { 
                                $Comma = $null
                                if ( $entry.ParameterName -eq ($param.Name) )
                                        {
                                                if ($entry.Mandatory)
                                                        {
                                                                $scriptMandatory = $entry.Mandatory.ToString().ToLower()                                                                
                                                                $scriptMandatory = "Mandatory = `$${scriptMandatory}"
                                                                $Comma = ",`r`n "
                                                        }
                                                else
                                                        {                                                                
                                                                $scriptMandatory = "Mandatory = `$false"
                                                                $Comma = ",`r`n "
                                                        }

                                                if (-not [string]::IsNullOrEmpty($param.Description))
                                                {                    
                                                    $Comma = ",`r`n "                                                    
                                                    $scriptParamDefinition = $param.Description.ToString().Replace("`'", "`"")
                                                    $scriptParamDefinition = "${Comma}HelpMessage = `'${scriptParamDefinition}`'"
                                                }
                                                else
                                                {
                                                    $scriptParamDefinition = $null
                                                }

                                                if ($null -ne $entry.Position)
                                                        {
                                                                $PositionValue = $entry.Position.ToString()
                                                                $Position ="${Comma}Position = ${PositionValue}"
                                                                $Comma = ",`r`n "
                                                        }
                                                else
                                                        {
                                                                $Position = $null
                                                        }

                                                if ($entry.ValueFromPipeline)
                                                        {

                                                                $scriptValueFromPipeline = $entry.ValueFromPipeline.ToString().ToLower()                                                                
                                                                $scriptValueFromPipeline = "${Comma}ValueFromPipeline = `$${scriptValueFromPipeline}"
                                                                $Comma = ",`r`n "

                                                        }
                                                else
                                                        {                                                                
                                                                $scriptValueFromPipeline = $null
                                                        }

                                                if ($entry.ValueFromPipelineByPropertyName)
                                                        {
                                                                $scriptValueFromPipelineByPropertyName = $entry.ValueFromPipelineByPropertyName.ToString().ToLower()                                                                
                                                                $scriptValueFromPipelineByPropertyName = "${Comma}ValueFromPipelineByPropertyName = `$${scriptValueFromPipelineByPropertyName}"
                                                                $Comma = ",`r`n "
                                                        }
                                                else
                                                        {                                                                
                                                                $scriptValueFromPipelineByPropertyName = $null
                                                        }

                                                if ($entry.ValueFromRemainingArguments)
                                                        {
                                                                $scriptValueFromRemainingArguments = $entry.ValueFromRemainingArguments.ToString().ToLower()                                                                
                                                                $scriptValueFromRemainingArguments = "${Comma}ValueFromRemainingArguments = `$${scriptValueFromRemainingArguments}"
                                                                $Comma = ",`r`n "
                                                        }
                                                else
                                                        {                                                                
                                                                $scriptValueFromRemainingArguments = $null
                                                        }


                                                if ($null -ne $entry.ParameterSetName -and "" -ne $entry.ParameterSetName)
                                                        {                    
                                                                $SetName = $entry.ParameterSetName        
                                                                $ParameterSetName = "${Comma}ParameterSetName = `"${SetName}`""
                                                                $Comma = ",`r`n "
                                                        }
                                                else
                                                        {
                                                                 $ParameterSetName = $null
                                                        }
                                                if ($comma)
                                                        {
                                                                                                                        
                                                                $scriptAttribute = "$FirstParamEntry[Parameter(${scriptMandatory}${scriptParamDefinition}${Position}${scriptValueFromPipeline}${scriptValueFromPipelineByPropertyName}${scriptValueFromRemainingArguments}${ParameterSetName})]" 
                                                                $FirstParamEntry = "`r`n"
                                                        }
                                                else
                                                        {
                                                                $scriptAttribute = "$FirstParamEntry[Parameter()]"
                                                                $FirstParamEntry = "`r`n"
                                                        }                                                
                                                $scriptHeading.Add($scriptAttribute)
                                        }
                        }


                if($null -ne $param.ValidateSet)
                {
                    $setMembers = [System.String]::Empty;
                    $firstIteration = $true;
                    Foreach($setMember in $param.ValidateSet)
                    {
                        if(-not $firstIteration)
                        {
                            $setMembers = $setMembers + ",";
                        }
                        $setMembers = $setMembers + "`""+$setMember+"`"";
                        $firstIteration = $false;
                    }
                    
                    $scriptHeading.Add("[ValidateSet($setMembers)]");
                }                
                
                $scriptHeadingAttributes = $null;
                $firstIteration = $true;
                Foreach($attr in $scriptheading)
                {
                    if(-not $firstIteration)
                    {                        
                        $scriptHeadingAttributes = $scriptHeadingAttributes + "`r`n ";
                    }                    
                    $scriptHeadingAttributes = $scriptHeadingAttributes + $attr;
                    $firstIteration = $false;
                }                
                                
                $scriptParamType = $param.Type
                $ParamName = Set-FirstLetterToUpper $param.Name.ToString()
                
        $parameterIndex = $parameterIndex + 1
        $comma = ",`r`n "
        if ($allParameterCount -eq $parameterIndex)
        {
            $comma = $null
        }
                $scriptParameterText=@"
            ${scriptHeadingAttributes}
            [${scriptParamType}]
            `$${ParamName}$comma
"@
            
            $null=$scriptFileBuilder.AppendLine($scriptParameterText)
        }
        
    $scriptCmdletEnd=@"
       
            )
 
            BEGIN {}
            PROCESS {}
            END {}
    }
 
"@
        

        $null=$scriptFileBuilder.AppendLine($scriptCmdletEnd)
    }

    $null = $scriptFileBuilder.AppendLine("Export-ModuleMember *")

    $scriptFileBuilder.ToString()
    
}

<#
    .SYNOPSIS
     Obtain Proxy Cmdlet implementations for a given project in CmdletDesigner
#>
 
function Get-PSScriptTemplate
{
        Param
          (
          
            [Parameter(Mandatory = $true, HelpMessage = 'Project Id in CmdletDesigner')]
            [string]
            $ProjectID,
            
            [Parameter(HelpMessage = 'Path to the output module containing cmdlet templates for the provided project')]
            [String]
            $ModuleName="$home\$ProjectID.psm1"

          )


          $scriptContent = Get-CmdletTemplate -ProjectId $ProjectID -CmdletName *

          $scriptContent | Out-File $ModuleName -Force    
}

Export-ModuleMember Get-PSScriptTemplate