示例#1
0
        /// <summary>
        /// Generate LogContext structure based on executionContext and invocationInfo passed in.
        ///
        /// LogContext structure is used in log provider interface.
        /// </summary>
        /// <param name="executionContext"></param>
        /// <param name="invocationInfo"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
        {
            if (executionContext == null)
            {
                return(null);
            }

            LogContext logContext = new LogContext();

            string shellId = executionContext.ShellID;

            logContext.ExecutionContext = executionContext;
            logContext.ShellId          = shellId;
            logContext.Severity         = severity.ToString();

            if (executionContext.EngineHostInterface != null)
            {
                logContext.HostName    = executionContext.EngineHostInterface.Name;
                logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString();
                logContext.HostId      = (string)executionContext.EngineHostInterface.InstanceId.ToString();
            }

            logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs());

            if (executionContext.CurrentRunspace != null)
            {
                logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
                logContext.RunspaceId    = executionContext.CurrentRunspace.InstanceId.ToString();

                Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (currentPipeline != null)
                {
                    logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
                }
            }

            logContext.SequenceNumber = NextSequenceNumber;

            try
            {
                if (executionContext.LogContextCache.User == null)
                {
                    logContext.User = Environment.UserDomainName + "\\" + Environment.UserName;
                    executionContext.LogContextCache.User = logContext.User;
                }
                else
                {
                    logContext.User = executionContext.LogContextCache.User;
                }
            }
            catch (InvalidOperationException)
            {
                logContext.User = Logging.UnknownUserName;
            }

            System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
            if (psSenderInfo != null)
            {
                logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
            }

            logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);

            if (invocationInfo == null)
            {
                return(logContext);
            }

            logContext.ScriptName  = invocationInfo.ScriptName;
            logContext.CommandLine = invocationInfo.Line;

            if (invocationInfo.MyCommand != null)
            {
                logContext.CommandName = invocationInfo.MyCommand.Name;
                logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString();

                switch (invocationInfo.MyCommand.CommandType)
                {
                case CommandTypes.Application:
                    logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path;
                    break;

                case CommandTypes.ExternalScript:
                    logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path;
                    break;
                }
            }

            return(logContext);
        }
        /// <summary>
        /// Starts the transcription.
        /// </summary>
        protected override void BeginProcessing()
        {
            // If they haven't specified a path, figure out the correct output path.
            if (!_isFilenameSet)
            {
                // read the filename from $TRANSCRIPT
                object value = this.GetVariableValue("global:TRANSCRIPT", null);

                // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt)
                if (value == null)
                {
                    // If they've specified an output directory, use it. Otherwise, use "My Documents"
                    if (OutputDirectory != null)
                    {
                        _outFilename   = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false);
                        _isLiteralPath = true;
                    }
                    else
                    {
                        _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath();
                    }
                }
                else
                {
                    _outFilename = (string)value;
                }
            }

            // Normalize outFilename here in case it is a relative path
            try
            {
                string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath);

                if (!ShouldProcess(effectiveFilePath))
                {
                    return;
                }

                if (System.IO.File.Exists(effectiveFilePath))
                {
                    if (NoClobber && !Append)
                    {
                        string message = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber,
                                                           effectiveFilePath,
                                                           "NoClobber"); // prevents localization
                        Exception   uae         = new UnauthorizedAccessException(message);
                        ErrorRecord errorRecord = new ErrorRecord(
                            uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath);

                        // NOTE: this call will throw
                        ThrowTerminatingError(errorRecord);
                    }

                    System.IO.FileInfo fInfo = new System.IO.FileInfo(effectiveFilePath);
                    if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        // Save some disk write time by checking whether file is readonly..
                        if (Force)
                        {
                            // Make sure the file is not read only
                            // Note that we will not clear the ReadOnly flag later
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                        else
                        {
                            string errorMessage = string.Format(
                                System.Globalization.CultureInfo.CurrentCulture,
                                TranscriptStrings.TranscriptFileReadOnly,
                                effectiveFilePath);
                            Exception innerException = new ArgumentException(errorMessage);
                            ThrowTerminatingError(new ErrorRecord(innerException, "FileReadOnly", ErrorCategory.InvalidArgument, effectiveFilePath));
                        }
                    }

                    // If they didn't specify -Append, empty the file
                    if (!_shouldAppend)
                    {
                        System.IO.File.WriteAllText(effectiveFilePath, string.Empty);
                    }
                }

                System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                    this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
                Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), UseMinimalHeader.IsPresent);

                // ch.StartTranscribing(effectiveFilePath, Append);

                // NTRAID#Windows Out Of Band Releases-931008-2006/03/21
                // Previous behavior was to write this even if ShouldProcess
                // returned false.  Why would we want that?
                PSObject outputObject = new PSObject(
                    StringUtil.Format(TranscriptStrings.TranscriptionStarted, Path));
                outputObject.Properties.Add(new PSNoteProperty("Path", Path));
                WriteObject(outputObject);
            }
            catch (Exception e)
            {
                try
                {
                    Host.UI.StopTranscribing();
                }
                catch
                {
                }

                string errorMessage = string.Format(
                    System.Globalization.CultureInfo.CurrentCulture,
                    TranscriptStrings.CannotStartTranscription,
                    e.Message);
                ErrorRecord er = new ErrorRecord(
                    PSTraceSource.NewInvalidOperationException(e, errorMessage),
                    "CannotStartTranscription", ErrorCategory.InvalidOperation, null);
                ThrowTerminatingError(er);
            }
        }