ASP/C#中转换字符串为安全PowerShell语法及new-mailbox报错求助
Let's break down why you're hitting this error and get it fixed quickly. The core issue right now is that you're passing the string (ConvertTo-SecureString -String P@ssword1 -AsPlainText -Force) directly as the -Password parameter value. PowerShell isn't interpreting that as a command to run—it's treating it like a plain text string, hence the conversion failure.
Here are two reliable solutions, with the first being the most secure and recommended:
1. Create a SecureString in C# First (Best Practice)
Instead of trying to get PowerShell to parse a string into a SecureString, create the SecureString directly in your C# code and pass it as a parameter. This avoids exposing plaintext passwords in script strings and eliminates parsing issues entirely.
using System.Security; using System.Management.Automation; // Convert plaintext password to a locked SecureString var securePassword = new SecureString(); foreach (char c in "P@ssword1") { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); // Prevent further modifications to the SecureString // Execute the New-Mailbox command using (var ps = PowerShell.Create()) { ps.AddCommand("New-Mailbox") .AddParameter("UserPrincipalName", "name@name.com") .AddParameter("Database", "db033") .AddParameter("DisplayName", "last, first") .AddParameter("Password", securePassword); var results = ps.Invoke(); // Handle any execution errors if (ps.HadErrors) { foreach (var error in ps.Streams.Error) { // Log or display error details as needed Console.WriteLine($"Error encountered: {error.ToString()}"); } } }
2. Execute the Full PowerShell Script as a Block
If you need to use a script string instead, make sure you pass the entire command as a script block so PowerShell parses and executes the ConvertTo-SecureString part correctly.
using System.Management.Automation; var mailboxScript = @" New-Mailbox -UserPrincipalName ""name@name.com"" -Database ""db033"" -DisplayName ""last, first"" -Password (ConvertTo-SecureString -String ""P@ssword1"" -AsPlainText -Force) "; using (var ps = PowerShell.Create()) { ps.AddScript(mailboxScript); var results = ps.Invoke(); if (ps.HadErrors) { foreach (var error in ps.Streams.Error) { Console.WriteLine($"Error encountered: {error.ToString()}"); } } }
Key Notes:
- Security: Always prioritize the first method. Storing plaintext passwords in script strings is a security risk, and creating the SecureString in C# keeps sensitive data handled properly.
- Permissions: Ensure your ASP.NET application's identity has the necessary Exchange permissions to run
New-Mailboxvia PowerShell. - Cleanup: Use the
usingstatement to dispose of thePowerShellinstance properly and avoid resource leaks.
内容的提问来源于stack exchange,提问作者Bbb

