Example PscxCmdlet with Path, LiteralPath and OutputPath parameters - NOTE you invoke this cmdlet with strings, as normal. The PscxPath attribute does the work of resolving, verifying and creating PscxPathInfo objects for you.

    [   // this cmdlet exports registry  keys
        Cmdlet(VerbsData.Export, "Registry", DefaultParameterSetName = "Path"),
    
        // all parameters that handles paths, i.e. decorated with [PscxPath], should only allow
        // paths from the registry provider unless otherwise specified
        ProviderConstraint(typeof(RegistryProvider))
    ] 
    public class ExportRegistryCommand : PscxCmdlet
    {
        // this parameter accepts a path and accepts wildcards, and must exist
        [PscxPath(ShouldExist = true)]
        [Parameter(ParameterSetName = "Path", Position = 0, Mandatory = true,
            ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)
        ]
        public PscxPathInfo[] Path
        {
            get; set;
        }

        // this parameter accepts paths and accepts literals (will not resolve wildcards)
        // and the path should also exist.
        [PscxPath(IsLiteral = true, ShouldExist = true)]
        [Alias("PSPath")]
        [Parameter(ParameterSetName = "LiteralPath", Position = 0, Mandatory = true,
            ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)
        ]
        public PscxPathInfo[] LiteralPath
        {
            get; set;
        }

        // this parameter accepts literal paths and they must lie on the filesystem
        // as this is where the registry export will be saved
        [PscxPath(typeof(FileSystemProvider), IsLiteral = true)]
        [Parameter(Mandatory = true, Position = 1)]
        public PscxPathInfo OutputPath
        {
            get; set;
        }

        protected override void EndProcessing()
        {
            PscxPathInfo[] pscxPaths = (this.ParameterSetName == "Path") ?
                this.Path : this.LiteralPath;

            // provider-internal path for filesystem
            string filePath = OutputPath.ProviderPath;
            
            using (StreamWriter writer = File.CreateText(filePath))
            {
                foreach (PscxPathInfo pscxPath in pscxPaths)
                {
                    // get fully qualified PSPath
                    string qualifiedPath = pscxPath.ToString();

                    // fetch it from the associated provider
                    var results = this.InvokeProvider.Item.Get(qualifiedPath);
                    foreach (var result in results)
                    {
                        // now write it in string format to the output file
                        writer.WriteLine(result.BaseObject.ToString());
                    }
                }
            }
        }
    }

Last edited Aug 10, 2008 at 6:52 PM by oisin, version 5

Comments

No comments yet.