Skip to main content
Glama
DynamicEndpoints

PowerShell Exec MCP Server

generate_custom_script

Create PowerShell scripts from natural language descriptions for enterprise automation, system monitoring, and management tasks in Microsoft Intune and IBM BigFix environments.

Instructions

Generate a custom PowerShell script based on description.

Args:
    description: Natural language description of what the script should do
    script_type: Type of script to generate (file_ops, service_mgmt, etc.)
    parameters: List of parameters the script should accept
    include_logging: Whether to include logging functions
    include_error_handling: Whether to include error handling
    output_path: Where to save the generated script (optional)
    timeout: Command timeout in seconds (1-300, default 60)
    
Returns:
    Generated script content or path where script was saved

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionYes
script_typeYes
parametersNo
include_loggingNo
include_error_handlingNo
output_pathNo
timeoutNo

Implementation Reference

  • The primary handler function for the 'generate_custom_script' tool. Decorated with @mcp.tool(), it generates a custom PowerShell script based on a natural language description, script type, parameters, and options for logging and error handling. Builds the script content programmatically and optionally saves it to a file.
    @mcp.tool()
    async def generate_custom_script(
        description: str,
        script_type: str,
        parameters: Optional[List[Dict[str, Any]]] = None,
        include_logging: bool = True,
        include_error_handling: bool = True,
        output_path: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> str:
        """Generate a custom PowerShell script based on description.
        
        Args:
            description: Natural language description of what the script should do
            script_type: Type of script to generate (file_ops, service_mgmt, etc.)
            parameters: List of parameters the script should accept
            include_logging: Whether to include logging functions
            include_error_handling: Whether to include error handling
            output_path: Where to save the generated script (optional)
            timeout: Command timeout in seconds (1-300, default 60)
            
        Returns:
            Generated script content or path where script was saved
        """
        script_content = []
        
        # Add help comment block
        script_content.extend([
            '<#',
            '.SYNOPSIS',
            f'    {description}',
            '.DESCRIPTION',
            f'    Dynamically generated PowerShell script for {script_type}',
            '.NOTES',
            '    Generated by PowerShell MCP Server',
            f'    Date: {datetime.now().strftime("%Y-%m-%d")}',
            '#>'
        ])
        
        # Add parameters
        if parameters:
            script_content.append('\nparam (')
            for param in parameters:
                param_str = f'    [Parameter(Mandatory=${param.get("mandatory", "false")})]'
                if param.get('type'):
                    param_str += f'\n    [{param["type"]}]'
                param_str += f'${param["name"]}'
                if param.get('default'):
                    param_str += f' = "{param["default"]}"'
                script_content.append(param_str + ',')
            script_content[-1] = script_content[-1].rstrip(',')  # Remove trailing comma
            script_content.append(')')
        
        # Add logging function
        if include_logging:
            script_content.extend([
                '\n# Function to write log messages',
                'function Write-Log {',
                '    param (',
                '        [Parameter(Mandatory=$true)]',
                '        [string]$Message,',
                '        [Parameter(Mandatory=$false)]',
                '        [ValidateSet("INFO", "WARNING", "ERROR")]',
                '        [string]$Level = "INFO"',
                '    )',
                '    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"',
                '    Write-Host "[$timestamp] [$Level] $Message"',
                '}'
            ])
        
        # Add error handling
        if include_error_handling:
            script_content.extend([
                '\n# Function to handle errors',
                'function Handle-Error {',
                '    param (',
                '        [Parameter(Mandatory=$true)]',
                '        [System.Management.Automation.ErrorRecord]$ErrorRecord',
                '    )',
                '    Write-Log -Level ERROR -Message "Error occurred: $($ErrorRecord.Exception.Message)"',
                '    Write-Log -Level ERROR -Message "Error details: $($ErrorRecord | Out-String)"',
                '}'
            ])
        
        # Add main script block
        script_content.extend([
            '\n# Main execution',
            'try {',
            '    Write-Log "Starting script execution..."',
            '    ',
            '    # TODO: Add script logic here based on description',
            '    # This is where you would add the specific PowerShell commands',
            '    Write-Log "Script completed successfully."',
            '}',
            'catch {',
            '    Handle-Error -ErrorRecord $_',
            '    exit 1',
            '}'
        ])
        
        final_content = '\n'.join(script_content)
        
        if output_path:
            with open(output_path, 'w') as f:
                f.write(final_content)
            return f"Script generated and saved to: {output_path}"
        
        return final_content

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/DynamicEndpoints/PowerShell-Exec-MCP-Server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server