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

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

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