Пример #1
0
        private SecureString ConvertToSecureString(string secret)
        {
            var results = InvokeCommand.InvokeScript(
                script: @"
                    param ([string] $secret)

                    ConvertTo-SecureString -String $secret -AsPlainText -Force
                ",
                useNewScope: false,
                writeToPipeline: System.Management.Automation.Runspaces.PipelineResultTypes.None,
                input: null,
                args: new object[] { secret });

            return((results.Count == 1) ? results[0].BaseObject as SecureString : null);
        }
Пример #2
0
        private void ExecuteRepl(IScriptCSSession session)
        {
            InvokeCommand.InvokeScript("write-host \"`nscriptcs REPL`ntype 'exit' to return to PowerShell`n\"").FirstOrDefault();
            while (true)
            {
                var input = this.InvokeCommand.InvokeScript("read-host -prompt \"`nscriptcs\"").FirstOrDefault();
                var cmd   = input.ToString();
                if ("exit" == cmd.ToLowerInvariant().Trim())
                {
                    return;
                }

                Execute(session, cmd);
            }
        }
        public virtual void InvokeScript(string script)
        {
            var resultTypes = PipelineResultTypes.Error | PipelineResultTypes.Output;

            try {
                InvokeCommand.InvokeScript(script, false, resultTypes, null, null);
            } catch (Exception ex) {
                LoggingService.LogInternalError("PowerShell script error.", ex);
                var errorRecord = new ErrorRecord(ex,
                                                  "PackageManagementInternalError",
                                                  ErrorCategory.InvalidOperation,
                                                  null);
                WriteError(errorRecord);
            }
        }
Пример #4
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            if (_hasRegisteredDirectoryHook)
            {
                return;
            }

            InvokeCommand.InvokeScript(@"Set-PSBreakpoint -Variable pwd -Mode Write -Action {
                [Jump.Location.JumpLocationCommand]::UpdateTime($($(Get-Item -Path $(Get-Location))).PSPath);
            }");

            _hasRegisteredDirectoryHook = true;
        }
        private void ConnectToGoPrtgServer(GoPrtgServer server)
        {
            if (client != null && client.Server == server.Server && client.UserName == server.UserName)
            {
                WriteColorOutput($"\nAlready connected to {server.Server} as {server.UserName}\n", ConsoleColor.Yellow);
            }
            else
            {
                var passhash = InvokeCommand.InvokeScript($"ConvertTo-SecureString {server.PassHash}").First().BaseObject as SecureString;

                var credential = new PSCredential(server.UserName, passhash);

                Connect(server.Server, credential);

                WriteColorOutput($"\nConnected to {server.Server} as {server.UserName}\n", ConsoleColor.Green);
            }
        }
Пример #6
0
 /// <summary>
 /// パスワードを決定して返す。
 /// </summary>
 /// <param name="password"></param>
 /// <param name="credential"></param>
 /// <param name="passwordFile"></param>
 /// <returns></returns>
 protected string GetPassword(string password, PSCredential credential, string passwordFile, SshSession session)
 {
     if (credential != null)
     {
         //  Credentialからパスワード読み取り
         return(System.Runtime.InteropServices.Marshal.PtrToStringUni(
                    System.Runtime.InteropServices.Marshal.SecureStringToGlobalAllocUnicode(credential.Password)));
     }
     else if (!string.IsNullOrEmpty(passwordFile) && File.Exists(passwordFile))
     {
         //  PasswordFileからパスワード読み取り
         try
         {
             //  ===========================================
             //  $cred = Get-Credential
             //  $cred.Password | ConvertFrom-SecureString | Set-Content .\pwoutput.txt
             //  ===========================================
             //  等で、PowerShellで暗号化したパスワードファイルをした場合
             var res = InvokeCommand.InvokeScript(
                 SessionState,
                 InvokeCommand.NewScriptBlock(
                     "[System.Runtime.InteropServices.Marshal]::PtrToStringBSTR(" +
                     "[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(" +
                     $"(Get-Content \"{passwordFile}\" | ConvertTo-SecureString)))"));
             if (res != null && res.Count > 0)
             {
                 return(res[0].ToString());
             }
         }
         catch
         {
             //  PowerShellで暗号化したパスワードファイルの読み込みに失敗した場合、平文テキストとして読み込み
             //  複数行の場合、最初の1行のみをパスワードとして判断
             using (var sr = new StreamReader(passwordFile, new UTF8Encoding(false)))
             {
                 return(sr.ReadLine());
             }
         }
     }
     else if (string.IsNullOrEmpty(password) && (session?.IsPasswordEmpty() ?? true))
     {
         //  Password, PasswordFile, Credentialの全部が空の場合
         return(ReadPassword());
     }
     return(password);
 }
        /// <inheritdoc/>
        protected override void ProcessRecord()
        {
            var scriptToRun = new StringBuilder();
            var _           = scriptToRun.Append(DisableAzPredictor._DisableStatements[0]);

            if (AllSession.IsPresent)
            {
                _ = scriptToRun.Append(";Write-Host \"To disable Az Predictor, please edit your profile ($PROFILE) and remove the following lines:`nImport-Module Az.Tools.Predictor`nSet-PSReadLineOption -PredictionSource HistoryAndPlugin`n\"");
            }

            InvokeCommand.InvokeScript(scriptToRun.ToString());

            if (PassThru.IsPresent)
            {
                WriteObject(true);
            }
        }
Пример #8
0
        protected override void EndProcessing()
        {
            if (_objects.Count == 0)
            {
                ExecuteWrite(WinFormsClipboard.Clear);
            }
            else
            {
                string cmd = "$input | out-string";

                if (_width.HasValue)
                {
                    cmd = String.Format(CultureInfo.InvariantCulture, "$input | out-string -width {0}", _width.Value);
                }

                StringBuilder         output  = new StringBuilder();
                Collection <PSObject> results = InvokeCommand.InvokeScript(cmd, false, PipelineResultTypes.None, _objects);

                foreach (PSObject obj in results)
                {
                    string text = obj.ToString();
                    if (!_noTrimEnd)
                    {
                        StringBuilder trimmedOutput = new StringBuilder();
                        string[]      lines         = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                        foreach (string line in lines)
                        {
                            trimmedOutput.AppendLine(line.TrimEnd(null));
                        }
                        text = trimmedOutput.ToString();
                    }
                    output.Append(text);
                }

                if (this.ParameterSetName == ParameterSetAsText)
                {
                    ExecuteWrite(
                        () => WinFormsClipboard.SetText(output.ToString()));
                }
                else
                {
                    CopyAsFile(output.ToString());
                }
            }
        }
Пример #9
0
        // Methods
        protected override void ProcessRecord()
        {
            var script     = string.Empty;
            var scriptItem = Item;

            if (Item != null)
            {
                if (!IsPowerShellScriptItem(Item))
                {
                    return;
                }
                script = Item[Templates.Script.Fields.ScriptBody];
            }
            else if (Path != null)
            {
                var drive = IsCurrentDriveSitecore ? CurrentDrive : ApplicationSettings.ScriptLibraryDb;

                scriptItem = PathUtilities.GetItem(Path, drive, ApplicationSettings.ScriptLibraryPath);

                if (scriptItem == null)
                {
                    WriteError(typeof(ItemNotFoundException), $"The script '{Path}' cannot be found.",
                               ErrorIds.ItemNotFound, ErrorCategory.ObjectNotFound, Path);
                    return;
                }
                if (!IsPowerShellScriptItem(scriptItem))
                {
                    return;
                }
                script = scriptItem[Templates.Script.Fields.ScriptBody];
            }

            if (!ShouldProcess(scriptItem.GetProviderPath(), "Invoke script"))
            {
                return;
            }

            var sendToPipeline = InvokeCommand.InvokeScript(script, false,
                                                            PipelineResultTypes.Output | PipelineResultTypes.Error, null, ArgumentList);

            if (sendToPipeline != null && sendToPipeline.Any())
            {
                WriteObject(sendToPipeline);
            }
        }
Пример #10
0
        internal List <GoPrtgServer> GetServers()
        {
            var servers = InvokeCommand.InvokeScript($"{goPrtgFunction} | ConvertFrom-Csv -Header \"{nameof(GoPrtgServer.Server)}\",\"{nameof(GoPrtgServer.Alias)}\",\"{nameof(GoPrtgServer.UserName)}\",\"{nameof(GoPrtgServer.PassHash)}\"");

            var objs = servers.Select(o =>
            {
                var s = new GoPrtgServer(o);

                if (client != null && s.Server == client.Server && s.UserName == client.UserName)
                {
                    s.IsActive = true;
                }

                return(s);
            }).ToList();

            return(objs);
        }
Пример #11
0
        /// <inheritdoc/>
        protected override void ProcessRecord()
        {
            var scriptToRun = new StringBuilder();
            var _           = scriptToRun.Append(EnableAzPredictor._EnableStatements[1]);

            if (AllSession.IsPresent)
            {
                _ = scriptToRun.Append($";Add-Content -Path $PROFILE -Value \"`n{string.Join("`n", EnableAzPredictor._EnableStatements)}\" -NoNewline -Encoding UTF8 -Force")
                    .Append($";Write-Host \"User profile ($PROFILE) has been updated.`n\"");
            }

            InvokeCommand.InvokeScript(scriptToRun.ToString());

            if (PassThru.IsPresent)
            {
                WriteObject(true);
            }
        }
Пример #12
0
        public void ExecuteScript(string packageInstallPath, string scriptRelativePath, object packageObject, Installation.InstallationTarget target)
        {
            IPackage package = (IPackage)packageObject;

            // If we don't have a project, we're at solution level
            string        projectName     = target.Name;
            FrameworkName targetFramework = target.GetSupportedFrameworks().FirstOrDefault();

            VsProject targetProject = target as VsProject;

            EnvDTE.Project project  = targetProject == null ? null : targetProject.DteProject;
            string         fullPath = Path.Combine(packageInstallPath, scriptRelativePath);

            if (!File.Exists(fullPath))
            {
                VsNuGetTraceSources.VsPowerShellScriptExecutionFeature.Error(
                    "missing_script",
                    "[{0}] Unable to locate expected script file: {1}",
                    projectName,
                    fullPath);
            }
            else
            {
                var    psVariable = SessionState.PSVariable;
                string toolsPath  = Path.GetDirectoryName(fullPath);

                // set temp variables to pass to the script
                psVariable.Set("__rootPath", packageInstallPath);
                psVariable.Set("__toolsPath", toolsPath);
                psVariable.Set("__package", package);
                psVariable.Set("__project", project);

                string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project";
                Log(MessageLevel.Info, String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));

                InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);

                // clear temp variables
                psVariable.Remove("__rootPath");
                psVariable.Remove("__toolsPath");
                psVariable.Remove("__package");
                psVariable.Remove("__project");
            }
        }
Пример #13
0
        protected override void ProcessRecord()
        {
            try
            {
                Latch.FeatureMode twoFactor, lockOnRequest = Latch.FeatureMode.DISABLED;
                if (String.IsNullOrEmpty(AppId))
                {
                    AppId = InputHelper.GetUserInput(this, "AppId");
                }
                if (String.IsNullOrEmpty(SecretKey))
                {
                    SecretKey = InputHelper.GetUserInput(this, "SecretKey");
                }
                if (String.IsNullOrEmpty(OperationId))
                {
                    OperationId = InputHelper.GetUserInput(this, "OperationId");
                }
                if (String.IsNullOrEmpty(Name))
                {
                    Name = InputHelper.GetUserInput(this, "Name");
                }
                if (String.IsNullOrEmpty(TwoFactor))
                {
                    TwoFactor = InputHelper.GetUserInput(this, String.Format("TwoFactor \"( {0} | {1} | {2} )\"",
                                                                             Latch.FeatureMode.DISABLED.ToString(), Latch.FeatureMode.MANDATORY.ToString(), Latch.FeatureMode.OPT_IN.ToString()));
                }
                if (String.IsNullOrEmpty(LockOnRequest))
                {
                    LockOnRequest = InputHelper.GetUserInput(this, String.Format("Name \"( {0} | {1} | {2} )\"",
                                                                                 Latch.FeatureMode.DISABLED.ToString(), Latch.FeatureMode.MANDATORY.ToString(), Latch.FeatureMode.OPT_IN.ToString()));
                }

                Enum.TryParse(TwoFactor, true, out twoFactor);
                Enum.TryParse(LockOnRequest, true, out lockOnRequest);

                Latch latch = new Latch(AppId, SecretKey);
                WriteObject(latch.UpdateOperation(OperationId, Name, twoFactor, lockOnRequest));
            }
            catch (Exception ex)
            {
                InvokeCommand.InvokeScript(String.Format("Write-Host Error: \"{0}\"", ex.Message));
            }
        }
Пример #14
0
        private PrtgClient GetNewClient()
        {
            var oldClient = client;

            if (Credential == null)
            {
                Credential = GetNewCredential(oldClient.UserName);
            }

            //Invoke Connect-PrtgServer via PowerShell Invocation instead of just calling the cmdlet directly
            //so we can mock it in Update-GoPrtgCredential's unit tests (otherwise the new PrtgClient's HttpClient
            //would try and connect to a PRTG Server)

            var argsVar = PrtgSessionState.PSEdition == PSEdition.Desktop ? "input" : "args";

            InvokeCommand.InvokeScript($"Connect-PrtgServer -Server ${argsVar}[0] -Credential ${argsVar}[1] -Force", new object[] { oldClient.Server, Credential });

            //Return the PrtgSessionState client
            return(client);
        }
Пример #15
0
        protected void ExecuteScript(
            string rootPath,
            string scriptFileName,
            IPackage package,
            FrameworkName targetFramework,
            Project project)
        {
            string scriptPath, fullPath;

            if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptPath))
            {
                fullPath = Path.Combine(rootPath, scriptPath);
            }
            else
            {
                return;
            }

            if (File.Exists(fullPath))
            {
                var    psVariable = SessionState.PSVariable;
                string toolsPath  = Path.GetDirectoryName(fullPath);

                // set temp variables to pass to the script
                psVariable.Set("__rootPath", rootPath);
                psVariable.Set("__toolsPath", toolsPath);
                psVariable.Set("__package", package);
                psVariable.Set("__project", project);

                string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project";
                WriteVerbose(String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));
                InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);

                // clear temp variables
                psVariable.Remove("__rootPath");
                psVariable.Remove("__toolsPath");
                psVariable.Remove("__package");
                psVariable.Remove("__project");
            }
        }
        protected override void ProcessRecord()
        {
            var clientCredentials = GetClientCredentials();

            using (var identityClient = new EryphIdentityClient(GetCredentials("identity:clients:write:all")))
            {
                foreach (var name in Name)
                {
                    var result = identityClient.Clients.Create(new Client
                    {
                        Name          = name,
                        Description   = Description,
                        AllowedScopes = AllowedScopes
                    });

                    if (AddToConfiguration)
                    {
                        var asDefault = !AsDefault ? "" : " -AsDefault";
                        InvokeCommand.InvokeScript(
                            $@"$args[0] | New-EryphClientCredentials -Id ""{result.Id}"" -IdentityEndpoint ""{clientCredentials.IdentityProvider}"" -Configuration ""{clientCredentials.Configuration}"" | Add-EryphClientConfiguration -Name ""{result.Name}""{asDefault}",
                            result.Key);

                        WriteObject(new Client(result.Id, result.Name, result.Description, result.AllowedScopes));
                    }
                    else
                    {
                        WriteObject(new CreatedClient
                        {
                            Id               = result.Id,
                            Name             = result.Name,
                            AllowedScopes    = result.AllowedScopes.ToArray(),
                            Description      = result.Description,
                            IdentityProvider = clientCredentials.IdentityProvider,
                            PrivateKey       = result.Key
                        });
                    }
                }
            }
        }
Пример #17
0
        protected ScaffoldingNuGetBaseCmdlet(ISolutionManager solutionManager, IVsPackageManagerFactory vsPackageManagerFactory)
        {
            // Command intrinsics (and hence DefaultProjectName) can't be accessed until the PSCmdlet enters the "ProcessRecord" phase,
            // so we have to defer evaluation of the following things until then. To support unit testing, it's possible to override
            // their instantiation by passing a non-null instance to the constructor.

            _packageManagerFactory = new Lazy <IVsPackageManagerFactory>(() => {
                return(vsPackageManagerFactory ?? new PowerShellPackageManagerFactory(InvokeCommand));
            });
            _packageManager = new Lazy <IPackageManager>(() => {
                return(_packageManagerFactory.Value.CreatePackageManager());
            });
            _solutionManager = new Lazy <ISolutionManager>(() => {
                if (solutionManager != null)
                {
                    return(solutionManager);
                }

                var getProjectResults  = InvokeCommand.InvokeScript("(Get-Project).Name").ToList();
                var defaultProjectName = getProjectResults.Count == 1 ? (string)getProjectResults.Single().BaseObject : null;
                return(new ScaffoldingSolutionManager(defaultProjectName));
            });
        }
Пример #18
0
        private void ExecuteInitialize()
        {
            object oldValue = null;

            if (_Exists)
            {
                oldValue = _Config.Value;
            }
            else
            {
                _Config = new Config();
            }

            _Config.Name   = _NameName;
            _Config.Module = _NameModule;
            _Config.Value  = Value;

            ApplyCommonSettings();

            // Do it again even though it is part of common settings
            // The common settings are only applied if the parameter is set, this always will.
            _Config.AllowDelete = AllowDelete.ToBool();

            _Config.Initialized = true;
            ConfigurationHost.Configurations[_NameFull] = _Config;

            if (_Exists)
            {
                try { ApplyValue(oldValue); }
                catch (Exception e)
                {
                    InvokeCommand.InvokeScript(true, ScriptBlock.Create(String.Format(_updateError, _NameFull, EnableException.ToBool())), null, e);
                    _KillIt = true;
                    return;
                }
            }
        }
Пример #19
0
        protected override void BeginProcessing()
        {
            if (!this.MyInvocation.BoundParameters.ContainsKey(nameof(Name)))
            {
                // Let the friendly Name be the module name.
                var results = InvokeCommand.InvokeScript(
                    script: @"param([string] $path) Split-Path -Path $path -Leaf",
                    useNewScope: true,
                    writeToPipeline: PipelineResultTypes.Error,
                    input: null,
                    args: new object[] { ModuleName });
                string moduleName = (results.Count == 1 && results[0] != null) ? (string)results[0].BaseObject : null;
                if (string.IsNullOrEmpty(moduleName))
                {
                    var msg = string.Format(CultureInfo.InvariantCulture,
                                            @"Unable to get friendly name from ModuleName : {0}",
                                            ModuleName);

                    ThrowTerminatingError(
                        new ErrorRecord(
                            exception: new PSInvalidOperationException(msg),
                            errorId: "RegisterSecretVaultCommandCannotParseModuleName",
                            errorCategory: ErrorCategory.InvalidOperation,
                            this));
                }

                var extension = System.IO.Path.GetExtension(moduleName);
                if (extension.Equals(".psd1", StringComparison.OrdinalIgnoreCase) ||
                    extension.Equals(".psm1", StringComparison.OrdinalIgnoreCase))
                {
                    moduleName = System.IO.Path.GetFileNameWithoutExtension(moduleName);
                }

                Name = moduleName;
            }
        }
        void ExecutePSScriptInternal(ScriptMessage message)
        {
            try {
                var request = new ScriptExecutionRequest(
                    message.ScriptPath,
                    message.InstallPath,
                    message.Identity,
                    message.Project);

                var psVariable = SessionState.PSVariable;

                // set temp variables to pass to the script
                psVariable.Set("__rootPath", request.InstallPath);
                psVariable.Set("__toolsPath", request.ToolsPath);
                psVariable.Set("__package", request.ScriptPackage);
                psVariable.Set("__project", request.Project);

                if (request.ScriptPath != null)
                {
                    string command = "& " + PathUtility.EscapePSPath(request.ScriptPath) + " $__rootPath $__toolsPath $__package $__project";
                    LogCore(MessageLevel.Info, String.Format(CultureInfo.CurrentCulture, "Executing script file '{0}'", request.ScriptPath));

                    InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);
                }

                // clear temp variables
                SessionState.PSVariable.Remove("__rootPath");
                SessionState.PSVariable.Remove("__toolsPath");
                SessionState.PSVariable.Remove("__package");
                SessionState.PSVariable.Remove("__project");
            } catch (Exception ex) {
                message.Exception = ex;
            } finally {
                message.EndSemaphore.Release();
            }
        }
Пример #21
0
 protected Collection <PSObject> InvokeBody(ScriptBlock body) => InvokeCommand.InvokeScript(useLocalScope: false, body, input: null, args: null);
Пример #22
0
 internal void LoadFunction(string str)
 {
     InvokeCommand.InvokeScript(str.Replace("function ", "function global:"));
 }
Пример #23
0
 internal string EncryptString(string str)
 {
     return(InvokeCommand.InvokeScript($"ConvertTo-SecureString {str} -AsPlainText -Force | ConvertFrom-SecureString").First().ToString());
 }
        /// <summary>
        /// Implements the begin action of Set-PSFConfig
        /// </summary>
        protected override void BeginProcessing()
        {
            if (!String.IsNullOrEmpty(Validation) && !ConfigurationHost.Validation.Keys.Contains(Validation.ToLower()))
            {
                InvokeCommand.InvokeScript(String.Format(_scriptErrorValidationValidation, Validation, String.Join(", ", ConfigurationHost.Validation.Keys), EnableException.ToBool()));
                _KillIt = true;
                return;
            }

            #region Name Interpretation
            if (!String.IsNullOrEmpty(FullName))
            {
                _NameFull = FullName.Trim('.').ToLower();
                if (!_NameFull.Contains('.'))
                {
                    InvokeCommand.InvokeScript(String.Format(_scriptErrorValidationFullName, FullName, EnableException.ToBool()));
                    _KillIt = true;
                    return;
                }

                int index = _NameFull.IndexOf('.');
                _NameModule = _NameFull.Substring(0, index);
                _NameName   = _NameFull.Substring(index + 1);
            }
            else
            {
                if (!String.IsNullOrEmpty(Module))
                {
                    _NameModule = Module.Trim('.', ' ').ToLower();
                    _NameName   = Name.Trim('.', ' ').ToLower();
                    _NameFull   = String.Format("{0}.{1}", _NameModule, _NameName);
                }
                else
                {
                    _NameFull = Name.Trim('.').ToLower();
                    if (!_NameFull.Contains('.'))
                    {
                        InvokeCommand.InvokeScript(String.Format(_scriptErrorValidationFullName, Name, EnableException.ToBool()));
                        _KillIt = true;
                        return;
                    }

                    int index = _NameFull.IndexOf('.');
                    _NameModule = _NameFull.Substring(0, index);
                    _NameName   = _NameFull.Substring(index + 1);
                }
            }

            if (String.IsNullOrEmpty(_NameModule) || String.IsNullOrEmpty(_NameName))
            {
                InvokeCommand.InvokeScript(String.Format(_scriptErrorValidationName, _NameFull, EnableException.ToBool()));
                _KillIt = true;
                return;
            }
            #endregion Name Interpretation

            _Exists = ConfigurationHost.Configurations.ContainsKey(_NameFull);
            if (_Exists)
            {
                _Config = ConfigurationHost.Configurations[_NameFull];
            }
            _Initialize     = Initialize;
            _Persisted      = !String.IsNullOrEmpty(PersistedValue);
            _PolicyEnforced = (_Exists && _Config.PolicyEnforced);

            // If the setting is already initialized, nothing should be done
            if (_Exists && _Config.Initialized && Initialize)
            {
                _KillIt = true;
            }
        }
Пример #25
0
        /// <summary>
        /// Processes the process phase of the cmdlet
        /// </summary>
        protected override void ProcessRecord()
        {
            #region Perform Transforms
            if ((!_fromStopFunction) && (Target != null))
            {
                Target = ResolveTarget(Target);
            }

            if (!_fromStopFunction)
            {
                if (Exception != null)
                {
                    Exception = ResolveException(Exception);
                }
                else if (ErrorRecord != null)
                {
                    Exception tempException = null;
                    for (int n = 0; n < ErrorRecord.Length; n++)
                    {
                        // If both Exception and ErrorRecord are specified, override the first error record's exception.
                        if ((n == 0) && (Exception != null))
                        {
                            tempException = Exception;
                        }
                        else
                        {
                            tempException = ResolveException(ErrorRecord[n].Exception);
                        }
                        if (tempException != ErrorRecord[n].Exception)
                        {
                            ErrorRecord[n] = new ErrorRecord(tempException, ErrorRecord[n].FullyQualifiedErrorId, ErrorRecord[n].CategoryInfo.Category, ErrorRecord[n].TargetObject);
                        }
                    }
                }
            }

            if (Level != MessageLevel.Warning)
            {
                Level = ResolveLevel(Level);
            }
            #endregion Perform Transforms

            #region Exception Integration

            /*
             *  While conclusive error handling must happen after message handling,
             *  in order to integrate the exception message into the actual message,
             *  it becomes necessary to first integrate the exception and error record parameters into a uniform view
             *
             *  Note: Stop-PSFFunction never specifies this parameter, thus it is not necessary to check,
             *  whether this function was called from Stop-PSFFunction.
             */
            if ((ErrorRecord == null) && (Exception != null))
            {
                ErrorRecord    = new ErrorRecord[1];
                ErrorRecord[0] = new ErrorRecord(Exception, String.Format("{0}_{1}", ModuleName, FunctionName), ErrorCategory.NotSpecified, Target);
            }
            #endregion Exception Integration

            #region Error handling
            PsfExceptionRecord errorRecord = null;
            if (ErrorRecord != null)
            {
                if (!_fromStopFunction)
                {
                    if (EnableException)
                    {
                        foreach (ErrorRecord record in ErrorRecord)
                        {
                            WriteError(record);
                        }
                    }
                }

                errorRecord = LogHost.WriteErrorEntry(ErrorRecord, FunctionName, ModuleName, _Tags, _timestamp, _MessageSystem, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName);
            }
            #endregion Error handling

            LogEntryType channels = LogEntryType.None;

            #region Warning handling
            if (Level == MessageLevel.Warning)
            {
                if (!_silent)
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            WriteWarning(_MessageStreams);
                            channels = channels | LogEntryType.Warning;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        WriteWarning(_MessageStreams);
                        channels = channels | LogEntryType.Warning;
                    }
                }
                WriteDebug(_MessageStreams);
                channels = channels | LogEntryType.Debug;
            }
            #endregion Warning handling

            #region Message handling
            if (!_silent)
            {
                if ((MessageHost.MaximumInformation >= (int)Level) && (MessageHost.MinimumInformation <= (int)Level))
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                            channels = channels | LogEntryType.Information;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        //InvokeCommand.InvokeScript(_writeHostScript, _MessageHost);
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                        channels = channels | LogEntryType.Information;
                    }
                }
            }

            if ((MessageHost.MaximumVerbose >= (int)Level) && (MessageHost.MinimumVerbose <= (int)Level))
            {
                if ((_callStack.Count() > 1) && _callStack.ElementAt(_callStack.Count() - 2).InvocationInfo.BoundParameters.ContainsKey("Verbose"))
                {
                    InvokeCommand.InvokeScript(@"$VerbosePreference = 'Continue'");
                }
                //SessionState.PSVariable.Set("VerbosePreference", ActionPreference.Continue);

                WriteVerbose(_MessageStreams);
                channels = channels | LogEntryType.Verbose;
            }

            if ((MessageHost.MaximumDebug >= (int)Level) && (MessageHost.MinimumDebug <= (int)Level))
            {
                bool restoreInquire = false;
                if (_isDebug)
                {
                    if (Breakpoint.ToBool())
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                    }
                    else
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Continue'"), null, null);
                        restoreInquire = true;
                    }
                    WriteDebug(String.Format("{0} | {1}", Line, _MessageStreams));
                    channels = channels | LogEntryType.Debug;
                }
                else
                {
                    WriteDebug(_MessageStreams);
                    channels = channels | LogEntryType.Debug;
                }

                if (restoreInquire)
                {
                    InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                }
            }
            #endregion Message handling

            #region Logging
            LogEntry entry = LogHost.WriteLogEntry(_MessageSystem, channels, _timestamp, FunctionName, ModuleName, _Tags, Level, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName, File, Line, _callStack, String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), errorRecord, String, StringValues, Target);
            #endregion Logging

            foreach (MessageEventSubscription subscription in MessageHost.Events.Values)
            {
                if (subscription.Applies(entry))
                {
                    try { InvokeCommand.InvokeScript(subscription.ScriptBlock.ToString(), entry); }
                    catch (Exception e) { WriteError(new ErrorRecord(e, "", ErrorCategory.NotSpecified, entry)); }
                }
            }
        }
Пример #26
0
 /// <summary>
 /// Invokes a string of text-based scriptcode
 /// </summary>
 /// <param name="ScriptCode">The script code to execute</param>
 /// <returns>Returns whatever it will return</returns>
 public System.Collections.ObjectModel.Collection <PSObject> Invoke(string ScriptCode)
 {
     return(InvokeCommand.InvokeScript(ScriptCode));
 }
Пример #27
0
        private void ChangeDirectory(string fullPath)
        {
            var verb = Push ? "Push" : "Set";

            InvokeCommand.InvokeScript(string.Format("{1}-Location '{0}'", fullPath.Trim(), verb));
        }
        protected override void EndProcessing()
        {
            var vaultInfo = new Hashtable();

            // Validate mandatory parameters.
            var vaultItems = RegisteredVaultCache.GetAll();

            if (vaultItems.ContainsKey(Name))
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new InvalidOperationException("Provided Name for vault is already being used."),
                        "RegisterSecretVaultInvalidVaultName",
                        ErrorCategory.InvalidArgument,
                        this));
            }

            if (!ShouldProcess(Name, VerbsLifecycle.Register))
            {
                return;
            }

            // Resolve the module name path in calling context, if it is a path and not a name.
            var results = InvokeCommand.InvokeScript(
                script: "param([string] $path) (Resolve-Path -Path $path -EA Silent).Path",
                args: new object[] { ModuleName });
            string resolvedPath     = (results.Count == 1 && results[0] != null) ? (string)results[0].BaseObject : null;
            string moduleNameOrPath = resolvedPath ?? ModuleName;

            results = InvokeCommand.InvokeScript(
                script: "(Get-Module -Name Microsoft.PowerShell.SecretManagement).ModuleBase");
            string secretMgtModulePath = (results.Count == 1 && results[0] != null) ? (string)results[0].BaseObject : string.Empty;

            secretMgtModulePath = System.IO.Path.Combine(secretMgtModulePath, "Microsoft.PowerShell.SecretManagement.psd1");

            var moduleInfo = GetModuleInfo(
                modulePath: moduleNameOrPath,
                secretMgtModulePath: secretMgtModulePath,
                error: out ErrorRecord moduleLoadError);

            if (moduleInfo == null)
            {
                var msg = string.Format(CultureInfo.InvariantCulture,
                                        "Could not load and retrieve module information for module: {0} with error : {1}.",
                                        ModuleName, moduleLoadError?.ToString() ?? string.Empty);

                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(msg),
                        "RegisterSecretVaultCantGetModuleInfo",
                        ErrorCategory.InvalidOperation,
                        this));
            }

            if (!CheckForImplementingModule(
                    dirPath: moduleInfo.ModuleBase,
                    moduleName: moduleInfo.Name,
                    secretMgtModulePath: secretMgtModulePath,
                    error: out Exception error))
            {
                var invalidException = new PSInvalidOperationException(
                    message: "Could not find a SecretManagement extension implementing script module.",
                    innerException: error);

                ThrowTerminatingError(
                    new ErrorRecord(
                        invalidException,
                        "RegisterSecretVaultCantFindImplementingScriptModule",
                        ErrorCategory.ObjectNotFound,
                        this));
            }

            // Find base path of module without version folder, to store in vault registry.
            string dirPath;

            if (System.IO.Path.GetFileName(moduleInfo.ModuleBase).Equals(moduleInfo.Name, StringComparison.OrdinalIgnoreCase))
            {
                dirPath = moduleInfo.ModuleBase;
            }
            else
            {
                var parent = System.IO.Directory.GetParent(moduleInfo.ModuleBase);
                while (parent != null && !parent.Name.Equals(moduleInfo.Name, StringComparison.OrdinalIgnoreCase))
                {
                    parent = parent.Parent;
                }
                dirPath = parent?.FullName ?? moduleInfo.ModuleBase;
            }

            // Store module information.
            vaultInfo.Add(
                key: ExtensionVaultModule.ModulePathStr,
                value: dirPath);
            vaultInfo.Add(
                key: ExtensionVaultModule.ModuleNameStr,
                value: moduleInfo.Name);

            // Store optional vault parameters.
            vaultInfo.Add(
                key: ExtensionVaultModule.VaultParametersStr,
                value: VaultParameters);

            // Register new secret vault information.
            RegisteredVaultCache.Add(
                keyName: Name,
                vaultInfo: vaultInfo,
                defaultVault: DefaultVault);
        }
Пример #29
0
        public virtual void InvokeScript(string script)
        {
            var resultTypes = PipelineResultTypes.Error | PipelineResultTypes.Output;

            InvokeCommand.InvokeScript(script, false, resultTypes, null, null);
        }
Пример #30
0
        protected override void ProcessRecord()
        {
            while ((Data as PSObject)?.ImmediateBaseObject is PSObject)
            {
                Data = (Data as PSObject).ImmediateBaseObject;
            }
            SessionState.PSVariable.Set("ScPsSlvPipelineObject", Data);

            if (Property == null && SessionState.PSVariable.Get("ScPsSlvProperties") == null)
            {
                var hasCustomObjects = false;
                var propScript       =
                    InvokeCommand.NewScriptBlock(
                        "$ScPsSlvPipelineObject | Foreach-Object { $_.PSStandardMembers.DefaultDisplayProperty } | Select-Object -First 1");
                var propDefault = InvokeCommand.InvokeScript(SessionState, propScript).FirstOrDefault();
                if (propDefault == null)
                {
                    hasCustomObjects = true;
                    // May be PSCustomObject
                    propScript =
                        InvokeCommand.NewScriptBlock(
                            "$ScPsSlvPipelineObject | Foreach-Object { $_.PSObject.Properties.Name } | Select-Object -First 1");
                    propDefault = InvokeCommand.InvokeScript(SessionState, propScript).FirstOrDefault();
                }
                if (propDefault != null)
                {
                    propScript = InvokeCommand.NewScriptBlock(hasCustomObjects
                        ? "$ScPsSlvPipelineObject | Foreach-Object { $_.PSObject.Properties.Name }"
                        : "$ScPsSlvPipelineObject | Foreach-Object { $_.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames }");

                    var propResult = InvokeCommand.InvokeScript(SessionState, propScript);
                    var properties = new List <object>(propResult.Count + 1)
                    {
                        propDefault.ToString()
                    };
                    if (propResult.Any())
                    {
                        properties.AddRange(propResult.Where(p => p != null));
                    }
                    Property = properties.ToArray();
                    SessionState.PSVariable.Set("ScPsSlvProperties", Property);
                }
            }

            LogErrors(() =>
            {
                var formatProperty = SessionState.PSVariable.Get("ScPsSlvProperties")?.Value;
                var script         = (formatProperty is string)
                    ? "$ScPsSlvPipelineObject | Select-Object -Property " + formatProperty
                    : "$ScPsSlvPipelineObject | Select-Object -Property $ScPsSlvProperties";

                var scriptBlock = InvokeCommand.NewScriptBlock(script);
                var result      = InvokeCommand.InvokeScript(SessionState, scriptBlock);

                if (result.Any())
                {
                    var varValue = Data.BaseObject();
                    if (varValue is PSCustomObject)
                    {
                        varValue = Data;
                    }

                    var slvDataObject = new DataObject
                    {
                        Original = varValue,
                        Id       = CumulativeData.Count
                    };

                    foreach (var psPropertyInfo in result[0].Properties)
                    {
                        slvDataObject.Display.Add(psPropertyInfo.Name, (psPropertyInfo.Value ?? string.Empty).ToString());
                    }
                    CumulativeData.Add(slvDataObject);
                }
            });
            SessionState.PSVariable.Remove("ScPsSlvPipelineObject");
        }