示例#1
0
 private static string _GetAsTyped_usingIckyPrivateReflection(PSObject pso)
 {
     return((string)s_tokenTextField.GetValue(pso));
 } // end _GetAsTyped_usingIckyPrivateReflection()
示例#2
0
        private void PopulateFromSerializedInfo(PSObject serializedScriptExtent)
        {
            string file = RemotingDecoder.GetPropertyValue<string>(serializedScriptExtent, "ScriptExtent_File");
            int startLineNumber = RemotingDecoder.GetPropertyValue<int>(serializedScriptExtent, "ScriptExtent_StartLineNumber");
            int startColumnNumber = RemotingDecoder.GetPropertyValue<int>(serializedScriptExtent, "ScriptExtent_StartColumnNumber");
            int endLineNumber = RemotingDecoder.GetPropertyValue<int>(serializedScriptExtent, "ScriptExtent_EndLineNumber");
            int endColumnNumber = RemotingDecoder.GetPropertyValue<int>(serializedScriptExtent, "ScriptExtent_EndColumnNumber");

            ScriptPosition startPosition = new ScriptPosition(file, startLineNumber, startColumnNumber, null);
            ScriptPosition endPosition = new ScriptPosition(file, endLineNumber, endColumnNumber, null);

            _startPosition = startPosition;
            _endPosition = endPosition;
        }
示例#3
0
        } // SetProperty

        /// <summary>
        /// Gives the provider a chance to attach additional parameters to
        /// the set-itemproperty cmdlet.
        /// </summary>
        /// 
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item to get the dynamic parameters for.
        /// </param>
        /// 
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value 
        /// of the properties to be set.
        /// </param>
        /// 
        /// <param name="cmdletProviderContext">
        /// The context under which this method is being called.
        /// </param>
        /// 
        /// <returns>
        /// An object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class.
        /// </returns>
        /// 
        internal object SetPropertyDynamicParameters(
            string path,
            PSObject propertyValue,
            CmdletProviderContext cmdletProviderContext)
        {
            Context = cmdletProviderContext;

            IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;

            if (propertyProvider == null)
            {
                return null;
            }
            return propertyProvider.SetPropertyDynamicParameters(path, propertyValue);
        } // SetPropertyDynamicParameters
        /// <summary>
        /// Adds the OutputTypes properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="outputTypes">output types</param>
        private static void AddOutputTypesProperties(PSObject obj, ReadOnlyCollection<PSTypeName> outputTypes)
        {
            PSObject returnValuesObj = new PSObject();

            returnValuesObj.TypeNames.Clear();
            returnValuesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            PSObject returnValueObj = new PSObject();

            returnValueObj.TypeNames.Clear();
            returnValueObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValue", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            PSObject typeObj = new PSObject();

            typeObj.TypeNames.Clear();
            typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            if (outputTypes.Count == 0)
            {
                typeObj.Properties.Add(new PSNoteProperty("name", "System.Object"));
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                foreach (PSTypeName outputType in outputTypes)
                {
                    sb.AppendLine(outputType.Name);
                }

                typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
            }

            returnValueObj.Properties.Add(new PSNoteProperty("type", typeObj));
            returnValuesObj.Properties.Add(new PSNoteProperty("returnValue", returnValueObj));
            obj.Properties.Add(new PSNoteProperty("returnValues", returnValuesObj));
        }
        private static void UpdateWSManConnectionInfo(
            WSManConnectionInfo wsmanConnectionInfo,
            PSObject rsInfoObject)
        {
            PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"];
            PSPropertyInfo pspBufferMode = rsInfoObject.Properties["BufferMode"];
            PSPropertyInfo pspResourceUri = rsInfoObject.Properties["ResourceUri"];
            PSPropertyInfo pspLocale = rsInfoObject.Properties["Locale"];
            PSPropertyInfo pspDataLocale = rsInfoObject.Properties["DataLocale"];
            PSPropertyInfo pspCompressionMode = rsInfoObject.Properties["CompressionMode"];
            PSPropertyInfo pspEncoding = rsInfoObject.Properties["Encoding"];
            PSPropertyInfo pspProfile = rsInfoObject.Properties["ProfileLoaded"];
            PSPropertyInfo pspMaxIdleTimeout = rsInfoObject.Properties["MaxIdleTimeout"];

            if (pspIdleTimeOut != null)
            {
                int idleTimeout;
                if (GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout))
                {
                    wsmanConnectionInfo.IdleTimeout = idleTimeout;
                }
            }
            if (pspBufferMode != null)
            {
                string bufferingMode = pspBufferMode.Value as string;
                if (bufferingMode != null)
                {
                    OutputBufferingMode outputBufferingMode;
                    if (Enum.TryParse<OutputBufferingMode>(bufferingMode, out outputBufferingMode))
                    {
                        // Update connection info.
                        wsmanConnectionInfo.OutputBufferingMode = outputBufferingMode;
                    }
                }
            }
            if (pspResourceUri != null)
            {
                string strShellUri = pspResourceUri.Value as string;
                if (strShellUri != null)
                {
                    wsmanConnectionInfo.ShellUri = strShellUri;
                }
            }
            if (pspLocale != null)
            {
                string localString = pspLocale.Value as string;
                if (localString != null)
                {
                    try
                    {
                        wsmanConnectionInfo.UICulture = new CultureInfo(localString);
                    }
                    catch (ArgumentException)
                    { }
                }
            }
            if (pspDataLocale != null)
            {
                string dataLocalString = pspDataLocale.Value as string;
                if (dataLocalString != null)
                {
                    try
                    {
                        wsmanConnectionInfo.Culture = new CultureInfo(dataLocalString);
                    }
                    catch (ArgumentException)
                    { }
                }
            }
            if (pspCompressionMode != null)
            {
                string compressionModeString = pspCompressionMode.Value as string;
                if (compressionModeString != null)
                {
                    wsmanConnectionInfo.UseCompression = compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase)
                        ? false : true;
                }
            }
            if (pspEncoding != null)
            {
                string encodingString = pspEncoding.Value as string;
                if (encodingString != null)
                {
                    wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase)
                        ? true : false;
                }
            }
            if (pspProfile != null)
            {
                string machineProfileLoadedString = pspProfile.Value as string;
                if (machineProfileLoadedString != null)
                {
                    wsmanConnectionInfo.NoMachineProfile = machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase)
                        ? false : true;
                }
            }
            if (pspMaxIdleTimeout != null)
            {
                int maxIdleTimeout;
                if (GetTimeIntValue(pspMaxIdleTimeout.Value as string, out maxIdleTimeout))
                {
                    wsmanConnectionInfo.MaxIdleTimeout = maxIdleTimeout;
                }
            }
        }
        /// <summary>
        /// Add the syntax parameters properties (these parameters are used to create the syntax section)
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="parameters">
        /// a collection of parameters in display order 
        /// ie., Positional followed by
        ///      Named Mandatory (in alpha numeric) followed by
        ///      Named (in alpha numeric)
        /// </param>
        /// <param name="common">common parameters</param>
        /// <param name="commonWorkflow">common workflow</param>
        /// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param>
        private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable<CommandParameterInfo> parameters,
            bool common, bool commonWorkflow, string parameterSetName)
        {
            ArrayList mshObjects = new ArrayList();

            foreach (CommandParameterInfo parameter in parameters)
            {
                if (commonWorkflow && IsCommonWorkflowParameter(parameter.Name))
                {
                    continue;
                }

                if (common && Cmdlet.CommonParameters.Contains(parameter.Name))
                {
                    continue;
                }

                PSObject mshObject = new PSObject();

                mshObject.TypeNames.Clear();
                mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

                Collection<Attribute> attributes = new Collection<Attribute>(parameter.Attributes);

                AddParameterProperties(mshObject, parameter.Name, new Collection<string>(parameter.Aliases),
                    parameter.IsDynamic, parameter.ParameterType, attributes, parameterSetName);

                Collection<ValidateSetAttribute> validateSet = GetValidateSetAttribute(attributes);
                List<string> names = new List<string>();

                foreach (ValidateSetAttribute set in validateSet)
                {
                    foreach (string value in set.ValidValues)
                    {
                        names.Add(value);
                    }
                }

                if (names.Count != 0)
                {
                    AddParameterValueGroupProperties(mshObject, names.ToArray());
                }
                else
                {
                    if (parameter.ParameterType.GetTypeInfo().IsEnum && (Enum.GetNames(parameter.ParameterType) != null))
                    {
                        AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType));
                    }
                    else if (parameter.ParameterType.IsArray)
                    {
                        if (parameter.ParameterType.GetElementType().GetTypeInfo().IsEnum &&
                            Enum.GetNames(parameter.ParameterType.GetElementType()) != null)
                        {
                            AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType.GetElementType()));
                        }
                    }
                    else if (parameter.ParameterType.GetTypeInfo().IsGenericType)
                    {
                        Type[] types = parameter.ParameterType.GetGenericArguments();

                        if (types.Length != 0)
                        {
                            Type type = types[0];

                            if (type.GetTypeInfo().IsEnum && (Enum.GetNames(type) != null))
                            {
                                AddParameterValueGroupProperties(mshObject, Enum.GetNames(type));
                            }
                            else if (type.IsArray)
                            {
                                if (type.GetElementType().GetTypeInfo().IsEnum &&
                                    Enum.GetNames(type.GetElementType()) != null)
                                {
                                    AddParameterValueGroupProperties(mshObject, Enum.GetNames(type.GetElementType()));
                                }
                            }
                        }
                    }
                }

                mshObjects.Add(mshObject);
            }

            obj.Properties.Add(new PSNoteProperty("parameter", mshObjects.ToArray()));
        }
        /// <summary>
        /// Generates a HelpInfo PSObject from a CmdletInfo object
        /// </summary>
        /// <param name="input">command info</param>
        /// <returns>HelpInfo PSObject</returns>
        internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input)
        {
            // Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
            // sets based on Dynamic Parameters (+ optional arguments)
            CommandInfo commandInfo = input.CreateGetCommandCopy(null);

            PSObject obj = new PSObject();

            obj.TypeNames.Clear();
            obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
            obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
            obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp);
            obj.TypeNames.Add("CmdletHelpInfo");
            obj.TypeNames.Add("HelpInfo");

            if (commandInfo is CmdletInfo)
            {
                CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
                bool common = false;
                bool commonWorkflow = false;
                if (cmdletInfo.Parameters != null)
                {
                    common = HasCommonParameters(cmdletInfo.Parameters);
                    commonWorkflow = ((cmdletInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);
                }

                obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
                obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
                AddDetailsProperties(obj, cmdletInfo.Name, cmdletInfo.Noun, cmdletInfo.Verb, TypeNameForDefaultHelp);
                AddSyntaxProperties(obj, cmdletInfo.Name, cmdletInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
                AddParametersProperties(obj, cmdletInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
                AddInputTypesProperties(obj, cmdletInfo.Parameters);
                AddRelatedLinksProperties(obj, commandInfo.CommandMetadata.HelpUri);

                try
                {
                    AddOutputTypesProperties(obj, cmdletInfo.OutputType);
                }
                catch (PSInvalidOperationException)
                {
                    AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
                }

                AddAliasesProperties(obj, cmdletInfo.Name, cmdletInfo.Context);

                if (HasHelpInfoUri(cmdletInfo.Module, cmdletInfo.ModuleName))
                {
                    AddRemarksProperties(obj, cmdletInfo.Name, cmdletInfo.CommandMetadata.HelpUri);
                }
                else
                {
                    obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
                }

                obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn));
            }
            else if (commandInfo is FunctionInfo)
            {
                FunctionInfo funcInfo = commandInfo as FunctionInfo;
                bool common = HasCommonParameters(funcInfo.Parameters);
                bool commonWorkflow = ((commandInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);

                obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
                obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
                AddDetailsProperties(obj, funcInfo.Name, String.Empty, String.Empty, TypeNameForDefaultHelp);
                AddSyntaxProperties(obj, funcInfo.Name, funcInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
                AddParametersProperties(obj, funcInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
                AddInputTypesProperties(obj, funcInfo.Parameters);
                AddRelatedLinksProperties(obj, funcInfo.CommandMetadata.HelpUri);

                try
                {
                    AddOutputTypesProperties(obj, funcInfo.OutputType);
                }
                catch (PSInvalidOperationException)
                {
                    AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
                }

                AddAliasesProperties(obj, funcInfo.Name, funcInfo.Context);

                if (HasHelpInfoUri(funcInfo.Module, funcInfo.ModuleName))
                {
                    AddRemarksProperties(obj, funcInfo.Name, funcInfo.CommandMetadata.HelpUri);
                }
                else
                {
                    obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
                }
            }

            obj.Properties.Add(new PSNoteProperty("alertSet", null));
            obj.Properties.Add(new PSNoteProperty("description", null));
            obj.Properties.Add(new PSNoteProperty("examples", null));
            obj.Properties.Add(new PSNoteProperty("Synopsis", commandInfo.Syntax));
            obj.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName));
            obj.Properties.Add(new PSNoteProperty("nonTerminatingErrors", String.Empty));
            obj.Properties.Add(new PSNoteProperty("xmlns:command", "http://schemas.microsoft.com/maml/dev/command/2004/10"));
            obj.Properties.Add(new PSNoteProperty("xmlns:dev", "http://schemas.microsoft.com/maml/dev/2004/10"));
            obj.Properties.Add(new PSNoteProperty("xmlns:maml", "http://schemas.microsoft.com/maml/2004/10"));

            return obj;
        }
示例#8
0
 bool IsContextType(PSObject source)
 {
     return(source.HasProperty("Account") && source.HasProperty("Tenant"));
 }
示例#9
0
 public override bool CanConvertTo(PSObject sourceValue, Type destinationType)
 {
     return(false);
 }
示例#10
0
 public override object ConvertTo(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
 {
     return(null);
 }
示例#11
0
 bool IsContainerType(PSObject source)
 {
     return(source.HasProperty("Context"));
 }
示例#12
0
        // Database defined types.
        internal void AddColumnsAndItem(PSObject liveObject, TableView tableView, TableControlBody tableBody)
        {
            _headerInfo = tableView.GenerateHeaderInfo(liveObject, tableBody, _parentCmdlet);

            AddColumnsAndItemEnd(liveObject);
        }
示例#13
0
 internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject)
 {
     Item          = obj;
     AppliesTo     = a;
     CurrentObject = currentObject;
 }
        /// <summary> Create the object </summary>
        protected override void ProcessRecord()
        {
            bool quietReply = false;

            try
            {
                IPHostEntry ipHostEntry = Dns.GetHostEntryAsync(ComputerName).Result;

                //If we got this far, somethings going good
                try
                {
                    for (int i = 0; i < Count; i++)
                    {
                        Ping      sender = new Ping();
                        PingReply reply  = sender.SendPingAsync(ComputerName, (timeout * 1000), new byte[] { 0xff }, new PingOptions(TTL, true)).Result;

                        //If things are good then set our bool to true, otherwise leave it false or whatever it currently is
                        if (reply.Status == IPStatus.Success)
                        {
                            quietReply = true;
                        }

                        //We want to be chatty
                        if (!this.quiet)
                        {
                            //We are going to wrap our custom class into a PSObject and format it
                            var outObj = new PingStatus(reply.Status, this.ComputerName, reply.Address, reply.RoundtripTime, TTL);
                            var pso    = new PSObject(outObj);
                            //Make sure to set the object Type so that it matches with our formatters
                            pso.TypeNames.Insert(0, "Microsoft.PowerShell.Commands.PingStatus");

                            //Write our object.
                            WriteObject(pso, true);
                        }

                        Thread.Sleep(new TimeSpan(0, 0, Delay));
                    }
                    //If we are passing -quiet we only want the one final pass/fail, so here it is
                    if (this.quiet)
                    {
                        WriteObject(quietReply);
                    }
                }
                catch (PingException pex)
                {
                    WriteError(new ErrorRecord(pex, pex.InnerException.ToString(), ErrorCategory.NotSpecified, pex.Source));
                }
                catch (NullReferenceException nrefex)
                {
                    WriteError(new ErrorRecord(nrefex, nrefex.Message, ErrorCategory.ObjectNotFound, nrefex.Source));
                }
                catch (Exception ex)
                {
                    WriteError(new ErrorRecord(ex, ex.InnerException.ToString(), ErrorCategory.NotSpecified, ex.Source));
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, ex.InnerException.ToString(), ErrorCategory.NotSpecified, ex.Source));
            }
        }
示例#15
0
 /// <summary>
 /// Helper to transcribe an error through formatting and output.
 /// </summary>
 /// <param name="context">The Execution Context</param>
 /// <param name="invocation">The invocation info associated with the record</param>
 /// <param name="errorWrap">The error record</param>
 internal void TranscribeError(ExecutionContext context, InvocationInfo invocation, PSObject errorWrap)
 {
     context.InternalHost.UI.TranscribeCommandComplete(invocation);
     InitialSessionState minimalState = InitialSessionState.CreateDefault2();
     Collection<PSObject> results = PowerShell.Create(minimalState).AddCommand("Out-String").Invoke(
         new List<PSObject>() { errorWrap });
     TranscribeResult(results[0].ToString());
 }
        private static void FormatDeployedStatefulServiceReplica(DeployedServiceReplica deployedServiceReplica, PSObject deployedServiceReplicaDetailPSObj)
        {
            var deployedServiceReplicaPSObj = new PSObject(deployedServiceReplica);

            deployedServiceReplicaPSObj.Members.Add(
                new PSCodeMethod(
                    Constants.ToStringMethodName,
                    typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

            deployedServiceReplicaDetailPSObj.Properties.Add(
                new PSNoteProperty(
                    Constants.DeployedServiceReplica,
                    deployedServiceReplicaPSObj));
        }
        /// <summary>
        /// Adds the syntax properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="cmdletName">command name</param>
        /// <param name="parameterSets">parameter sets</param>
        /// <param name="common">common parameters</param>
        /// <param name="commonWorkflow">common workflow parameters</param>
        /// <param name="typeNameForHelp">type name for help</param>
        internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp)
        {
            PSObject mshObject = new PSObject();

            mshObject.TypeNames.Clear();
            mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp));

            AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, commonWorkflow, typeNameForHelp);

            obj.Properties.Add(new PSNoteProperty("Syntax", mshObject));
        }
        private static void FormatReconfigurationInformation(System.Fabric.ReconfigurationInformation reconfigurationInformation, PSObject result)
        {
            var reconfigurationInformationObj = new PSObject(reconfigurationInformation);

            reconfigurationInformationObj.Members.Add(
                new PSCodeMethod(
                    Constants.ToStringMethodName,
                    typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));
            result.Properties.Add(
                new PSNoteProperty(
                    Constants.ReconfigurationInformation,
                    reconfigurationInformationObj));
        }
        /// <summary>
        /// Add the parameters properties (these parameters are used to create the parameters section)
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="parameters">parameters</param>
        /// <param name="common">common parameters</param>
        /// <param name="commonWorkflow">common workflow parameters</param>
        /// <param name="typeNameForHelp">type name for help</param>
        internal static void AddParametersProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters, bool common, bool commonWorkflow, string typeNameForHelp)
        {
            PSObject paramsObject = new PSObject();

            paramsObject.TypeNames.Clear();
            paramsObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameters", typeNameForHelp));

            ArrayList paramObjects = new ArrayList();

            ArrayList sortedParameters = new ArrayList();

            if (parameters != null)
            {
                foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
                {
                    sortedParameters.Add(parameter.Key);
                }
            }

            sortedParameters.Sort(StringComparer.Ordinal);

            foreach (string parameter in sortedParameters)
            {
                if (commonWorkflow && IsCommonWorkflowParameter(parameter))
                {
                    continue;
                }

                if (common && Cmdlet.CommonParameters.Contains(parameter))
                {
                    continue;
                }

                PSObject paramObject = new PSObject();

                paramObject.TypeNames.Clear();
                paramObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

                AddParameterProperties(paramObject, parameter, parameters[parameter].Aliases,
                    parameters[parameter].IsDynamic, parameters[parameter].ParameterType, parameters[parameter].Attributes);

                paramObjects.Add(paramObject);
            }

            paramsObject.Properties.Add(new PSNoteProperty("parameter", paramObjects.ToArray()));
            obj.Properties.Add(new PSNoteProperty("parameters", paramsObject));
        }
        protected override object FormatOutput(object output)
        {
            if (output is DeployedServiceReplicaDetail)
            {
                var item = output as DeployedServiceReplicaDetail;

                var itemPSObj = new PSObject(item);

                var reportedLoadObject = new PSObject(item.ReportedLoad);
                reportedLoadObject.Members.Add(
                    new PSCodeMethod(
                        Constants.ToStringMethodName,
                        typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                itemPSObj.Properties.Add(
                    new PSNoteProperty(
                        Constants.ReportedLoadPropertyName,
                        reportedLoadObject));

                if (item is DeployedStatefulServiceReplicaDetail)
                {
                    var inner = item as DeployedStatefulServiceReplicaDetail;

                    if (inner.ReplicatorStatus != null)
                    {
                        var replicatorStatus = inner.ReplicatorStatus;

                        if (replicatorStatus is PrimaryReplicatorStatus)
                        {
                            var innerReplicatorStatus = replicatorStatus as PrimaryReplicatorStatus;

                            if (!this.ReplicatorDetail)
                            {
                                var basicInfo = new PSObject(innerReplicatorStatus.ReplicationQueueStatus);
                                basicInfo.Members.Add(
                                    new PSCodeMethod(
                                        Constants.ToStringMethodName,
                                        typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                                itemPSObj.Properties.Add(
                                    new PSNoteProperty(
                                        Constants.ReplicatorStatusPropertyName,
                                        basicInfo));
                            }
                            else
                            {
                                var detailInfo = new PSObject(innerReplicatorStatus);
                                detailInfo.Members.Add(
                                    new PSCodeMethod(
                                        Constants.ToStringMethodName,
                                        typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                                itemPSObj.Properties.Add(
                                    new PSNoteProperty(
                                        Constants.ReplicatorStatusPropertyName,
                                        detailInfo));
                            }
                        }
                        else if (replicatorStatus is SecondaryReplicatorStatus)
                        {
                            var innerReplicatorStatus = replicatorStatus as SecondaryReplicatorStatus;

                            if (!this.ReplicatorDetail)
                            {
                                var basicInfo = new PSObject(innerReplicatorStatus.ReplicationQueueStatus);
                                basicInfo.Members.Add(
                                    new PSCodeMethod(
                                        Constants.ToStringMethodName,
                                        typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                                itemPSObj.Properties.Add(
                                    new PSNoteProperty(
                                        Constants.ReplicatorStatusPropertyName,
                                        basicInfo));
                            }
                            else
                            {
                                var detailInfo = new PSObject(innerReplicatorStatus);
                                detailInfo.Members.Add(
                                    new PSCodeMethod(
                                        Constants.ToStringMethodName,
                                        typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                                itemPSObj.Properties.Add(
                                    new PSNoteProperty(
                                        Constants.ReplicatorStatusPropertyName,
                                        detailInfo));
                            }
                        }
                        else
                        {
                            // Unknown format. Neglect result and return
                            return(itemPSObj);
                        }
                    } // ReplicatorStatus

                    if (inner.ReplicaStatus != null)
                    {
                        var kvsStatus = inner.ReplicaStatus as KeyValueStoreReplicaStatus;
                        if (kvsStatus != null)
                        {
                            var kvsStatusObject = new PSObject(kvsStatus);
                            kvsStatusObject.Members.Add(
                                new PSCodeMethod(
                                    Constants.ToStringMethodName,
                                    typeof(OutputFormatter).GetMethod(Constants.FormatObjectMethodName)));

                            itemPSObj.Properties.Add(
                                new PSNoteProperty(
                                    Constants.ReplicaStatus,
                                    kvsStatusObject));
                        }
                    } // ReplicaStatus

                    var deployedStatefulServiceReplicaDetail = item as DeployedStatefulServiceReplicaDetail;

                    if (deployedStatefulServiceReplicaDetail.DeployedServiceReplica != null)
                    {
                        FormatDeployedStatefulServiceReplica(deployedStatefulServiceReplicaDetail.DeployedServiceReplica, itemPSObj);

                        var deployedStatefulServiceReplica = deployedStatefulServiceReplicaDetail.DeployedServiceReplica as DeployedStatefulServiceReplica;
                        FormatReconfigurationInformation(deployedStatefulServiceReplica.ReconfigurationInformation, itemPSObj);
                    }
                }
                else
                {
                    var deployedStatelessServiceInstanceDetail = item as DeployedStatelessServiceInstanceDetail;
                    if (deployedStatelessServiceInstanceDetail.DeployedServiceReplicaInstance != null)
                    {
                        FormatDeployedStatelessServiceInstance(deployedStatelessServiceInstanceDetail.DeployedServiceReplicaInstance, itemPSObj);
                    }
                }

                return(itemPSObj);
            }
            else
            {
                return(base.FormatOutput(output));
            }
        }
        /// <summary>
        /// Adds the parameterValue properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="parameterType">the type of a parameter</param>
        /// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param>
        private static void AddParameterValueProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
        {
            PSObject mshObject;

            if (parameterType != null)
            {
                Type type = Nullable.GetUnderlyingType(parameterType) ?? parameterType;
                var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
                mshObject = new PSObject(parameterTypeString);
                mshObject.Properties.Add(new PSNoteProperty("variableLength", parameterType.IsArray));
            }
            else
            {
                mshObject = new PSObject("System.Object");
                mshObject.Properties.Add(new PSNoteProperty("variableLength",
                    StringUtil.Format(HelpDisplayStrings.FalseShort)));
            }

            mshObject.Properties.Add(new PSNoteProperty("required", "true"));

            obj.Properties.Add(new PSNoteProperty("parameterValue", mshObject));
        }
示例#22
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            _compressionThreads = new List <NtfsCompressionThread>();

            foreach (var path in Path)
            {
                var fsi = System.IO.Path.HasExtension(path) ? (FileSystemInfo) new FileInfo(path) : new DirectoryInfo(path);

                if (!fsi.Exists)
                {
                    WriteError((fsi is FileInfo ? (Exception) new FileNotFoundException("The file was not found.", fsi.FullName) : new DirectoryNotFoundException($"The directory \"{fsi.FullName}\" was not found.")).ToErrorRecord());
                    continue;
                }

                if ((fsi.Attributes & FileAttributes.Compressed) != 0 && Options.EnableCompression && !Options.ForceRecompress)
                {
                    WriteWarning($"The file system object \"{fsi.FullName}\" already has NTFS compression enabled, and the ForceRecompress property on the NtfsCompressionOptions object was false.");
                    continue;
                }

                var ntfsCompress = new NtfsCompress(fsi, Options);

                if (Path.Length == 1)
                {
                    ntfsCompress.OutputDataReceived += NtfsCompressOnOutputDataReceived;
                }

                if (RedirectStandardError)
                {
                    ntfsCompress.ErrorDataReceived += NtfsCompressOnErrorDataReceived;
                }

                _compressionThreads.Add(new NtfsCompressionThread(ntfsCompress, ntfsCompress.BeginCompress(Timeout, TerminateOnTimeout, null, null)));
            }

            ThreadPool.QueueUserWorkItem(ProgressThreadProc);

            try
            {
                while (_compressionThreads.Any())
                {
                    int index, i;
                    for (index = 0, i = 0; i < _compressionThreads.Count; i++)
                    {
                        if (_compressionThreads[i].AsyncResult.IsCompleted || _compressionThreads[i].AsyncResult.CompletedSynchronously)
                        {
                            index = i;
                            break;
                        }

                        if (index < _compressionThreads.Count - 1)
                        {
                            continue;
                        }

                        Thread.Sleep(250);
                        i = -1;
                    }

                    var thread = _compressionThreads[index];

                    try
                    {
                        var result = thread.NtfsCompress.EndCompress(false, thread.AsyncResult);
                        WriteObject(PSObject.AsPSObject(
                                        new
                        {
                            Path = thread.NtfsCompress.FileSystemInfo.FullName,
                            result.PreCompressionSize,
                            result.PostCompressionSize
                        }));
                    }
                    catch (Exception e)
                    {
                        WriteError(new ErrorRecord(e, null, ErrorCategory.NotSpecified, null));
                    }
                    finally
                    {
                        _compressionThreads.RemoveAt(index);
                    }
                }
            }
            finally
            {
                if (_compressionThreads.Any())
                {
                    foreach (var compressionThread in _compressionThreads)
                    {
                        try
                        {
                            compressionThread.NtfsCompress.EndCompress(false, compressionThread.AsyncResult);
                        }
                        catch (Exception e) when(e is OperationCanceledException)
                        {
                            WriteWarning(e.Message);
                        }
                    }
                }
            }

            void ProgressThreadProc(object state)
            {
                var timer = Stopwatch.StartNew();

                while (_compressionThreads.Any())
                {
                    lock (SyncObject)
                        Host.UI.WriteProgress(0, new ProgressRecord(0,
                                                                    $"{(Path.Length == 1 ? (!RedirectStandardOutput && string.IsNullOrEmpty(_compactOutput) ? "Waiting for data from compact.exe output stream..." : RedirectStandardOutput ? "Running compact.exe (output redirected)..." : _compactOutput) : $"{(Options.EnableCompression ? "Compressing" : "Uncompressing")} file system objects...")}",
                                                                    $"Paths to compress: {Path.Length}   Processes: {_compressionThreads.Count}   Time Elapsed: {timer.Elapsed:g}"));

                    Thread.Sleep(500);
                }

                timer.Stop();
            }
        }
 /// <summary>
 /// Adds the remarks properties
 /// </summary>
 /// <param name="obj">HelpInfo object</param>
 /// <param name="cmdletName"></param>
 /// <param name="helpUri"></param>
 private static void AddRemarksProperties(PSObject obj, string cmdletName, string helpUri)
 {
     if (String.IsNullOrEmpty(helpUri))
     {
         obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContentWithoutHelpUri, cmdletName)));
     }
     else
     {
         obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContent, cmdletName, helpUri)));
     }
 }
示例#24
0
 internal virtual void Add(PSObject groupValue)
 {
     this.group.Add(groupValue);
     this.count++;
 }
示例#25
0
 /// <summary>
 /// TracePowerShellObject
 /// </summary>
 public bool TracePowerShellObject(PSObject powerShellObject)
 {
     return this.DebugChannel.TraceDebug(PowerShellTraceEvent.PowerShellObject,
                                         PowerShellTraceOperationCode.Method, PowerShellTraceTask.None);
 }
        /// <summary>
        /// Creates a DBA Instance parameter from any object
        /// </summary>
        /// <param name="Input">Object to parse</param>
        public DbaInstanceParameter(object Input)
        {
            InputObject = Input;
            PSObject tempInput = new PSObject(Input);
            string   typeName  = "";

            try { typeName = tempInput.TypeNames[0].ToLower(); }
            catch
            {
                throw new PSArgumentException("Failed to interpret input as Instance: " + Input);
            }

            typeName = typeName.Replace("Deserialized.", "");

            switch (typeName)
            {
            case "microsoft.sqlserver.management.smo.server":
                try
                {
                    if (tempInput.Properties["ServerType"] != null && (string)tempInput.Properties["ServerType"].Value.ToString() == "SqlAzureDatabase")
                    {
                        _ComputerName = (new DbaInstanceParameter((string)tempInput.Properties["Name"].Value)).ComputerName;
                    }
                    else
                    {
                        if (tempInput.Properties["NetName"] != null)
                        {
                            _ComputerName = (string)tempInput.Properties["NetName"].Value;
                        }
                        else
                        {
                            _ComputerName = (new DbaInstanceParameter((string)tempInput.Properties["DomainInstanceName"].Value)).ComputerName;
                        }
                    }
                    _InstanceName = (string)tempInput.Properties["InstanceName"].Value;
                    PSObject tempObject = new PSObject(tempInput.Properties["ConnectionContext"].Value);

                    string tempConnectionString = (string)tempObject.Properties["ConnectionString"].Value;
                    tempConnectionString = tempConnectionString.Split(';')[0].Split('=')[1].Trim().Replace(" ", "");

                    if (Regex.IsMatch(tempConnectionString, @",\d{1,5}$") && (tempConnectionString.Split(',').Length == 2))
                    {
                        try { Int32.TryParse(tempConnectionString.Split(',')[1], out _Port); }
                        catch (Exception e)
                        {
                            throw new PSArgumentException("Failed to parse port number on connection string: " + tempConnectionString, e);
                        }
                        if (_Port > 65535)
                        {
                            throw new PSArgumentException("Failed to parse port number on connection string: " + tempConnectionString);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new PSArgumentException("Failed to interpret input as Instance: " + Input + " : " + e.Message, e);
                }
                break;

            case "microsoft.sqlserver.management.smo.linkedserver":
                try
                {
                    _ComputerName = (string)tempInput.Properties["Name"].Value;
                }
                catch (Exception e)
                {
                    throw new PSArgumentException("Failed to interpret input as Instance: " + Input, e);
                }
                break;

            case "microsoft.activedirectory.management.adcomputer":
                try
                {
                    _ComputerName = (string)tempInput.Properties["Name"].Value;

                    // We prefer using the dnshostname whenever possible
                    if (tempInput.Properties["DNSHostName"].Value != null)
                    {
                        if (!String.IsNullOrEmpty((string)tempInput.Properties["DNSHostName"].Value))
                        {
                            _ComputerName = (string)tempInput.Properties["DNSHostName"].Value;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new PSArgumentException("Failed to interpret input as Instance: " + Input, e);
                }
                break;

            case "microsoft.sqlserver.management.registeredservers.registeredserver":
                try
                {
                    //Pass the ServerName property of the SMO object to the string constrtuctor,
                    //so we don't have to re-invent the wheel on instance name / port parsing
                    DbaInstanceParameter parm =
                        new DbaInstanceParameter((string)tempInput.Properties["ServerName"].Value);
                    _ComputerName = parm.ComputerName;

                    if (parm.InstanceName != "MSSQLSERVER")
                    {
                        _InstanceName = parm.InstanceName;
                    }

                    if (parm.Port != 1433)
                    {
                        _Port = parm.Port;
                    }
                }
                catch (Exception e)
                {
                    throw new PSArgumentException("Failed to interpret input as Instance: " + Input, e);
                }
                break;

            default:
                throw new PSArgumentException("Failed to interpret input as Instance: " + Input);
            }
        }
示例#27
0
        } // WriteObject

        /// <summary>
        /// Wraps the item in a PSObject and attaches some notes to the
        /// object that deal with path information.
        /// </summary>
        ///
        /// <param name="item">
        /// The item to be wrapped.
        /// </param>
        ///
        /// <param name="path">
        /// The path to the item.
        /// </param>
        ///
        /// <returns>
        /// A PSObject that wraps the item and has path information attached
        /// as notes.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="item"/> is null.
        /// </exception>
        /// 
        private PSObject WrapOutputInPSObject(
            object item,
            string path)
        {
            if (item == null)
            {
                throw PSTraceSource.NewArgumentNullException("item");
            }
            PSObject result = new PSObject(item);

            Diagnostics.Assert(
                ProviderInfo != null,
                "The ProviderInfo should always be set");

            // Move the TypeNames to the wrapping object if the wrapped object
            // was an PSObject

            PSObject mshObj = item as PSObject;
            if (mshObj != null)
            {
                result.InternalTypeNames = new ConsolidatedString(mshObj.InternalTypeNames);
            }

            // Construct a provider qualified path as the Path note

            String providerQualifiedPath =
                LocationGlobber.GetProviderQualifiedPath(path, ProviderInfo);

            result.AddOrSetProperty("PSPath", providerQualifiedPath);
            providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSPath", providerQualifiedPath);

            // Now get the parent path and child name

            NavigationCmdletProvider navProvider = this as NavigationCmdletProvider;
            if (navProvider != null && path != null)
            {
                // Get the parent path

                string parentPath = null;

                if (PSDriveInfo != null)
                {
                    parentPath = navProvider.GetParentPath(path, PSDriveInfo.Root, Context);
                }
                else
                {
                    parentPath = navProvider.GetParentPath(path, String.Empty, Context);
                }

                string providerQualifiedParentPath = String.Empty;

                if (!String.IsNullOrEmpty(parentPath))
                {
                    providerQualifiedParentPath =
                        LocationGlobber.GetProviderQualifiedPath(parentPath, ProviderInfo);
                }
                result.AddOrSetProperty("PSParentPath", providerQualifiedParentPath);
                providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSParentPath", providerQualifiedParentPath);

                // Get the child name

                string childName = navProvider.GetChildName(path, Context);


                result.AddOrSetProperty("PSChildName", childName);
                providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName);
            }

            // PSDriveInfo

            if (PSDriveInfo != null)
            {
                result.AddOrSetProperty(this.PSDriveInfo.GetNotePropertyForProviderCmdlets("PSDrive"));
                providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSDrive", this.PSDriveInfo);
            }

            // ProviderInfo

            result.AddOrSetProperty(this.ProviderInfo.GetNotePropertyForProviderCmdlets("PSProvider"));
            providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSProvider", this.ProviderInfo);

            return result;
        } // WrapOutputInPSObject
示例#28
0
        /// <summary>
        /// This method implements the ProcessRecord method for get-member command.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (this.InputObject == null || this.InputObject == AutomationNull.Value)
            {
                return;
            }

            Type baseObjectAsType = null;

            string  typeName;
            Adapter staticAdapter = null;

            if (this.Static == true)
            {
                staticAdapter = PSObject.DotNetStaticAdapter;
                object baseObject = this.InputObject.BaseObject;
                baseObjectAsType = baseObject as System.Type ?? baseObject.GetType();
                typeName         = baseObjectAsType.FullName;
            }
            else
            {
                var typeNames = this.InputObject.InternalTypeNames;
                if (typeNames.Count != 0)
                {
                    typeName = typeNames[0];
                }
                else
                {
                    // This is never used for display.  It is used only as a key to typesAlreadyDisplayed
                    typeName = "<null>";
                }
            }

            if (_typesAlreadyDisplayed.Contains(typeName))
            {
                return;
            }
            else
            {
                _typesAlreadyDisplayed.Add(typeName, string.Empty);
            }

            PSMemberTypes     memberTypeToSearch = MemberType;
            PSMemberViewTypes viewToSearch       = View;

            if (((View & PSMemberViewTypes.Extended) == 0) &&
                (!typeof(PSMemberSet).ToString().Equals(typeName, StringComparison.OrdinalIgnoreCase)))
            {
                // PSMemberSet is an internal memberset and its properties/methods are populated differently.
                // PSMemberSet instance is created to represent PSExtended, PSAdapted, PSBase, PSObject hidden
                // properties. We should honor extended properties for such case.

                // request is to search dotnet or adapted or both members.
                // dotnet,adapted members cannot be Script*,Note*,Code*
                memberTypeToSearch ^= (PSMemberTypes.AliasProperty | PSMemberTypes.CodeMethod | PSMemberTypes.CodeProperty
                                       | PSMemberTypes.MemberSet | PSMemberTypes.NoteProperty | PSMemberTypes.PropertySet | PSMemberTypes.ScriptMethod
                                       | PSMemberTypes.ScriptProperty);
            }

            if (((View & PSMemberViewTypes.Adapted) == 0) && (View & PSMemberViewTypes.Base) == 0)
            {
                // base and adapted are not mentioned in the view so ignore respective properties
                memberTypeToSearch ^= (PSMemberTypes.Property | PSMemberTypes.ParameterizedProperty | PSMemberTypes.Method);
            }

            if (((View & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) &&
                (InputObject.InternalBaseDotNetAdapter == null))
            {
                // the input object don't have a custom adapter..
                // for this case adapted view and base view are the same.
                viewToSearch |= PSMemberViewTypes.Adapted;
            }

            PSMemberInfoCollection <PSMemberInfo> membersToSearch;

            if (this.Static == true)
            {
                membersToSearch = staticAdapter.BaseGetMembers <PSMemberInfo>(baseObjectAsType);
            }
            else
            {
                Collection <CollectionEntry <PSMemberInfo> > memberCollection = PSObject.GetMemberCollection(viewToSearch);
                membersToSearch = new PSMemberInfoIntegratingCollection <PSMemberInfo>(this.InputObject, memberCollection);
            }

            foreach (string nameElement in this.Name)
            {
                ReadOnlyPSMemberInfoCollection <PSMemberInfo> readOnlyMembers;
                readOnlyMembers = membersToSearch.Match(nameElement, memberTypeToSearch, _matchOptions);

                MemberDefinition[] members = new MemberDefinition[readOnlyMembers.Count];
                int resultCount            = 0;
                foreach (PSMemberInfo member in readOnlyMembers)
                {
                    if (!Force)
                    {
                        PSMethod memberAsPSMethod = member as PSMethod;
                        if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial))
                        {
                            continue;
                        }
                    }

                    members[resultCount] = new MemberDefinition(typeName, member.Name, member.MemberType, member.ToString());
                    resultCount++;
                }

                Array.Sort <MemberDefinition>(members, 0, resultCount, new MemberComparer());
                for (int index = 0; index < resultCount; index++)
                {
                    this.WriteObject(members[index]);
                }
            }
        }
示例#29
0
        } // AddPropertyValueAt
        
        /// <summary>
        /// Gives the provider a chance to attach additional parameters to
        /// the add-propertyvalue -at cmdlet.
        /// </summary>
        /// 
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item to get the dynamic parameters for.
        /// </param>
        /// 
        /// <param name="at">
        /// The position to place the new value of the property.
        /// </param>
        ///
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value 
        /// of the properties to be added.
        /// </param>
        /// 
        /// <param name="cmdletProviderContext">
        /// The context under which this method is being called.
        /// </param>
        /// 
        /// <returns>
        /// An object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class.
        /// </returns>
        /// 
        internal object AddPropertyValueAtDynamicParameters(
            string path, 
            object at,
            PSObject propertyValue,
            CmdletProviderContext cmdletProviderContext)
        {
            Context = cmdletProviderContext;

            IMultivaluePropertyCmdletProvider propertyProvider = this as IMultivaluePropertyCmdletProvider;

            if (propertyProvider == null)
            {
                return null;
            }
            return propertyProvider.AddPropertyValueAtDynamicParameters(path, at, propertyValue);
        } // AddPropertyValueAtDynamicParameters
示例#30
0
        /// <summary>
        /// Return an alternate representation of the specified object that serializes the same JSON, except
        /// that properties that cannot be evaluated are treated as having the value null.
        ///
        /// Primitive types are returned verbatim.  Aggregate types are processed recursively.
        /// </summary>
        /// <param name="obj">The object to be processed</param>
        /// <param name="depth">The current depth into the object graph</param>
        /// <returns>An object suitable for serializing to JSON</returns>
        private object ProcessValue(object obj, int depth)
        {
            if (Stopping)
            {
                throw new StoppingException();
            }

            PSObject pso = obj as PSObject;

            if (pso != null)
            {
                obj = pso.BaseObject;
            }

            Object rv          = obj;
            bool   isPurePSObj = false;
            bool   isCustomObj = false;

            if (obj == null ||
                DBNull.Value.Equals(obj) ||
                obj is string ||
                obj is char ||
                obj is bool ||
                obj is DateTime ||
                obj is DateTimeOffset ||
                obj is Guid ||
                obj is Uri ||
                obj is double ||
                obj is float ||
                obj is decimal)
            {
                rv = obj;
            }
            else if (obj is Newtonsoft.Json.Linq.JObject jObject)
            {
                rv = jObject.ToObject <Dictionary <object, object> >();
            }
            else
            {
                TypeInfo t = obj.GetType().GetTypeInfo();


                if (t.IsPrimitive)
                {
                    rv = obj;
                }
                else if (t.IsEnum)
                {
                    // Win8:378368 Enums based on System.Int64 or System.UInt64 are not JSON-serializable
                    // because JavaScript does not support the necessary precision.
                    Type enumUnderlyingType = Enum.GetUnderlyingType(obj.GetType());
                    if (enumUnderlyingType.Equals(typeof(Int64)) || enumUnderlyingType.Equals(typeof(UInt64)))
                    {
                        rv = obj.ToString();
                    }
                    else
                    {
                        rv = obj;
                    }
                }
                else
                {
                    if (depth > Depth)
                    {
                        if (pso != null && (bool)_immediateBaseObjectIsEmptyField.GetValue(pso))
                        {
                            // The obj is a pure PSObject, we convert the original PSObject to a string,
                            // instead of its base object in this case
                            rv = LanguagePrimitives.ConvertTo(pso, typeof(string),
                                                              CultureInfo.InvariantCulture);
                            isPurePSObj = true;
                        }
                        else
                        {
                            rv = LanguagePrimitives.ConvertTo(obj, typeof(String),
                                                              CultureInfo.InvariantCulture);
                        }
                    }
                    else
                    {
                        IDictionary dict = obj as IDictionary;
                        if (dict != null)
                        {
                            rv = ProcessDictionary(dict, depth);
                        }
                        else
                        {
                            IEnumerable enumerable = obj as IEnumerable;
                            if (enumerable != null)
                            {
                                rv = ProcessEnumerable(enumerable, depth);
                            }
                            else
                            {
                                rv          = ProcessCustomObject <JsonIgnoreAttribute>(obj, depth);
                                isCustomObj = true;
                            }
                        }
                    }
                }
            }

            rv = AddPsProperties(pso, rv, depth, isPurePSObj, isCustomObj);

            return(rv);
        }
示例#31
0
        /// <summary>
        /// Decode parameters.
        /// </summary>
        private static object[] DecodeParameters(PSObject parametersPSObject, Type[] parameterTypes)
        {
            // Extract the ArrayList and decode the parameters.
            ArrayList parameters = (ArrayList)parametersPSObject.BaseObject;
            List<object> decodedParameters = new List<object>();
            Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length");
            for (int i = 0; i < parameters.Count; ++i)
            {
                object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]);
                decodedParameters.Add(parameter);
            }

            return decodedParameters.ToArray();
        }
        /// <summary>
        /// Takes out the content from the database and writes them
        /// out
        /// </summary>
        protected override void ProcessRecord()
        {
            bool writeOldWay = PowerShellVersion == null ||
                               PowerShellVersion.Major < 5 ||
                               PowerShellVersion.Build < 11086;

            TypeInfoDataBase db = this.Context.FormatDBManager.Database;

            List <ViewDefinition> viewdefinitions            = db.viewDefinitionsSection.viewDefinitionList;
            Dictionary <string, List <string> > typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList);

            var typedefs = new Dictionary <ConsolidatedString, List <FormatViewDefinition> >(ConsolidatedString.EqualityComparer);

            foreach (ViewDefinition definition in viewdefinitions)
            {
                if (definition.isHelpFormatter)
                {
                    continue;
                }

                var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap);

                if (!ShouldGenerateView(consolidatedTypeName))
                {
                    continue;
                }

                PSControl control;

                var tableControlBody = definition.mainControl as TableControlBody;
                if (tableControlBody != null)
                {
                    control = new TableControl(tableControlBody, definition);
                }
                else
                {
                    var listControlBody = definition.mainControl as ListControlBody;
                    if (listControlBody != null)
                    {
                        control = new ListControl(listControlBody, definition);
                    }
                    else
                    {
                        var wideControlBody = definition.mainControl as WideControlBody;
                        if (wideControlBody != null)
                        {
                            control = new WideControl(wideControlBody, definition);
                            if (writeOldWay)
                            {
                                // Alignment was added to WideControl in V2, but wasn't
                                // used.  It was removed in V5, but old PowerShell clients
                                // expect this property or fail to rehydrate the remote object.
                                var psobj = new PSObject(control);
                                psobj.Properties.Add(new PSNoteProperty("Alignment", 0));
                            }
                        }
                        else
                        {
                            var complexControlBody = (ComplexControlBody)definition.mainControl;
                            control = new CustomControl(complexControlBody, definition);
                        }
                    }
                }

                // Older version of PowerShell do not know about something in the control, so
                // don't return it.
                if (writeOldWay && !control.CompatibleWithOldPowerShell())
                {
                    continue;
                }

                var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId);

                List <FormatViewDefinition> viewList;
                if (!typedefs.TryGetValue(consolidatedTypeName, out viewList))
                {
                    viewList = new List <FormatViewDefinition>();
                    typedefs.Add(consolidatedTypeName, viewList);
                }
                viewList.Add(formatdef);
            }// foreach(ViewDefinition...

            // write out all the available type definitions
            foreach (var pair in typedefs)
            {
                var typeNames = pair.Key;

                if (writeOldWay)
                {
                    foreach (var typeName in typeNames)
                    {
                        var etd = new ExtendedTypeDefinition(typeName, pair.Value);
                        WriteObject(etd);
                    }
                }
                else
                {
                    var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value);
                    for (int i = 1; i < typeNames.Count; i++)
                    {
                        etd.TypeNames.Add(typeNames[i]);
                    }
                    WriteObject(etd);
                }
            }
        }
        /// <summary>
        /// Adds the details properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="name">command name</param>
        /// <param name="noun">command noun</param>
        /// <param name="verb">command verb</param>
        /// <param name="typeNameForHelp">type name for help</param>
        /// <param name="synopsis">synopsis</param>
        internal static void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp,
            string synopsis = null)
        {
            PSObject mshObject = new PSObject();

            mshObject.TypeNames.Clear();
            mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp));

            mshObject.Properties.Add(new PSNoteProperty("name", name));
            mshObject.Properties.Add(new PSNoteProperty("noun", noun));
            mshObject.Properties.Add(new PSNoteProperty("verb", verb));

            // add synopsis
            if (!string.IsNullOrEmpty(synopsis))
            {
                PSObject descriptionObject = new PSObject();
                descriptionObject.TypeNames.Clear();
                descriptionObject.TypeNames.Add("MamlParaTextItem");
                descriptionObject.Properties.Add(new PSNoteProperty("Text", synopsis));
                mshObject.Properties.Add(new PSNoteProperty("Description", descriptionObject));
            }

            obj.Properties.Add(new PSNoteProperty("details", mshObject));
        }
        } // end SetDefaultFormatInfoForObject()

        /// <summary>
        ///    Given a PSObject, choose a ViewDefinitionInfo for it. Optionally specify
        ///    the desired view definition type. The ViewDefinitionInfo may come from the
        ///    list of registered views, or from a special property on the object, or be
        ///    auto-supplied for ISupportColor objects.
        ///
        ///    If an IFormatInfo cannot be found, returns null.
        /// </summary>
        /// <param name="formatInfoType">
        ///    Optional: if null, will return the first view definition it finds,
        ///    excluding AltSingleLineViewDefinitions.
        /// </param>
        public static IFormatInfo ChooseFormatInfoForPSObject(PSObject outputObject,
                                                              Type formatInfoType)
        {
            if (null == outputObject)
            {
                throw new ArgumentNullException("outputObject");
            }

            IFormatInfo fi = null;

            //
            // First check the hidden property for an object-specific view.
            //

            PSPropertyInfo pspi = outputObject.Properties[DefaultViewDefPropName];

            if ((null != pspi) && (null != pspi.Value))
            {
                if (!(pspi.Value is IFormatInfo))
                {
                    Util.Fail("Expected hidden property to be an IFormatInfo.");
                }
                else
                {
                    fi = (IFormatInfo)pspi.Value;
                }
            }

            //
            // But wait... does it match the requested view type?
            //
            // If there is a requested type (formatInfoType is not null), but it matches
            // the object-specific default view... should we use the object specific
            // default view?
            //
            // I think it could go either way, but I'm going to choose to go with the
            // object-specific default view, because say somebody does:
            //
            //    $stuff = Invoke-SomeCommand
            //    $stuff
            //    $stuff | ft
            //
            // Where "$stuff" has object-specific default views attached, and they are
            // table views. The user would probably expect to get the same output for
            // second and third commands.
            //

            if ((null != fi) &&
                ((null == formatInfoType) ||
                 (formatInfoType.IsAssignableFrom(fi.GetType()))))
            {
                return(fi);
            }

            //
            // Okay, now check for views registered for all instances of the object's
            // type.
            //

            var viewInfo = ChooseFormatInfoForPSObjectFromRegistered(outputObject,
                                                                     formatInfoType);

            if (null != viewInfo)
            {
                return(viewInfo.ViewDefinition);
            }
            else if (((null == formatInfoType) || (typeof(AltCustomViewDefinition) == formatInfoType)) &&
                     (outputObject.BaseObject is ISupportColor))
            {
                // For objects that implement ISupportColor but don't have a registered
                // view, we'll supply a view for them.
                return(sm_customIdentityView);
            }

            return(null);
        }
        /// <summary>
        /// Add the syntax item properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="cmdletName">cmdlet name, you can't get this from parameterSets</param>
        /// <param name="parameterSets">a collection of parameter sets</param>
        /// <param name="common">common parameters</param>
        /// <param name="commonWorkflow">common workflow parameters</param>
        /// <param name="typeNameForHelp">type name for help</param>
        private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp)
        {
            ArrayList mshObjects = new ArrayList();

            foreach (CommandParameterSetInfo parameterSet in parameterSets)
            {
                PSObject mshObject = new PSObject();

                mshObject.TypeNames.Clear();
                mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp));

                mshObject.Properties.Add(new PSNoteProperty("name", cmdletName));
                mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common));
                mshObject.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));

                Collection<CommandParameterInfo> parameters = new Collection<CommandParameterInfo>();
                // GenerateParameters parameters in display order 
                // ie., Positional followed by
                //      Named Mandatory (in alpha numeric) followed by
                //      Named (in alpha numeric)
                parameterSet.GenerateParametersInDisplayOrder(commonWorkflow,
                                                  parameters.Add,
                                                  delegate { });

                AddSyntaxParametersProperties(mshObject, parameters, common, commonWorkflow, parameterSet.Name);

                mshObjects.Add(mshObject);
            }

            obj.Properties.Add(new PSNoteProperty("syntaxItem", mshObjects.ToArray()));
        }
        // N.B.: Does not enumerat an object-specific view (if there is one attached to
        // the object).
        public static IEnumerable <AltTypeFormatEntryPair> EnumerateAllFormatInfoForPSObject(PSObject outputObject,
                                                                                             Type formatInfoType)
        {
            if (null == outputObject)
            {
                throw new ArgumentNullException("outputObject");
            }

            return(_Singleton.EnumerateAllFormatInfoForTypeNames(outputObject.TypeNames, formatInfoType));
        }
        /// <summary>
        /// Adds a parameter value group (for enums)
        /// </summary>
        /// <param name="obj">object</param>
        /// <param name="values">parameter group values</param>
        private static void AddParameterValueGroupProperties(PSObject obj, string[] values)
        {
            PSObject paramValueGroup = new PSObject();

            paramValueGroup.TypeNames.Clear();
            paramValueGroup.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            ArrayList paramValue = new ArrayList(values);

            paramValueGroup.Properties.Add(new PSNoteProperty("parameterValue", paramValue.ToArray()));
            obj.Properties.Add(new PSNoteProperty("parameterValueGroup", paramValueGroup));
        }
示例#38
0
 public static string GetItemSpec(PSObject obj)
 {
     return(((ITaskItem)obj.BaseObject).ItemSpec);
 }
        /// <summary>
        /// Adds the parameter properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="name">parameter name</param>
        /// <param name="aliases">parameter aliases</param>
        /// <param name="dynamic">is dynamic parameter?</param>
        /// <param name="type">parameter type</param>
        /// <param name="attributes">parameter attributes</param>
        /// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param>
        private static void AddParameterProperties(PSObject obj, string name, Collection<string> aliases, bool dynamic,
            Type type, Collection<Attribute> attributes, string parameterSetName = null)
        {
            Collection<ParameterAttribute> attribs = GetParameterAttribute(attributes);

            obj.Properties.Add(new PSNoteProperty("name", name));

            if (attribs.Count == 0)
            {
                obj.Properties.Add(new PSNoteProperty("required", ""));
                obj.Properties.Add(new PSNoteProperty("pipelineInput", ""));
                obj.Properties.Add(new PSNoteProperty("isDynamic", ""));
                obj.Properties.Add(new PSNoteProperty("parameterSetName", ""));
                obj.Properties.Add(new PSNoteProperty("description", ""));
                obj.Properties.Add(new PSNoteProperty("position", ""));
                obj.Properties.Add(new PSNoteProperty("aliases", ""));
            }
            else
            {
                ParameterAttribute paramAttribute = attribs[0];
                if (!string.IsNullOrEmpty(parameterSetName))
                {
                    foreach (var attrib in attribs)
                    {
                        if (string.Equals(attrib.ParameterSetName, parameterSetName, StringComparison.OrdinalIgnoreCase))
                        {
                            paramAttribute = attrib;
                            break;
                        }
                    }
                }

                obj.Properties.Add(new PSNoteProperty("required", CultureInfo.CurrentCulture.TextInfo.ToLower(paramAttribute.Mandatory.ToString())));
                obj.Properties.Add(new PSNoteProperty("pipelineInput", GetPipelineInputString(paramAttribute)));
                obj.Properties.Add(new PSNoteProperty("isDynamic", CultureInfo.CurrentCulture.TextInfo.ToLower(dynamic.ToString())));

                if (paramAttribute.ParameterSetName.Equals(ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase))
                {
                    obj.Properties.Add(new PSNoteProperty("parameterSetName", StringUtil.Format(HelpDisplayStrings.AllParameterSetsName)));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < attribs.Count; i++)
                    {
                        sb.Append(attribs[i].ParameterSetName);

                        if (i != (attribs.Count - 1))
                        {
                            sb.Append(", ");
                        }
                    }

                    obj.Properties.Add(new PSNoteProperty("parameterSetName", sb.ToString()));
                }

                if (paramAttribute.HelpMessage != null)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine(paramAttribute.HelpMessage);

                    obj.Properties.Add(new PSNoteProperty("description", sb.ToString()));
                }

                // We do not show switch parameters in the syntax section
                // (i.e. [-Syntax] not [-Syntax <SwitchParameter>]
                if (type != typeof(SwitchParameter))
                {
                    AddParameterValueProperties(obj, type, attributes);
                }

                AddParameterTypeProperties(obj, type, attributes);

                if (paramAttribute.Position == int.MinValue)
                {
                    obj.Properties.Add(new PSNoteProperty("position",
                        StringUtil.Format(HelpDisplayStrings.NamedParameter)));
                }
                else
                {
                    obj.Properties.Add(new PSNoteProperty("position",
                        paramAttribute.Position.ToString(CultureInfo.InvariantCulture)));
                }

                if (aliases.Count == 0)
                {
                    obj.Properties.Add(new PSNoteProperty("aliases", StringUtil.Format(
                        HelpDisplayStrings.None)));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < aliases.Count; i++)
                    {
                        sb.Append(aliases[i]);

                        if (i != (aliases.Count - 1))
                        {
                            sb.Append(", ");
                        }
                    }

                    obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
                }
            }
        }
示例#40
0
 public static int GetMetadataCount(PSObject obj)
 {
     return(((ITaskItem)obj.BaseObject).MetadataCount);
 }
        /// <summary>
        /// Adds the parameterType properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="parameterType">the type of a parameter</param>
        /// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param>
        private static void AddParameterTypeProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
        {
            PSObject mshObject = new PSObject();

            mshObject.TypeNames.Clear();
            mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
            mshObject.Properties.Add(new PSNoteProperty("name", parameterTypeString));

            obj.Properties.Add(new PSNoteProperty("type", mshObject));
        }
示例#42
0
 public static ICollection GetMetadataNames(PSObject obj)
 {
     return(((ITaskItem)obj.BaseObject).MetadataNames);
 }
        /// <summary>
        /// Adds the InputTypes properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="parameters">command parameters</param>
        internal static void AddInputTypesProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters)
        {
            Collection<string> inputs = new Collection<string>();

            if (parameters != null)
            {
                foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
                {
                    Collection<ParameterAttribute> attribs = GetParameterAttribute(parameter.Value.Attributes);

                    foreach (ParameterAttribute attrib in attribs)
                    {
                        if (attrib.ValueFromPipeline ||
                            attrib.ValueFromPipelineByPropertyName ||
                            attrib.ValueFromRemainingArguments)
                        {
                            if (!inputs.Contains(parameter.Value.ParameterType.FullName))
                            {
                                inputs.Add(parameter.Value.ParameterType.FullName);
                            }
                        }
                    }
                }
            }

            if (inputs.Count == 0)
            {
                inputs.Add(StringUtil.Format(HelpDisplayStrings.None));
            }

            StringBuilder sb = new StringBuilder();

            foreach (string input in inputs)
            {
                sb.AppendLine(input);
            }

            PSObject inputTypesObj = new PSObject();

            inputTypesObj.TypeNames.Clear();
            inputTypesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            PSObject inputTypeObj = new PSObject();

            inputTypeObj.TypeNames.Clear();
            inputTypeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputType", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            PSObject typeObj = new PSObject();

            typeObj.TypeNames.Clear();
            typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

            typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
            inputTypeObj.Properties.Add(new PSNoteProperty("type", typeObj));
            inputTypesObj.Properties.Add(new PSNoteProperty("inputType", inputTypeObj));
            obj.Properties.Add(new PSNoteProperty("inputTypes", inputTypesObj));
        }
示例#44
0
 /// <summary>
 /// Converts a <see cref="ResourcePropertyObject"/> to <see cref="JToken"/>
 /// </summary>
 /// <param name="propertyObject">The <see cref="ResourcePropertyObject"/></param>
 internal static JToken ToResourcePropertiesBody(this PSObject propertyObject)
 {
     return(PsObjectExtensions.ToJToken(propertyObject));
 }
        /// <summary>
        /// Adds the aliases properties
        /// </summary>
        /// <param name="obj">HelpInfo object</param>
        /// <param name="name">command name</param>
        /// <param name="context">execution context</param>
        private static void AddAliasesProperties(PSObject obj, string name, ExecutionContext context)
        {
            StringBuilder sb = new StringBuilder();

            bool found = false;

            if (context != null)
            {
                foreach (string alias in context.SessionState.Internal.GetAliasesByCommandName(name))
                {
                    found = true;
                    sb.AppendLine(alias);
                }
            }

            if (!found)
            {
                sb.AppendLine(StringUtil.Format(HelpDisplayStrings.None));
            }

            obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
        }
示例#46
0
        internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context)
        {
            PSNoteProperty pSNoteProperty;
            string         str;
            PSObject       pSObject = PSObject.AsPSObject(content);

            if (this.currentContentItem == null || this.currentContentItem.PathInfo != pathInfo && string.Compare(pathInfo.Path, this.currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase) != 0)
            {
                this.currentContentItem = new ContentCommandBase.ContentPathsCache(pathInfo);
                string path = pathInfo.Path;
                pSNoteProperty = new PSNoteProperty("PSPath", path);
                pSObject.Properties.Add(pSNoteProperty, true);
                object[] objArray = new object[2];
                objArray[0] = "PSPath";
                objArray[1] = path;
                CoreCommandBase.tracer.WriteLine("Attaching {0} = {1}", objArray);
                this.currentContentItem.PSPath = path;
                try
                {
                    if (pathInfo.Drive == null)
                    {
                        str = base.SessionState.Path.ParseParent(pathInfo.Path, string.Empty, context);
                    }
                    else
                    {
                        str = base.SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context);
                    }
                    pSNoteProperty = new PSNoteProperty("PSParentPath", str);
                    pSObject.Properties.Add(pSNoteProperty, true);
                    object[] objArray1 = new object[2];
                    objArray1[0] = "PSParentPath";
                    objArray1[1] = str;
                    CoreCommandBase.tracer.WriteLine("Attaching {0} = {1}", objArray1);
                    this.currentContentItem.ParentPath = str;
                    string str1 = base.SessionState.Path.ParseChildName(pathInfo.Path, context);
                    pSNoteProperty = new PSNoteProperty("PSChildName", str1);
                    pSObject.Properties.Add(pSNoteProperty, true);
                    object[] objArray2 = new object[2];
                    objArray2[0] = "PSChildName";
                    objArray2[1] = str1;
                    CoreCommandBase.tracer.WriteLine("Attaching {0} = {1}", objArray2);
                    this.currentContentItem.ChildName = str1;
                }
                catch (NotSupportedException notSupportedException)
                {
                }
                if (pathInfo.Drive != null)
                {
                    PSDriveInfo drive = pathInfo.Drive;
                    pSNoteProperty = new PSNoteProperty("PSDrive", drive);
                    pSObject.Properties.Add(pSNoteProperty, true);
                    object[] objArray3 = new object[2];
                    objArray3[0] = "PSDrive";
                    objArray3[1] = drive;
                    CoreCommandBase.tracer.WriteLine("Attaching {0} = {1}", objArray3);
                    this.currentContentItem.Drive = drive;
                }
                ProviderInfo provider = pathInfo.Provider;
                pSNoteProperty = new PSNoteProperty("PSProvider", provider);
                pSObject.Properties.Add(pSNoteProperty, true);
                object[] objArray4 = new object[2];
                objArray4[0] = "PSProvider";
                objArray4[1] = provider;
                CoreCommandBase.tracer.WriteLine("Attaching {0} = {1}", objArray4);
                this.currentContentItem.Provider = provider;
            }
            else
            {
                pSObject = this.currentContentItem.AttachNotes(pSObject);
            }
            pSNoteProperty = new PSNoteProperty("ReadCount", (object)readCount);
            pSObject.Properties.Add(pSNoteProperty, true);
            base.WriteObject(pSObject);
        }
        /// <summary>
        /// Adds the related links properties
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="relatedLink"></param>
        internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink)
        {
            if (!String.IsNullOrEmpty(relatedLink))
            {
                PSObject navigationLinkObj = new PSObject();

                navigationLinkObj.TypeNames.Clear();
                navigationLinkObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#navigationLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));

                navigationLinkObj.Properties.Add(new PSNoteProperty("uri", relatedLink));

                List<PSObject> navigationLinkValues = new List<PSObject> { navigationLinkObj };

                // check if obj already has relatedLinks property
                PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty;
                if ((relatedLinksPO != null) && (relatedLinksPO.Value != null))
                {
                    PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value);
                    PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty;
                    if ((navigationLinkPO != null) && (navigationLinkPO.Value != null))
                    {
                        PSObject navigationLinkValue = navigationLinkPO.Value as PSObject;
                        if (navigationLinkValue != null)
                        {
                            navigationLinkValues.Add(navigationLinkValue);
                        }
                        else
                        {
                            PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[];
                            if (navigationLinkValueArray != null)
                            {
                                foreach (var psObject in navigationLinkValueArray)
                                {
                                    navigationLinkValues.Add(psObject);
                                }
                            }
                        }
                    }
                }

                PSObject relatedLinksObj = new PSObject();

                relatedLinksObj.TypeNames.Clear();
                relatedLinksObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#relatedLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
                relatedLinksObj.Properties.Add(new PSNoteProperty("navigationLink", navigationLinkValues.ToArray()));

                obj.Properties.Add(new PSNoteProperty("relatedLinks", relatedLinksObj));
            }
        }
示例#48
0
 public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo());
        private static void ComputeDisconnectedOnExpiresOn(
            PSObject rsInfoObject,
            out DateTime? disconnectedOn,
            out DateTime? expiresOn)
        {
            PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"];
            PSPropertyInfo pspShellInactivity = rsInfoObject.Properties["ShellInactivity"];

            if (pspIdleTimeOut != null && pspShellInactivity != null)
            {
                string shellInactivityString = pspShellInactivity.Value as string;
                int idleTimeout;
                if ((shellInactivityString != null) &&
                    GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout))
                {
                    try
                    {
                        TimeSpan shellInactivityTime = Xml.XmlConvert.ToTimeSpan(shellInactivityString);
                        TimeSpan idleTimeoutTime = TimeSpan.FromSeconds(idleTimeout / 1000);

                        if (idleTimeoutTime > shellInactivityTime)
                        {
                            DateTime now = DateTime.Now;
                            disconnectedOn = now.Subtract(shellInactivityTime);
                            expiresOn = disconnectedOn.Value.Add(idleTimeoutTime);

                            return;
                        }
                    }
                    catch (FormatException)
                    { }
                    catch (ArgumentOutOfRangeException)
                    { }
                    catch (OverflowException)
                    { }
                }
            }

            disconnectedOn = null;
            expiresOn = null;
        }
示例#50
0
        internal void Import()
        {
            CreateFileStream();
            _deserializer = new Deserializer(_xr);
            // If total count has been requested, return a dummy object with zero confidence
            if (_cmdlet.PagingParameters.IncludeTotalCount)
            {
                PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0);
                _cmdlet.WriteObject(totalCount);
            }

            ulong skip  = _cmdlet.PagingParameters.Skip;
            ulong first = _cmdlet.PagingParameters.First;

            // if paging is not specified then keep the old V2 behavior
            if (skip == 0 && first == ulong.MaxValue)
            {
                while (!_deserializer.Done())
                {
                    object result = _deserializer.Deserialize();
                    _cmdlet.WriteObject(result);
                }
            }
            // else try to flatten the output if possible
            else
            {
                ulong skipped = 0;
                ulong count   = 0;
                while (!_deserializer.Done() && count < first)
                {
                    object   result   = _deserializer.Deserialize();
                    PSObject psObject = result as PSObject;

                    if (psObject != null)
                    {
                        ICollection c = psObject.BaseObject as ICollection;
                        if (c != null)
                        {
                            foreach (object o in c)
                            {
                                if (count >= first)
                                {
                                    break;
                                }

                                if (skipped++ >= skip)
                                {
                                    count++;
                                    _cmdlet.WriteObject(o);
                                }
                            }
                        }
                        else
                        {
                            if (skipped++ >= skip)
                            {
                                count++;
                                _cmdlet.WriteObject(result);
                            }
                        }
                    }
                    else if (skipped++ >= skip)
                    {
                        count++;
                        _cmdlet.WriteObject(result);
                        continue;
                    }
                }
            }
        }
示例#51
0
 internal void ToPSObjectForRemoting(PSObject dest)
 {
     RemotingEncoder.AddNoteProperty(dest, "ScriptExtent_File", () => File);
     RemotingEncoder.AddNoteProperty(dest, "ScriptExtent_StartLineNumber", () => StartLineNumber);
     RemotingEncoder.AddNoteProperty(dest, "ScriptExtent_StartColumnNumber", () => StartColumnNumber);
     RemotingEncoder.AddNoteProperty(dest, "ScriptExtent_EndLineNumber", () => EndLineNumber);
     RemotingEncoder.AddNoteProperty(dest, "ScriptExtent_EndColumnNumber", () => EndColumnNumber);
 }
示例#52
0
 public Package(PSObject obj, string feedId) :
     this(obj, feedId, new PowerShellWrapper(RunspaceMode.CurrentRunspace))
 {
 }
示例#53
0
 internal static ScriptExtent FromPSObjectForRemoting(PSObject serializedScriptExtent)
 {
     ScriptExtent extent = new ScriptExtent();
     extent.PopulateFromSerializedInfo(serializedScriptExtent);
     return extent;
 }
示例#54
0
        /// <summary>
        /// Serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            PSObject psObject = PSObject.AsPSObject(this);

            psObject.GetObjectData(info, context);
        }
示例#55
0
        } // GetPropertyDynamicParameters

        /// <summary>
        /// Internal wrapper for the SetProperty protected method. This method will
        /// only be called if the provider implements the IPropertyCmdletProvider interface.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item to set the properties on.
        /// </param>
        /// 
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value 
        /// of the properties to be set.
        /// </param>
        /// 
        /// <param name="cmdletProviderContext">
        /// The context under which this method is being called.
        /// </param>
        /// 
        internal void SetProperty(
            string path,
            PSObject propertyValue,
            CmdletProviderContext cmdletProviderContext)
        {
            Context = cmdletProviderContext;

            IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;

            if (propertyProvider == null)
            {
                throw
                    PSTraceSource.NewNotSupportedException(
                        SessionStateStrings.IPropertyCmdletProvider_NotSupported);
            }

            // Call interface method

            propertyProvider.SetProperty(path, propertyValue);
        } // SetProperty
示例#56
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="command"></param>
        /// <param name="sb"></param>
        /// <param name="filePath"></param>
        /// <param name="initSb"></param>
        /// <param name="argumentList"></param>
        /// <param name="inputObject"></param>
        /// <param name="psCmdlet"></param>
        public ThreadJob(
            string name,
            string command,
            ScriptBlock sb,
            string filePath,
            ScriptBlock initSb,
            object[] argumentList,
            PSObject inputObject,
            PSCmdlet psCmdlet)
            : base(command, name)
        {
            _sb           = sb;
            _filePath     = filePath;
            _initSb       = initSb;
            _argumentList = argumentList;
            _input        = new PSDataCollection <object>();
            if (inputObject != null)
            {
                _input.Add(inputObject);
            }
            _output = new PSDataCollection <PSObject>();

            this.PSJobTypeName = "ThreadJob";

            // Create host object for thread jobs.
            ThreadJobHost host = new ThreadJobHost();

            HookupHostDataDelegates(host);

            // Create Runspace/PowerShell object and state callback.
            // The job script/command will run in a separate thread associated with the Runspace.
            _rs = RunspaceFactory.CreateRunspace(host);
            _rs.Open();
            _ps          = PowerShell.Create();
            _ps.Runspace = _rs;
            _ps.InvocationStateChanged += (sender, psStateChanged) =>
            {
                // Update Job state.
                switch (psStateChanged.InvocationStateInfo.State)
                {
                case PSInvocationState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PSInvocationState.Stopped:
                    SetJobState(JobState.Stopped);
                    break;

                case PSInvocationState.Failed:
                    SetJobState(JobState.Failed);
                    break;

                case PSInvocationState.Completed:
                    if (_runningInitScript)
                    {
                        // Begin running main script.
                        _runningInitScript = false;
                        RunScript();
                    }
                    else
                    {
                        SetJobState(JobState.Completed);
                    }
                    break;
                }
            };

            // Hook up data streams.
            this.Output = _output;
            this.Output.EnumeratorNeverBlocks = true;

            this.Error = _ps.Streams.Error;
            this.Error.EnumeratorNeverBlocks = true;

            this.Progress = _ps.Streams.Progress;
            this.Progress.EnumeratorNeverBlocks = true;

            this.Verbose = _ps.Streams.Verbose;
            this.Verbose.EnumeratorNeverBlocks = true;

            this.Warning = _ps.Streams.Warning;
            this.Warning.EnumeratorNeverBlocks = true;

            this.Debug = _ps.Streams.Debug;
            this.Debug.EnumeratorNeverBlocks = true;

            // Add to job repository
            if (psCmdlet != null)
            {
                psCmdlet.JobRepository.Add(this);
            }
        }
示例#57
0
        } // RemovePropertyValueAtDynamicParameters
        
        /// <summary>
        /// Adds the specified properties of the item at the specified path at the specified
        /// position if the property is a multivalued property.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item to add the property to.
        /// </param>
        /// 
        /// <param name="position">
        /// The position to place the new value of the property.
        /// </param>
        ///
        /// <param name="propertyValue">
        /// A PSObject which contains a collection of the name, type, value 
        /// of the properties to be added.
        /// </param>
        /// 
        /// <param name="cmdletProviderContext">
        /// The context under which this method is being called.
        /// </param>
        /// 
        /// <returns>
        /// Nothing. An instance of PSObject representing the properties that were set
        /// should be passed to the WriteObject() method.
        /// </returns>
        /// 
        internal void AddPropertyValueAt(
            string path,
            object position,
            PSObject propertyValue,
            CmdletProviderContext cmdletProviderContext)
        {
            Context = cmdletProviderContext;

            IMultivaluePropertyCmdletProvider propertyProvider = 
                this as IMultivaluePropertyCmdletProvider;

            if (propertyProvider == null)
            {
                throw
                    providerBaseTracer.NewNotSupportedException(
                        "SessionStateStrings",
                        "IMultivaluePropertyCmdletProvider_NotSupported");
            }

            // Call interface method

            propertyProvider.AddPropertyValueAt(path, position, propertyValue);
        } // AddPropertyValueAt
示例#58
0
        /// <summary>
        /// Decode.
        /// </summary>
        internal static RemoteHostResponse Decode(PSObject data)
        {
            Dbg.Assert(data != null, "Expected data != null");

            // Extract all the fields from data.
            long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId);
            RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId);

            // Decode the return value and the exception.
            RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId);
            object returnValue = DecodeReturnValue(data, methodInfo.ReturnType);
            Exception exception = DecodeException(data);

            // Use these values to create a RemoteHostResponse and return it.
            return new RemoteHostResponse(callId, methodId, returnValue, exception);
        }
示例#59
0
 static AutomationNull()
 {
     Value = new PSObject();
 }
示例#60
0
        // Expand a list of (possibly wildcarded) expressions into resolved expressions that
        // match property names on the incoming objects.
        private static List <MshParameter> ExpandExpressions(List <PSObject> inputObjects, List <MshParameter> unexpandedParameterList)
        {
            List <MshParameter> expandedParameterList = new List <MshParameter>();

            if (unexpandedParameterList != null)
            {
                foreach (MshParameter unexpandedParameter in unexpandedParameterList)
                {
                    PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
                    if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings
                    {
                        expandedParameterList.Add(unexpandedParameter);
                    }
                    else
                    {
                        SortedDictionary <string, PSPropertyExpression> expandedPropertyNames = new SortedDictionary <string, PSPropertyExpression>(StringComparer.OrdinalIgnoreCase);
                        if (inputObjects != null)
                        {
                            foreach (object inputObject in inputObjects)
                            {
                                if (inputObject is null)
                                {
                                    continue;
                                }

                                foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject)))
                                {
                                    expandedPropertyNames[resolvedName.ToString()] = resolvedName;
                                }
                            }
                        }

                        foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values)
                        {
                            MshParameter expandedParameter = new MshParameter();
                            expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone();
                            expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression;

                            expandedParameterList.Add(expandedParameter);
                        }
                    }
                }
            }

            return(expandedParameterList);
        }