Skip to main content
Glama
DynamicEndpoints

PowerShell Exec MCP Server

generate_intune_script_pair

Create Microsoft Intune detection and remediation script pairs to automate system compliance checks and fixes, following Microsoft best practices for enterprise management.

Instructions

Generate a complete pair of Microsoft Intune detection and remediation scripts.

This is the RECOMMENDED tool for Intune compliance as it creates both required scripts:
- Detection script: Checks current system state and determines compliance
- Remediation script: Fixes non-compliant conditions with proper safeguards

Both scripts follow Microsoft Intune best practices:
- Proper exit codes (Detection: 0=compliant, 1=non-compliant, 2=error; Remediation: 0=success, 1=failure, 2=error)
- Event log integration for centralized monitoring
- System restore points before changes (remediation only)
- Comprehensive error handling and logging
- No user interaction (silent execution required)

Microsoft References:
- Intune Remediation Scripts Overview: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations
- Script Deployment Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples
- PowerShell 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-deployment
- Monitoring and Reporting: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-monitor

Args:
    description: Clear description of what the scripts should detect and remediate (e.g., 'Ensure Chrome browser is installed with latest version')
    detection_logic: PowerShell code that performs the compliance check. Use 'Complete-Detection -Compliant $true/$false -Message "status"' to indicate result
    remediation_logic: PowerShell code that fixes non-compliant conditions. Use 'Complete-Remediation -Success $true/$false -Message "result"' to indicate completion
    output_dir: Optional directory to save both scripts. If not provided, returns script content in response
    timeout: Command timeout in seconds (1-300, default 60)
    
Returns:
    Dictionary containing both scripts: {"detection_script": "content/path", "remediation_script": "content/path"}
    
Example:
    Generate scripts to manage Chrome browser installation:
    ```
    result = await generate_intune_script_pair(
        description="Ensure Chrome browser is installed with version 100.0.0.0 or higher",
        detection_logic='''
        try {
            $app = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" -ErrorAction Stop
            $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion
            $compliant = [version]$version -ge [version]"100.0.0.0"
            Complete-Detection -Compliant $compliant -Message "Chrome version: $version (Required: 100.0.0.0+)"
        } catch {
            Complete-Detection -Compliant $false -Message "Chrome not found or inaccessible"
        }
        ''',
        remediation_logic='''
        try {
            $installer = "$env:TEMP\ChromeSetup.exe"
            Write-IntuneLog "Downloading Chrome installer..."
            Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer -UseBasicParsing
            Write-IntuneLog "Installing Chrome silently..."
            Start-Process -FilePath $installer -Args "/silent /install" -Wait
            Remove-Item $installer -Force
            Complete-Remediation -Success $true -Message "Chrome installation completed successfully"
        } catch {
            Complete-Remediation -Success $false -Message "Chrome installation failed: $($_.Exception.Message)"
        }
        ''',
        output_dir="chrome_intune_scripts"
    )
    ```
    
Tips:
    - Always test both scripts in a controlled environment first
    - Use descriptive logging messages for easier troubleshooting
    - Consider the impact of remediation actions (e.g., system restarts, user disruption)
    - Use Write-IntuneLog for detailed progress tracking
    - Ensure detection logic is fast and efficient (runs frequently)
    - Make remediation logic idempotent (safe to run multiple times)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionYes
detection_logicYes
remediation_logicYes
output_dirNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function for the 'generate_intune_script_pair' MCP tool. Orchestrates generation of both Intune detection and remediation scripts using helper functions.
    @mcp.tool()
    async def generate_intune_script_pair(
        description: str,
        detection_logic: str,
        remediation_logic: str,
        output_dir: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> Dict[str, str]:
        """Generate a complete pair of Microsoft Intune detection and remediation scripts.
        
        This is the RECOMMENDED tool for Intune compliance as it creates both required scripts:
        - Detection script: Checks current system state and determines compliance
        - Remediation script: Fixes non-compliant conditions with proper safeguards
        
        Both scripts follow Microsoft Intune best practices:
        - Proper exit codes (Detection: 0=compliant, 1=non-compliant, 2=error; Remediation: 0=success, 1=failure, 2=error)
        - Event log integration for centralized monitoring
        - System restore points before changes (remediation only)
        - Comprehensive error handling and logging
        - No user interaction (silent execution required)
        
        Microsoft References:
        - Intune Remediation Scripts Overview: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations
        - Script Deployment Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples
        - PowerShell 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-deployment
        - Monitoring and Reporting: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-monitor
        
        Args:
            description: Clear description of what the scripts should detect and remediate (e.g., 'Ensure Chrome browser is installed with latest version')
            detection_logic: PowerShell code that performs the compliance check. Use 'Complete-Detection -Compliant $true/$false -Message "status"' to indicate result
            remediation_logic: PowerShell code that fixes non-compliant conditions. Use 'Complete-Remediation -Success $true/$false -Message "result"' to indicate completion
            output_dir: Optional directory to save both scripts. If not provided, returns script content in response
            timeout: Command timeout in seconds (1-300, default 60)
            
        Returns:
            Dictionary containing both scripts: {"detection_script": "content/path", "remediation_script": "content/path"}
            
        Example:
            Generate scripts to manage Chrome browser installation:
            ```
            result = await generate_intune_script_pair(
                description="Ensure Chrome browser is installed with version 100.0.0.0 or higher",
                detection_logic='''
                try {
                    $app = Get-ItemProperty "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe" -ErrorAction Stop
                    $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion
                    $compliant = [version]$version -ge [version]"100.0.0.0"
                    Complete-Detection -Compliant $compliant -Message "Chrome version: $version (Required: 100.0.0.0+)"
                } catch {
                    Complete-Detection -Compliant $false -Message "Chrome not found or inaccessible"
                }
                ''',
                remediation_logic='''
                try {
                    $installer = "$env:TEMP\\ChromeSetup.exe"
                    Write-IntuneLog "Downloading Chrome installer..."
                    Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer -UseBasicParsing
                    Write-IntuneLog "Installing Chrome silently..."
                    Start-Process -FilePath $installer -Args "/silent /install" -Wait
                    Remove-Item $installer -Force
                    Complete-Remediation -Success $true -Message "Chrome installation completed successfully"
                } catch {
                    Complete-Remediation -Success $false -Message "Chrome installation failed: $($_.Exception.Message)"
                }
                ''',
                output_dir="chrome_intune_scripts"
            )
            ```
            
        Tips:
            - Always test both scripts in a controlled environment first
            - Use descriptive logging messages for easier troubleshooting
            - Consider the impact of remediation actions (e.g., system restarts, user disruption)
            - Use Write-IntuneLog for detailed progress tracking
            - Ensure detection logic is fast and efficient (runs frequently)
            - Make remediation logic idempotent (safe to run multiple times)
        """
        if output_dir:
            # Create output directory in current working directory
            abs_output_dir = ensure_directory(output_dir)
            
            # Create full paths for scripts
            detect_path = os.path.join(abs_output_dir, "detect.ps1")
            remedy_path = os.path.join(abs_output_dir, "remedy.ps1")
            
            # Create parent directory if it doesn't exist
            os.makedirs(abs_output_dir, exist_ok=True)
            
            detect_result = await generate_intune_detection_script(
                description=description,
                detection_logic=detection_logic,
                output_path=detect_path,
                timeout=timeout
            )        
            remedy_result = await generate_intune_remediation_script(
                description=description,
                remediation_logic=remediation_logic,
                output_path=remedy_path,
                timeout=timeout
            )
        else:
            detect_result = await generate_intune_detection_script(
                description=description,
                detection_logic=detection_logic,
                timeout=timeout
            )
            
            remedy_result = await generate_intune_remediation_script(
                description=description,
                remediation_logic=remediation_logic,
                timeout=timeout
            )
        
        return {
            "detection_script": detect_result,
            "remediation_script": remedy_result
        }
  • src/server.py:458-458 (registration)
    MCP tool registration decorator that registers the generate_intune_script_pair function as an MCP tool.
    @mcp.tool()
  • Helper tool function called by generate_intune_script_pair to generate the detection script from template.
    async def generate_intune_detection_script(
        description: str,
        detection_logic: str,
        output_path: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> str:
        """Generate a Microsoft Intune detection script with enterprise-grade compliance checking.
        
        Creates a PowerShell detection script that follows Microsoft Intune best practices:
        - Proper exit codes (0=compliant, 1=non-compliant, 2=error)
        - Event log integration for monitoring and troubleshooting
        - Fast execution optimized for frequent compliance checks
        - Comprehensive error handling and logging
        - No user interaction (required for Intune deployment)
        
        💡 TIP: For complete Intune compliance, you need BOTH detection and remediation scripts.
        Consider using 'generate_intune_script_pair' to create both scripts together with matching logic.
        
        Microsoft References:
        - Intune Detection 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 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-deployment
        
        Args:
            description: Clear description of what the script should detect (e.g., 'Check if Chrome is installed with correct version', 'Verify Windows firewall is enabled')
            detection_logic: PowerShell code that performs the compliance check. Use 'Complete-Detection -Compliant $true/$false -Message "status"' to indicate result
            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 detect Chrome installation:
            ```
            result = await generate_intune_detection_script(
                description="Check if Chrome browser is installed with version 100.0.0.0 or higher",
                detection_logic='''
                try {
                    $app = Get-ItemProperty "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe" -ErrorAction Stop
                    $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion
                    $compliant = [version]$version -ge [version]"100.0.0.0"
                    Complete-Detection -Compliant $compliant -Message "Chrome version: $version (Required: 100.0.0.0+)"
                } catch {
                    Complete-Detection -Compliant $false -Message "Chrome not found or inaccessible"
                }
                ''',
                output_path="detect_chrome.ps1"
            )
            ```
            
        Tips:
            - Keep detection logic fast and efficient (runs frequently)
            - Always use Complete-Detection function to set proper exit codes
            - Use try-catch blocks for robust error handling
            - Test detection logic thoroughly in different environments
            - Use Write-IntuneLog for detailed progress tracking
            - Avoid making changes in detection scripts (read-only operations)
        """
        params = {
            "SYNOPSIS": f"Intune Detection Script - {description}",
            "DESCRIPTION": description,
            "DATE": datetime.now().strftime('%Y-%m-%d'),
            "DETECTION_LOGIC": detection_logic
        }
        
        if output_path:
            output_path = ensure_directory(output_path)
        
        return await generate_script_from_template("intune_detection", params, output_path, timeout)
  • Helper tool function called by generate_intune_script_pair to generate the remediation script from template.
    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)
  • Core helper function that loads and parameterizes template files, used by Intune script generators.
    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
Behavior5/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 thoroughly explains what the tool does: generates scripts following best practices like proper exit codes, event log integration, system restore points, error handling, and silent execution. It also details the return format ('Dictionary containing both scripts'), timeout behavior, and output options, providing comprehensive behavioral context beyond basic functionality.

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. However, it includes extensive sections like Microsoft references and a detailed example that, while helpful, make it longer than necessary. Every sentence adds value, but some redundancy (e.g., repeating exit code details) slightly reduces conciseness. Overall, it's efficient but could be more streamlined.

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 paired scripts with best practices), no annotations, and an output schema that only specifies return structure, the description provides complete context. It covers purpose, usage, behavioral details, parameter semantics, examples, and tips, ensuring the agent has all necessary information to use the tool correctly without relying on external documentation.

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?

Schema description coverage is 0%, so the description must compensate fully. It does so by clearly explaining each parameter: 'description' specifies what scripts should do, 'detection_logic' and 'remediation_logic' define PowerShell code with usage examples, 'output_dir' indicates optional saving, and 'timeout' sets command limits. The example illustrates parameter usage in context, 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 complete pair of Microsoft Intune detection and remediation scripts.' It specifies the verb ('generate') and resource ('pair of Microsoft Intune detection and remediation scripts'), and distinguishes it from siblings by emphasizing it's the 'RECOMMENDED tool for Intune compliance' and creates both required scripts, unlike tools like 'generate_intune_remediation_script' which might only handle one.

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: 'This is the RECOMMENDED tool for Intune compliance as it creates both required scripts.' It implicitly suggests alternatives by mentioning sibling tools like 'generate_intune_remediation_script' for cases where only remediation is needed. The 'Tips' section adds context on when to use it effectively, such as testing in controlled environments and considering remediation impacts.

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