Skip to main content
Glama
alxspiker

Windows Command Line MCP Server

execute_powershell

Execute PowerShell scripts to perform complex Windows operations through controlled command-line access, returning script output for automation and system management tasks.

Instructions

Execute a PowerShell script and return its output. This allows for more complex operations and script execution. PowerShell must be in the allowed commands list.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYesPowerShell script to execute
workingDirNoWorking directory for the script
timeoutNoTimeout in milliseconds

Implementation Reference

  • The core handler function for the 'execute_powershell' tool. It checks the platform, performs security validation by blocking dangerous PowerShell patterns, constructs the command using powershell.exe, executes it via the executeCommand helper with optional working directory and timeout, and returns the stdout or formatted error response.
    async ({ script, workingDir, timeout }) => {
      if (!isWindows) {
        return {
          content: [
            {
              type: "text",
              text: "The PowerShell execution tool is only available on Windows. Current platform: " + platform(),
            },
          ],
        };
      }
      
      try {
        // Security check: Ensure no dangerous operations
        const scriptLower = script.toLowerCase();
        
        // Block potentially dangerous commands
        const dangerousPatterns = [
          'new-user', 'add-user', 'remove-item -recurse -force', 'format-volume', 
          'reset-computer', 'stop-computer', 'restart-computer', 'stop-process -force',
          'remove-item -force', 'set-executionpolicy', 'invoke-webrequest',
          'start-bitstransfer', 'set-location', 'invoke-expression', 'iex', '& {',
          'invoke-command', 'new-psdrive', 'remove-psdrive', 'enable-psremoting',
          'new-service', 'remove-service', 'set-service'
        ];
        
        // Check for dangerous patterns
        if (dangerousPatterns.some(pattern => scriptLower.includes(pattern.toLowerCase()))) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: "Script contains potentially dangerous operations and cannot be executed.",
              },
            ],
          };
        }
        
        const options: any = { timeout };
        if (workingDir) {
          options.cwd = workingDir;
        }
        
        const stdout = executeCommand(`powershell.exe -Command "${script}"`, options);
        return {
          content: [
            {
              type: "text",
              text: stdout.toString() || 'PowerShell script executed successfully (no output)',
            },
          ],
        };
      } catch (error) {
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error executing PowerShell script: ${error}`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the execute_powershell tool: required 'script' string, optional 'workingDir' string, and 'timeout' number with default 30000.
    {
      script: z.string().describe("PowerShell script to execute"),
      workingDir: z.string().optional().describe("Working directory for the script"),
      timeout: z.number().default(30000).describe("Timeout in milliseconds"),
    },
  • index.ts:517-590 (registration)
    Registration of the 'execute_powershell' tool using server.tool(), including name, description, schema, and inline handler function.
    server.tool(
      "execute_powershell",
      "Execute a PowerShell script and return its output. This allows for more complex operations and script execution. PowerShell must be in the allowed commands list.",
      {
        script: z.string().describe("PowerShell script to execute"),
        workingDir: z.string().optional().describe("Working directory for the script"),
        timeout: z.number().default(30000).describe("Timeout in milliseconds"),
      },
      async ({ script, workingDir, timeout }) => {
        if (!isWindows) {
          return {
            content: [
              {
                type: "text",
                text: "The PowerShell execution tool is only available on Windows. Current platform: " + platform(),
              },
            ],
          };
        }
        
        try {
          // Security check: Ensure no dangerous operations
          const scriptLower = script.toLowerCase();
          
          // Block potentially dangerous commands
          const dangerousPatterns = [
            'new-user', 'add-user', 'remove-item -recurse -force', 'format-volume', 
            'reset-computer', 'stop-computer', 'restart-computer', 'stop-process -force',
            'remove-item -force', 'set-executionpolicy', 'invoke-webrequest',
            'start-bitstransfer', 'set-location', 'invoke-expression', 'iex', '& {',
            'invoke-command', 'new-psdrive', 'remove-psdrive', 'enable-psremoting',
            'new-service', 'remove-service', 'set-service'
          ];
          
          // Check for dangerous patterns
          if (dangerousPatterns.some(pattern => scriptLower.includes(pattern.toLowerCase()))) {
            return {
              isError: true,
              content: [
                {
                  type: "text",
                  text: "Script contains potentially dangerous operations and cannot be executed.",
                },
              ],
            };
          }
          
          const options: any = { timeout };
          if (workingDir) {
            options.cwd = workingDir;
          }
          
          const stdout = executeCommand(`powershell.exe -Command "${script}"`, options);
          return {
            content: [
              {
                type: "text",
                text: stdout.toString() || 'PowerShell script executed successfully (no output)',
              },
            ],
          };
        } catch (error) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error executing PowerShell script: ${error}`,
              },
            ],
          };
        }
      }
    );
  • Shared helper function executeCommand used by the tool (and others) to synchronously execute the constructed PowerShell command via execSync on Windows, with fallback logic for non-Windows platforms.
    function executeCommand(command: string, options: any = {}) {
      if (isWindows) {
        return execSync(command, options);
      } else {
        // Log warning for non-Windows environments
        console.error(`Warning: Running in a non-Windows environment (${platform()}). Windows commands may not work.`);
        
        // For testing purposes on non-Windows platforms
        try {
          // For Linux/MacOS, we'll strip cmd.exe and powershell.exe references
          let modifiedCmd = command;
          
          // Replace cmd.exe /c with empty string
          modifiedCmd = modifiedCmd.replace(/cmd\.exe\s+\/c\s+/i, '');
          
          // Replace powershell.exe -Command with empty string or a compatible command
          modifiedCmd = modifiedCmd.replace(/powershell\.exe\s+-Command\s+("|')/i, '');
          
          // Remove trailing quotes if we removed powershell -Command
          if (modifiedCmd !== command) {
            modifiedCmd = modifiedCmd.replace(/("|')$/, '');
          }
          
          console.error(`Attempting to execute modified command: ${modifiedCmd}`);
          return execSync(modifiedCmd, options);
        } catch (error) {
          console.error(`Error executing modified command: ${error}`);
          return Buffer.from(`This tool requires a Windows environment. Current platform: ${platform()}`);
        }
      }
    }
  • index.ts:8-8 (helper)
    Platform detection constant used throughout the handler to restrict PowerShell execution to Windows.
    const isWindows = platform() === 'win32';
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions that the tool returns output and has a prerequisite (PowerShell in allowed commands), but lacks details on security implications, error handling, execution environment, or potential side effects. For a tool that executes arbitrary scripts, this is a significant gap in transparency.

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 appropriately concise with two sentences that each serve a purpose - the first states the core functionality, the second adds an important constraint. It's front-loaded with the main purpose and avoids unnecessary elaboration.

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

Completeness2/5

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

Given this is a potentially dangerous script execution tool with no annotations and no output schema, the description is insufficient. It doesn't explain what kind of output to expect, error conditions, security implications, or execution limitations. For a tool that could have significant system impact, more context is needed.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema - it mentions script execution generally but provides no additional context about parameter usage, constraints, or examples.

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

Purpose4/5

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

The description clearly states the tool executes a PowerShell script and returns output, specifying the verb 'execute' and resource 'PowerShell script'. It distinguishes from sibling tools like execute_command by specifying PowerShell specifically, though it doesn't explicitly contrast with them.

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

Usage Guidelines3/5

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

The description implies usage context by stating 'PowerShell must be in the allowed commands list', suggesting a prerequisite. However, it doesn't provide explicit guidance on when to use this tool versus alternatives like execute_command or other system tools, leaving usage context somewhat implied rather than clearly defined.

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/alxspiker/Windows-Command-Line-MCP-Server'

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