本文整理汇总了C#中System.Management.Automation.PSCommand类的典型用法代码示例。如果您正苦于以下问题:C# PSCommand类的具体用法?C# PSCommand怎么用?C# PSCommand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PSCommand类属于System.Management.Automation命名空间,在下文中一共展示了PSCommand类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InvokeCommands
public void InvokeCommands(PSCommand[] profileCommands)
{
WithLock(() =>
{
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = _runspace;
foreach (PSCommand command in profileCommands)
{
powerShell.Commands = command;
powerShell.AddCommand("out-default");
powerShell.Invoke();
}
}
});
}
示例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)
{
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];
}
示例3: Create
public PSSession Create(string userName, SecureString password, string connectionUri, string schemauri, Action<PSDataStreams> psDataStreamAction)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentOutOfRangeException("userName");
}
if (password == null)
{
throw new ArgumentOutOfRangeException("password");
}
if (string.IsNullOrEmpty(connectionUri))
{
throw new ArgumentOutOfRangeException("connectionUri");
}
this.runspace.SetCredentialVariable(userName, password);
var command = new PSCommand();
string importpssessionscript = Constants.SessionScripts.NewPSSessionScriptWithBasicAuth;
if (AllowRedirection) importpssessionscript += Constants.SessionScripts.AllowRedirectionInNewPSSession;
command.AddScript(string.Format(importpssessionscript, schemauri, connectionUri));
Collection<PSSession> sessions = this.runspace.ExecuteCommand<PSSession>(command, psDataStreamAction);
if (sessions.Count > 0) this.runspace.SetRunspaceVariable(Constants.ParameterNameStrings.Session, sessions[0]);
return sessions.Count == 0 ? null : sessions[0];
}
示例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)
{
// 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];
}
示例5: 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();
}
}
示例6: assignPhoto
public void assignPhoto(string login, string fileLocation)
{
using (var context = new PrincipalContext(ContextType.Domain, Form1._Domain, Form1._AdminUser, Form1._Password))
{
//Import-RecipientDataProperty -Identity "Scott Carter" -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\StaffPhotos\DJScott1.jpg" -Encoding Byte -ReadCount 0))
PowerShell powershell = PowerShell.Create();
powershell.Runspace = getRunspace();
PSCommand command = new PSCommand();
command.AddScript("Import-RecipientDataProperty -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -Picture -FileData ([Byte[]]$(Get-Content -Path " + '\u0022' + fileLocation + '\u0022' + " -Encoding Byte -ReadCount 0))");
powershell.Commands = command;
try
{
Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
foreach (PSObject result in commandResults)
{
Form1.myForm.lblExchMessage.Text = result.ToString();
Form1.myForm.lblExchMessage.Visible = true;
}
}
catch (Exception e)
{
Form1.myForm.lblExchMessage.Text = e.Message;
Form1.myForm.lblExchMessage.Visible = true;
}
finally
{
powershell.Dispose();
}
}
}
示例7: 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();
}
示例8: PSCommand
internal PSCommand(PSCommand commandToClone)
{
this.commands = new CommandCollection();
foreach (Command command in commandToClone.Commands)
{
Command item = command.Clone();
this.commands.Add(item);
this.currentCommand = item;
}
}
示例9: PSCommand
/// <summary>
/// Internal copy constructor
/// </summary>
/// <param name="commandToClone"></param>
internal PSCommand(PSCommand commandToClone)
{
_commands = new CommandCollection();
foreach (Command command in commandToClone.Commands)
{
Command clone = command.Clone();
// Attach the cloned Command to this instance.
_commands.Add(clone);
_currentCommand = clone;
}
}
示例10: InvokeCommand
internal Collection<PSObject> InvokeCommand(PSCommand command, ExchContext context)
{
if (context == null)
{
throw new ArgumentNullException("Context", "Parametr not defined. [" + _log.Name + "]");
}
PSCredential _credential = GetPSCredential(context);
WSManConnectionInfo _connection = new WSManConnectionInfo(
new Uri(context.Uri),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
_credential);
_connection.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
_connection.MaximumConnectionRedirectionCount = 3;
_connection.SkipCACheck = true;
_connection.SkipCNCheck = true;
using (Runspace _runspace = RunspaceFactory.CreateRunspace(_connection))
{
_runspace.Open();
//_runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Continue");
using (PowerShell _powershell = PowerShell.Create())
{
_powershell.Commands = command;
try
{
//RunspaceInvoke _invoker = new RunspaceInvoke(_runspace);
//Collection<PSObject> _commandResults = _invoker.Invoke(command.ToString());
_powershell.Runspace = _runspace;
Collection<PSObject> _commandResults = _powershell.Invoke();
CheckErrors(_powershell.Streams.Error);
return _commandResults;
//foreach (PSObject _result in _commandResults)
//{
// Console.WriteLine(_result.ToString());
//}
}
catch (Exception ex)
{
throw new Exception(ex.Message + ". [" + _log.Name + "]");
}
}
}
}
示例11: CanExecutePSCommand
public async Task CanExecutePSCommand()
{
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$a = \"foo\"; $a");
var executeTask =
this.powerShellContext.ExecuteCommand<string>(psCommand);
await this.AssertStateChange(PowerShellContextState.Running);
await this.AssertStateChange(PowerShellContextState.Ready);
var result = await executeTask;
Assert.Equal("foo", result.First());
}
示例12: 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");
}
}
示例13: 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());
}
}
示例14: 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();
}
}
}
示例15: CanQueueParallelRunspaceRequests
public async Task CanQueueParallelRunspaceRequests()
{
// Concurrently initiate 4 requests in the session
this.powerShellContext.ExecuteScriptString("$x = 100");
Task<RunspaceHandle> handleTask = this.powerShellContext.GetRunspaceHandle();
this.powerShellContext.ExecuteScriptString("$x += 200");
this.powerShellContext.ExecuteScriptString("$x = $x / 100");
PSCommand psCommand = new PSCommand();
psCommand.AddScript("$x");
Task<IEnumerable<int>> resultTask = this.powerShellContext.ExecuteCommand<int>(psCommand);
// Wait for the requested runspace handle and then dispose it
RunspaceHandle handle = await handleTask;
handle.Dispose();
// At this point, the remaining command executions should execute and complete
int result = (await resultTask).FirstOrDefault();
// 100 + 200 = 300, then divided by 100 is 3. We are ensuring that
// the commands were executed in the sequence they were called.
Assert.Equal(3, result);
}