本文整理汇总了C#中System.Management.Automation.PSCommand.AddCommand方法的典型用法代码示例。如果您正苦于以下问题:C# PSCommand.AddCommand方法的具体用法?C# PSCommand.AddCommand怎么用?C# PSCommand.AddCommand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.Automation.PSCommand
的用法示例。
在下文中一共展示了PSCommand.AddCommand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: disableMailbox
public void disableMailbox(string login)
{
PowerShell powershell = PowerShell.Create();
powershell.Runspace = getRunspace();
PSCommand command = new PSCommand();
command.AddCommand("Disable-Mailbox");
command.AddParameter("Identity", login);
command.AddParameter("Confirm", false);
powershell.Commands = command;
try
{
Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
foreach (PSObject result in commandResults)
{
Console.WriteLine(result.ToString());
}
//Form1.myForm.lblStatus.Text = powershell.Streams.Error.ToString();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
powershell.Dispose();
}
}
示例2: SetBreakpoints
/// <summary>
/// Sets the list of breakpoints for the current debugging session.
/// </summary>
/// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param>
/// <param name="lineNumbers">The line numbers at which breakpoints will be set.</param>
/// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param>
/// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns>
public async Task<BreakpointDetails[]> SetBreakpoints(
ScriptFile scriptFile,
int[] lineNumbers,
bool clearExisting = true)
{
IEnumerable<Breakpoint> resultBreakpoints = null;
if (clearExisting)
{
await this.ClearBreakpointsInFile(scriptFile);
}
if (lineNumbers.Length > 0)
{
// Fix for issue #123 - file paths that contain wildcard chars [ and ] need to
// quoted and have those wildcard chars escaped.
string escapedScriptPath = PowerShellContext.EscapeWildcardsInPath(scriptFile.FilePath);
PSCommand psCommand = new PSCommand();
psCommand.AddCommand("Set-PSBreakpoint");
psCommand.AddParameter("Script", escapedScriptPath);
psCommand.AddParameter("Line", lineNumbers.Length > 0 ? lineNumbers : null);
resultBreakpoints =
await this.powerShellContext.ExecuteCommand<Breakpoint>(
psCommand);
return
resultBreakpoints
.Select(BreakpointDetails.Create)
.ToArray();
}
return new BreakpointDetails[0];
}
示例3: GetProfileCommands
/// <summary>
/// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
/// </summary>
/// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
/// <param name="useTestProfile">used from test not to overwrite the profile file names from development boxes</param>
/// <returns></returns>
internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile)
{
List<PSCommand> commands = new List<PSCommand>();
string allUsersAllHosts = HostUtilities.GetFullProfileFileName(null, false, useTestProfile);
string allUsersCurrentHost = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile);
string currentUserAllHosts = HostUtilities.GetFullProfileFileName(null, true, useTestProfile);
string currentUserCurrentHost = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile);
PSObject dollarProfile = HostUtilities.GetDollarProfile(allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost);
PSCommand command = new PSCommand();
command.AddCommand("set-variable");
command.AddParameter("Name", "profile");
command.AddParameter("Value", dollarProfile);
command.AddParameter("Option", ScopedItemOptions.None);
commands.Add(command);
string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost };
foreach (string profilePath in profilePaths)
{
if (!System.IO.File.Exists(profilePath))
{
continue;
}
command = new PSCommand();
command.AddCommand(profilePath, false);
commands.Add(command);
}
return commands.ToArray();
}
示例4: SetBreakpoints
/// <summary>
/// Sets the list of breakpoints for the current debugging session.
/// </summary>
/// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param>
/// <param name="lineNumbers">The line numbers at which breakpoints will be set.</param>
/// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param>
/// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns>
public async Task<BreakpointDetails[]> SetBreakpoints(
ScriptFile scriptFile,
int[] lineNumbers,
bool clearExisting = true)
{
IEnumerable<Breakpoint> resultBreakpoints = null;
if (clearExisting)
{
await this.ClearBreakpointsInFile(scriptFile);
}
if (lineNumbers.Length > 0)
{
PSCommand psCommand = new PSCommand();
psCommand.AddCommand("Set-PSBreakpoint");
psCommand.AddParameter("Script", scriptFile.FilePath);
psCommand.AddParameter("Line", lineNumbers.Length > 0 ? lineNumbers : null);
resultBreakpoints =
await this.powerShellContext.ExecuteCommand<Breakpoint>(
psCommand);
return
resultBreakpoints
.Select(BreakpointDetails.Create)
.ToArray();
}
return new BreakpointDetails[0];
}
示例5: Get_MailboxSize
/// <summary>
/// Gets a specific users mailbox size
/// </summary>
/// <param name="userGuid"></param>
/// <returns></returns>
public StatMailboxSizes Get_MailboxSize(Guid userGuid, bool isArchive = false)
{
PSCommand cmd = new PSCommand();
cmd.AddCommand("Get-MailboxStatistics");
cmd.AddParameter("Identity", userGuid.ToString());
cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC);
if (isArchive)
cmd.AddParameter("Archive");
_powershell.Commands = cmd;
Collection<PSObject> psObjects = _powershell.Invoke();
if (psObjects.Count > 0)
{
StatMailboxSizes returnSize = new StatMailboxSizes();
foreach (PSObject obj in psObjects)
{
returnSize.UserGuid = userGuid;
returnSize.MailboxDatabase = obj.Members["Database"].Value.ToString();
returnSize.TotalItemSize = obj.Members["TotalItemSize"].Value.ToString();
returnSize.TotalItemSizeInBytes = GetExchangeBytes(returnSize.TotalItemSize);
returnSize.TotalDeletedItemSize = obj.Members["TotalDeletedItemSize"].Value.ToString();
returnSize.TotalDeletedItemSizeInBytes = GetExchangeBytes(returnSize.TotalDeletedItemSize);
int itemCount = 0;
int.TryParse(obj.Members["ItemCount"].Value.ToString(), out itemCount);
returnSize.ItemCount = itemCount;
int deletedItemCount = 0;
int.TryParse(obj.Members["DeletedItemCount"].Value.ToString(), out deletedItemCount);
returnSize.DeletedItemCount = deletedItemCount;
returnSize.Retrieved = DateTime.Now;
break;
}
return returnSize;
}
else
{
if (_powershell.Streams.Error.Count > 0)
throw _powershell.Streams.Error[0].Exception;
if (_powershell.Streams.Warning.Count > 0)
throw new Exception(_powershell.Streams.Warning[0].Message);
throw new Exception("No data was returned");
}
}
示例6: Get_ExchangeGuid
public Guid Get_ExchangeGuid(string identity)
{
PSCommand cmd = new PSCommand();
cmd.AddCommand("Get-Mailbox");
cmd.AddParameter("Identity", identity);
cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC);
_powershell.Commands = cmd;
Collection<PSObject> psObjects = _powershell.Invoke();
if (_powershell.HadErrors)
throw _powershell.Streams.Error[0].Exception;
else
{
var foundUser = psObjects[0];
return Guid.Parse(foundUser.Properties["ExchangeGuid"].Value.ToString());
}
}
示例7: Create
public void Create(ExchMailbox mailbox)
{
if (string.IsNullOrEmpty(mailbox.Domain))
{
throw new Exception("Mailbox domain not defined. [" + _log.Name + "]");
}
ExchContext _context = ExchManager.Instance.Config.GetContext(mailbox.Domain);
if(_context == null)
{
throw new Exception("Exchange context not defined for domain <" + mailbox.Domain + ">. [" + _log.Name + "]");
}
mailbox.Context = _context;
string _database = ExchManager.Instance.Config.GetDatabase(mailbox);
if (string.IsNullOrEmpty(_database))
{
throw new Exception("Mailbox database not defined. [" + _log.Name + "]");
}
mailbox.Database = _database;
PSCommand _command = new PSCommand();
_command.AddCommand("Enable-Mailbox");
_command.AddParameter("Identity", mailbox.Identity);
_command.AddParameter("DomainController", mailbox.Context.Pdc);
_command.AddParameter("Database", _database);
Collection<PSObject> _result = ExchManager.Instance.InvokeCommand(_command, _context);
foreach(PSObject _rec in _result)
{
if (_rec.Properties["PrimarySmtpAddress"] != null)
{
mailbox.Address = _rec.Properties["PrimarySmtpAddress"].Value.ToString();
}
}
}
示例8: ImportPSSession
public PSModuleInfo ImportPSSession(PSSession session, Action<PSDataStreams> psDataStreamAction)
{
if (session == null)
{
throw new ArgumentOutOfRangeException("session");
}
var command = new PSCommand();
command.AddCommand(Constants.SessionScripts.ImportPSSession);
command.AddParameter(Constants.ParameterNameStrings.Session, session);
Collection<PSModuleInfo> modules;
try
{
modules = this.runspace.ExecuteCommand<PSModuleInfo>(command, psDataStreamAction);
if (modules.Count > 0) return modules[0];
}
catch (Exception)
{
return null;
}
return null;
}
示例9: Get_MailboxSizes
/// <summary>
/// Gets a list of mailbox sizes Exchange
/// </summary>
/// <returns></returns>
public List<MailboxUser> Get_MailboxSizes()
{
PowerShell powershell = null;
try
{
// DEBUG
logger.Debug("Retrieving a list of mailbox users from the SQL database...");
// Start clock
Stopwatch stopwatch = Stopwatch.StartNew();
// Get a list of users from the database
List<ADUser> allUsers = DbSql.Get_Users();
// Our return object of information
List<MailboxUser> users = new List<MailboxUser>();
// Now loop through the databases and query the information
foreach (ADUser user in allUsers)
{
if (user.MailboxPlanID > 0)
{
// DEBUG
logger.Debug("Retrieving mailbox statistics for user " + user);
// Our MailboxUser object to store this users information
MailboxUser currentUser = new MailboxUser();
try
{
// Run commands
powershell = PowerShell.Create();
powershell.Runspace = runspace;
// Get Databases
PSCommand cmd = new PSCommand();
cmd.AddCommand("Get-MailboxStatistics");
cmd.AddParameter("Identity", user.UserPrincipalName);
cmd.AddParameter("DomainController", this.domainController);
powershell.Commands = cmd;
// Now read the returned values
Collection<PSObject> foundStatistics = powershell.Invoke();
foreach (PSObject o in foundStatistics)
{
currentUser.UserPrincipalName = user.UserPrincipalName;
currentUser.ItemCount = int.Parse(o.Members["ItemCount"].Value.ToString(), CultureInfo.InvariantCulture);
currentUser.DeletedItemCount = int.Parse(o.Members["DeletedItemCount"].Value.ToString(), CultureInfo.InvariantCulture);
currentUser.TotalItemSize = o.Members["TotalItemSize"].Value.ToString();
currentUser.TotalDeletedItemSize = o.Members["TotalDeletedItemSize"].Value.ToString();
currentUser.Database = o.Members["Database"].Value.ToString();
currentUser.MailboxDataRetrieved = DateTime.Now;
}
// Log the powershell commands
LogPowershellCommands(ref powershell);
// Find all the errors
if (powershell.HadErrors)
{
// Log all errors detected
foreach (ErrorRecord err in powershell.Streams.Error)
{
logger.Error("Error getting mailbox size for " + user, err.Exception);
// Compile message
StringBuilder sb = new StringBuilder();
sb.AppendLine("Failed to get mailbox size for: " + user);
sb.AppendLine("");
sb.AppendLine("Recommended Action:");
sb.AppendLine("This could be because the user no longer exists in Active Directory but still exists in the database.");
sb.AppendLine("If that is the case simply delete the user from CloudPanel. If the issues stays the same please contact support.");
sb.AppendLine("");
sb.AppendLine("Error:");
sb.AppendLine(err.Exception.ToString());
// Send message
Support.SendEmailMessage("Failed to get mailbox size for: " + user, sb.ToString());
}
// Log all warnings detected
foreach (WarningRecord err in powershell.Streams.Warning)
{
logger.Error("Warning getting mailbox size for " + user + ": " + err.Message);
}
}
else
{
logger.Info("Successfully retrieved mailbox size information for " + currentUser.UserPrincipalName);
users.Add(currentUser);
}
}
catch (Exception ex)
{
//.........这里部分代码省略.........
示例10: Get_CalendarName
/// <summary>
/// Gets the calendar name because it can be in a different language
/// </summary>
/// <param name="userPrincipalName"></param>
/// <returns></returns>
public string Get_CalendarName(string userPrincipalName)
{
PowerShell powershell = null;
try
{
// DEBUG //
logger.Debug("Getting calendar name for " + userPrincipalName);
// Run commands
powershell = PowerShell.Create();
powershell.Runspace = runspace;
//
// First we need to remove the default calendar permissions and add the security group
//
PSCommand cmd = new PSCommand();
cmd.AddCommand("Get-MailboxFolderStatistics");
cmd.AddParameter("Identity", userPrincipalName);
cmd.AddParameter("FolderScope", "Calendar");
cmd.AddParameter("DomainController", this.domainController);
powershell.Commands = cmd;
// Default calendar name in English
string calendarName = "Calendar";
Collection<PSObject> obj = powershell.Invoke();
if (obj != null && obj.Count > 0)
{
foreach (PSObject ps in obj)
{
if (ps.Members["FolderType"] != null)
{
string folderType = ps.Members["FolderType"].Value.ToString();
if (folderType.Equals("Calendar"))
{
calendarName = ps.Members["Name"].Value.ToString();
break;
}
}
}
}
return calendarName;
}
catch (Exception ex)
{
logger.Error("Error getting calendar name for " + userPrincipalName, ex);
// Return the default name
return "Calendar";
}
finally
{
if (powershell != null)
powershell.Dispose();
}
}
示例11: HandleExpandAliasRequest
private async Task HandleExpandAliasRequest(
string content,
RequestContext<string> requestContext)
{
var script = @"
function __Expand-Alias {
param($targetScript)
[ref]$errors=$null
$tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) |
Sort Start -Descending
foreach ($token in $tokens) {
$definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition
if($definition) {
$lhs=$targetScript.Substring(0, $token.Start)
$rhs=$targetScript.Substring($token.Start + $token.Length)
$targetScript=$lhs + $definition + $rhs
}
}
$targetScript
}";
var psCommand = new PSCommand();
psCommand.AddScript(script);
await this.editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand);
psCommand = new PSCommand();
psCommand.AddCommand("__Expand-Alias").AddArgument(content);
var result = await this.editorSession.PowerShellContext.ExecuteCommand<string>(psCommand);
await requestContext.SendResult(result.First().ToString());
}
示例12: CreatePsCommandNotOverriden
private PSCommand CreatePsCommandNotOverriden(string line, bool isScript, bool? useNewScope)
{
PSCommand command = new PSCommand();
if (isScript)
{
if (useNewScope.HasValue)
{
command.AddScript(line, useNewScope.Value);
return command;
}
command.AddScript(line);
return command;
}
if (useNewScope.HasValue)
{
command.AddCommand(line, useNewScope.Value);
return command;
}
command.AddCommand(line);
return command;
}
示例13: NewLitigationHold
public void NewLitigationHold(string userPrincipalName, string comment, string url, int? days)
{
try
{
this.logger.Debug("Enabling litigation hold for " + userPrincipalName);
PSCommand cmd = new PSCommand();
cmd.AddCommand("Set-Mailbox");
cmd.AddParameter("Identity", userPrincipalName);
cmd.AddParameter("LitigationHoldEnabled", true);
if (!string.IsNullOrEmpty(comment))
cmd.AddParameter("RetentionComment", comment);
else
cmd.AddParameter("RetentionComment", null);
if (!string.IsNullOrEmpty(url))
cmd.AddParameter("RetentionUrl", url);
else
cmd.AddParameter("RetentionUrl", null);
if (days != null)
cmd.AddParameter("LitigationHoldDuration", days);
else
cmd.AddParameter("LitigationHoldDuration", null);
cmd.AddParameter("Confirm", false);
cmd.AddParameter("Force");
cmd.AddParameter("DomainController", domainController);
powershell.Commands = cmd;
Collection<PSObject> obj = powershell.Invoke();
if (powershell.HadErrors)
throw powershell.Streams.Error[0].Exception;
}
catch (Exception ex)
{
this.logger.Error("Failed to enable litigation hold for " + userPrincipalName, ex);
throw;
}
}
示例14: DeleteDistributionGroup
public void DeleteDistributionGroup(string identity)
{
try
{
PSCommand cmd = new PSCommand();
cmd.AddCommand("Remove-DistributionGroup");
cmd.AddParameter("Identity", identity);
cmd.AddParameter("Confirm", false);
cmd.AddParameter("DomainController", domainController);
powershell.Commands = cmd;
powershell.Invoke();
if (powershell.HadErrors)
{
ErrorCategory errCategory = powershell.Streams.Error[0].CategoryInfo.Category;
string reason = powershell.Streams.Error[0].CategoryInfo.Reason;
if (errCategory != ErrorCategory.NotSpecified && !reason.Equals("ManagementObjectNotFoundException"))
throw powershell.Streams.Error[0].Exception;
else
this.logger.Info("Failed to remove distribution group " + identity + " because it didn't exist");
}
}
catch (Exception ex)
{
this.logger.Error("Failed to delete distribution group " + identity, ex);
throw;
}
}
示例15: DeleteAllMailboxes
public void DeleteAllMailboxes(string companyCode)
{
try
{
this.logger.Info("Disabling all mailboxes for " + companyCode);
PSCommand cmd = new PSCommand();
cmd.AddCommand("Get-Mailbox");
cmd.AddParameter("Filter", string.Format("CustomAttribute1 -eq '{0}'", companyCode));
cmd.AddParameter("DomainController", domainController);
cmd.AddCommand("Disable-Mailbox");
cmd.AddParameter("Confirm", false);
cmd.AddParameter("DomainController", domainController);
powershell.Commands = cmd;
powershell.Invoke();
if (powershell.HadErrors)
throw powershell.Streams.Error[0].Exception;
}
catch (Exception ex)
{
this.logger.Error("Failed to disable all mailboxes for company " + companyCode, ex);
throw;
}
}