• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Automation.PSCommand类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Management.Automation.PSCommand的典型用法代码示例。如果您正苦于以下问题:C# PSCommand类的具体用法?C# PSCommand怎么用?C# PSCommand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



PSCommand类属于System.Management.Automation命名空间,在下文中一共展示了PSCommand类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
                    }
                }
            });
        }
开发者ID:Newtopian,项目名称:nuget,代码行数:17,代码来源:RunspaceDispatcher.cs


示例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];
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:38,代码来源:DebugService.cs


示例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];
        }
开发者ID:PowerShellPowered,项目名称:PowerShellConnect,代码行数:25,代码来源:ExecutionSession.cs


示例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];
        }
开发者ID:sunnyc7,项目名称:PowerShellEditorServices,代码行数:42,代码来源:DebugService.cs


示例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();
     }
 }
开发者ID:KameronHott,项目名称:Work,代码行数:27,代码来源:Exchange.cs


示例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();
                }
            }
        }
开发者ID:KameronHott,项目名称:Work,代码行数:31,代码来源:Exchange.cs


示例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();
        }
开发者ID:mauroa,项目名称:NuGet.VisualStudioExtension,代码行数:35,代码来源:HostUtilities.cs


示例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;
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:10,代码来源:PSCommand.cs


示例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;
     }
 }
开发者ID:40a,项目名称:PowerShell,代码行数:15,代码来源:PSCommand.cs


示例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 + "]");
                    }
                    
                }
            }

        }
开发者ID:Eugene-Ishkov,项目名称:RestService,代码行数:54,代码来源:ExchManager.cs


示例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());
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:14,代码来源:PowerShellContextTests.cs


示例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");
            }
        }
开发者ID:KnowMoreIT,项目名称:CloudPanel-Service,代码行数:53,代码来源:ExchActions.cs


示例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());
            }
        }
开发者ID:KnowMoreIT,项目名称:CloudPanel-Service,代码行数:17,代码来源:ExchActions.cs


示例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();
                }
            }
        }
开发者ID:Eugene-Ishkov,项目名称:RestService,代码行数:39,代码来源:ExchMailboxManager.cs


示例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);
        }
开发者ID:juvchan,项目名称:PowerShellEditorServices,代码行数:23,代码来源:PowerShellContextTests.cs


示例16: 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;
        }
开发者ID:PowerShellPowered,项目名称:PowerShellConnect,代码行数:23,代码来源:ExecutionSession.cs


示例17: GetCommandInfo

        private async Task<CommandInfo> GetCommandInfo(string commandName)
        {
            PSCommand command = new PSCommand();
            command.AddCommand("Get-Command");
            command.AddArgument(commandName);

            var results = await this.powerShellContext.ExecuteCommand<CommandInfo>(command);
            return results.FirstOrDefault();
        }
开发者ID:modulexcite,项目名称:PowerShellEditorServices,代码行数:9,代码来源:LanguageService.cs


示例18: 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());
        }
开发者ID:modulexcite,项目名称:PowerShellEditorServices,代码行数:37,代码来源:LanguageServer.cs


示例19: HandleShowOnlineHelpRequest

        protected async Task HandleShowOnlineHelpRequest(
            string helpParams,
            RequestContext<object> requestContext)
        {
            if (helpParams == null) { helpParams = "get-help"; }

            var psCommand = new PSCommand();
            psCommand.AddCommand("Get-Help");
            psCommand.AddArgument(helpParams);
            psCommand.AddParameter("Online");

            await editorSession.PowerShellContext.ExecuteCommand<object>(
                    psCommand);

            await requestContext.SendResult(null);
        }
开发者ID:modulexcite,项目名称:PowerShellEditorServices,代码行数:16,代码来源:LanguageServer.cs


示例20: 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;
 }
开发者ID:nickchal,项目名称:pash,代码行数:21,代码来源:RunspaceRef.cs



注:本文中的System.Management.Automation.PSCommand类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Automation.PSCredential类代码示例发布时间:2022-05-26
下一篇:
C# Automation.PSCmdlet类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap