Skip to main content
Glama
DynamicEndpoints

PowerShell Exec MCP Server

generate_intune_remediation_script

Create PowerShell remediation scripts for Microsoft Intune that follow enterprise best practices, including proper exit codes, event logging, and system restore points for automated device management.

Instructions

Generate a Microsoft Intune remediation script with enterprise-grade features.

Creates a PowerShell remediation script that follows Microsoft Intune best practices:
- Proper exit codes (0=success, 1=failure, 2=error)
- Event log integration for monitoring and troubleshooting
- System restore point creation before making changes
- Comprehensive error handling and logging
- No user interaction (required for Intune deployment)

⚠️  IMPORTANT: For complete Intune compliance, you need BOTH detection and remediation scripts.
Consider using 'generate_intune_script_pair' instead to create both scripts together.

Microsoft References:
- Intune Remediation Scripts: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations
- Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples
- PowerShell Script Requirements: https://docs.microsoft.com/en-us/mem/intune/apps/intune-management-extension
- Exit Code Standards: https://docs.microsoft.com/en-us/mem/intune/apps/troubleshoot-mam-app-installation#exit-codes

Args:
    description: Clear description of what the script should remediate (e.g., 'Install Chrome browser', 'Configure Windows firewall')
    remediation_logic: PowerShell code that performs the remediation. Use 'Complete-Remediation -Success $true -Message "description"' to indicate completion
    output_path: Optional file path where the script will be saved. If not provided, returns script content
    timeout: Command timeout in seconds (1-300, default 60)
    
Returns:
    Generated script content or path where script was saved
    
Example:
    Generate a script to install Chrome:
    ```
    result = await generate_intune_remediation_script(
        description="Install Chrome browser to latest version",
        remediation_logic='''
        $installer = "$env:TEMP\ChromeSetup.exe"
        Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer
        Start-Process -FilePath $installer -Args "/silent /install" -Wait
        Remove-Item $installer -Force
        Complete-Remediation -Success $true -Message "Chrome installation completed successfully"
        ''',
        output_path="remediate_chrome.ps1"
    )
    ```
    
Tips:
    - Always use Complete-Remediation function to set proper exit codes
    - Test your remediation_logic in a safe environment first
    - Consider creating a system restore point for major changes
    - Use Write-IntuneLog for detailed logging and troubleshooting
    - Ensure no user interaction is required (scripts run silently)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionYes
remediation_logicYes
output_pathNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function implementing the 'generate_intune_remediation_script' MCP tool. It prepares template parameters based on user inputs (description, remediation_logic, etc.) and delegates to the shared generate_script_from_template helper using the specific 'intune_remediation' template for Intune best practices.
    @mcp.tool()
    async def generate_intune_remediation_script(
        description: str,
        remediation_logic: str,
        output_path: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> str:
        """Generate a Microsoft Intune remediation script with enterprise-grade features.
        
        Creates a PowerShell remediation script that follows Microsoft Intune best practices:
        - Proper exit codes (0=success, 1=failure, 2=error)
        - Event log integration for monitoring and troubleshooting
        - System restore point creation before making changes
        - Comprehensive error handling and logging
        - No user interaction (required for Intune deployment)
        
        ⚠️  IMPORTANT: For complete Intune compliance, you need BOTH detection and remediation scripts.
        Consider using 'generate_intune_script_pair' instead to create both scripts together.
        
        Microsoft References:
        - Intune Remediation Scripts: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations
        - Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples
        - PowerShell Script Requirements: https://docs.microsoft.com/en-us/mem/intune/apps/intune-management-extension
        - Exit Code Standards: https://docs.microsoft.com/en-us/mem/intune/apps/troubleshoot-mam-app-installation#exit-codes
        
        Args:
            description: Clear description of what the script should remediate (e.g., 'Install Chrome browser', 'Configure Windows firewall')
            remediation_logic: PowerShell code that performs the remediation. Use 'Complete-Remediation -Success $true -Message "description"' to indicate completion
            output_path: Optional file path where the script will be saved. If not provided, returns script content
            timeout: Command timeout in seconds (1-300, default 60)
            
        Returns:
            Generated script content or path where script was saved
            
        Example:
            Generate a script to install Chrome:
            ```
            result = await generate_intune_remediation_script(
                description="Install Chrome browser to latest version",
                remediation_logic='''
                $installer = "$env:TEMP\\ChromeSetup.exe"
                Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer
                Start-Process -FilePath $installer -Args "/silent /install" -Wait
                Remove-Item $installer -Force
                Complete-Remediation -Success $true -Message "Chrome installation completed successfully"
                ''',
                output_path="remediate_chrome.ps1"
            )
            ```
            
        Tips:
            - Always use Complete-Remediation function to set proper exit codes
            - Test your remediation_logic in a safe environment first
            - Consider creating a system restore point for major changes
            - Use Write-IntuneLog for detailed logging and troubleshooting
            - Ensure no user interaction is required (scripts run silently)
        """
        params = {
            "SYNOPSIS": f"Intune Remediation Script - {description}",
            "DESCRIPTION": description,
            "DATE": datetime.now().strftime('%Y-%m-%d'),
            "REMEDIATION_LOGIC": remediation_logic
        }
        
        if output_path:
            output_path = ensure_directory(output_path)
        
        return await generate_script_from_template("intune_remediation", params, output_path, timeout)
  • Shared helper tool used by generate_intune_remediation_script (and others) to load a named PowerShell template from TEMPLATES_DIR, perform parameter substitution, optionally save to output_path, and return the generated script content.
    @mcp.tool()
    async def generate_script_from_template(
        template_name: str,
        parameters: Dict[str, Any],
        output_path: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> str:
        """Generate a PowerShell script from a template.
        
        Args:
            template_name: Name of the template to use (without .ps1 extension)
            parameters: Dictionary of parameters to replace in the template
            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
        """
        template_path = os.path.join(TEMPLATES_DIR, f"{template_name}.ps1")
        if not os.path.exists(template_path):
            raise ValueError(f"Template {template_name} not found")
            
        with open(template_path, 'r') as f:
            template_content = f.read()
            
        # Replace template variables
        script_content = template_content
        parameters['DATE'] = datetime.now().strftime('%Y-%m-%d')
        
        for key, value in parameters.items():
            script_content = script_content.replace(f"{{{{{key}}}}}", str(value))
            
        if output_path:
            with open(output_path, 'w') as f:
                f.write(script_content)
            return f"Script generated and saved to: {output_path}"
        
        return script_content
  • Helper utility called by generate_intune_remediation_script to normalize and ensure the output directory exists before writing the generated script file.
    @mcp.tool()
    def ensure_directory(path: str) -> str:
        """Ensure directory exists and return absolute path."""
        abs_path = normalize_path(path)
        if os.path.splitext(abs_path)[1]:  # If path has an extension
            dir_path = os.path.dirname(abs_path)
        else:
            dir_path = abs_path
        os.makedirs(dir_path, exist_ok=True)
        return abs_path
  • src/server.py:389-389 (registration)
    The @mcp.tool() decorator registers the generate_intune_remediation_script function as an MCP tool with FastMCP.
    @mcp.tool()
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behavioral traits: the script follows enterprise-grade practices (exit codes, event log integration, system restore points, error handling, no user interaction), runs silently, and includes timeout handling. It also mentions testing recommendations and references Microsoft documentation. However, it doesn't explicitly state potential side effects like system changes or permission requirements, leaving some gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and front-loaded with the core purpose and key features. It uses bullet points for best practices, includes important warnings and alternatives, provides parameter explanations, an example, and tips. While comprehensive, some sections (like the extensive Microsoft references list) could be trimmed without losing essential information, making it slightly verbose but still highly usable.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (generating scripts with enterprise features), no annotations, and an output schema that only indicates return types, the description provides excellent contextual completeness. It covers purpose, usage guidelines, behavioral traits, parameter semantics, examples, and tips. The output schema handles return values, so the description appropriately focuses on other aspects, making it fully sufficient for an agent to understand and use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, so the description must fully compensate. It provides detailed explanations for all parameters: 'description' clarifies it's for what the script remediates, 'remediation_logic' specifies PowerShell code with usage of 'Complete-Remediation', 'output_path' explains optional file saving, and 'timeout' defines command timeout range and default. The example further illustrates parameter usage, adding significant value beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Generate a Microsoft Intune remediation script with enterprise-grade features.' It specifies the verb ('Generate'), resource ('Microsoft Intune remediation script'), and distinguishes it from sibling tools like 'generate_intune_script_pair' by focusing on remediation-only scripts. The description explicitly mentions what the script does (follows best practices like exit codes, event log integration, etc.).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool versus alternatives. It states: '⚠️ IMPORTANT: For complete Intune compliance, you need BOTH detection and remediation scripts. Consider using 'generate_intune_script_pair' instead to create both scripts together.' This clearly indicates when to use this tool (for remediation-only scripts) and when to prefer an alternative (for paired scripts), helping the agent make informed decisions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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