protected override void ProcessPath(PscxPathInfo pscxPath) { try { WriteVerbose("Processing " + pscxPath.ProviderPath); bool exists = FileSystem.AlternateDataStreamExists(pscxPath.ProviderPath, Name); WriteObject(exists); } catch (SecurityException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (UnauthorizedAccessException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (PipelineStoppedException) { throw; } catch (Exception ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.NotSpecified, pscxPath.ProviderPath)); } }
/// <summary> /// /// </summary> /// <param name="pscxPath"></param> /// <returns></returns> public static bool Exists(PscxPathInfo pscxPath) { string qualifiedPath = pscxPath.ToString(); bool isLiteral = pscxPath.IsUnresolved; return(Exists(qualifiedPath, isLiteral)); }
protected override void ProcessPath(PscxPathInfo pscxPath) { if (ShouldProcess(pscxPath.ProviderPath)) { _writer.ProcessPath(pscxPath); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { FileHandler.ProcessRead(pscxPath.ProviderPath, delegate(Stream stream) { Bitmap bmp = new Bitmap(stream); WriteObject(bmp); }); }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; FileHandler.ProcessRead(filePath, delegate(Stream stream) { ProcessPathImpl(filePath, stream); }); }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; if (ShouldProcess(filePath)) { ConvertLineEndingFromFile(filePath); } }
private static bool DeleteFileOrDirectory(PscxPathInfo pscxPath, FileSystemInfo fi) { if (fi is DirectoryInfo) { return NativeMethods.RemoveDirectory(pscxPath.ProviderPath); } return NativeMethods.DeleteFile(pscxPath.ProviderPath); }
protected override void ProcessPath(PscxPathInfo pscxPath) { var name = ReparsePointHelper.EnsurePathSlash(pscxPath.ProviderPath); if (!NativeMethods.DeleteVolumeMountPoint(name)) { ErrorHandler.WriteLastWin32Error("DeleteVolumeMountPointFailed", name); } base.ProcessPath(pscxPath); }
protected override void ProcessPath(PscxPathInfo pscxPath) { FileHandler.ProcessRead(pscxPath.ProviderPath, delegate(Stream stream) { using (var streamReader = new StreamReader(stream)) { string script = streamReader.ReadToEnd(); TestScript(script, pscxPath.ToPathInfo().Path); } }); }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; if (File.Exists(filePath)) { WriteObject(FileVersionInfo.GetVersionInfo(filePath)); } else if (!Directory.Exists(filePath)) { ErrorHandler.WriteFileNotFoundError(filePath); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; try { string shortPath = Utils.GetShortPathName(filePath); var shortPathInfo = new ShortPathInfo(filePath, shortPath); WriteObject(shortPathInfo); } catch (IOException exc) { ErrorHandler.HandleFileError(false, filePath, exc); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { var filePath = pscxPath.ProviderPath; if (ReparsePointHelper.IsReparsePoint(filePath)) { if (Raw) { WriteObject(ReparsePointHelper.GetReparsePointData(filePath)); } else { WriteObject(ReparsePointHelper.GetReparsePoint(filePath)); } } }
/// <summary> /// /// </summary> /// <param name="pscxPath"></param> /// <param name="pathType"></param> /// <returns></returns> public static bool Exists(PscxPathInfo pscxPath, ref PscxPathType pathType) { string qualifiedPath = pscxPath.ToString(); pathType = PscxPathType.Unknown; string pathArg = (pscxPath.IsUnresolved) ? "LiteralPath" : "Path"; if (Exists(pscxPath)) { bool isLeaf = PipelineHelper.ExecuteScalar <bool>( new Command("Test-Path"), new CommandArgument() { Name = pathArg, Value = qualifiedPath }, new CommandArgument() { Name = "PathType", Value = "Leaf" }); if (isLeaf) { pathType = PscxPathType.Leaf; } else { bool isContainer = PipelineHelper.ExecuteScalar <bool>( new Command("Test-Path"), new CommandArgument() { Name = pathArg, Value = qualifiedPath }, new CommandArgument() { Name = "PathType", Value = "Container" }); if (isContainer) { pathType = PscxPathType.Container; } } return(true); } return(false); }
protected override void ProcessPath(PscxPathInfo pscxPath) { if (ShouldProcess(pscxPath.ProviderPath)) { var fi = Utils.GetFileOrDirectory(pscxPath.ProviderPath); if ((fi.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) { ErrorHandler.WriteIsNotReparsePointError(pscxPath.ProviderPath); return; } if (!DeleteFileOrDirectory(pscxPath, fi)) { ErrorHandler.WriteLastWin32Error("RemoveReparsePointFailed", Path); return; } } base.ProcessPath(pscxPath); }
protected override void ProcessPath(PscxPathInfo pscxPath) { try { if (List) { IList<AlternateDataStreamInfo> streamInfos = FileSystem.ListAlternateDataStreams(pscxPath.ProviderPath); WriteObject(streamInfos, true); } else { foreach (string aName in Name) { if (!FileSystem.AlternateDataStreamExists(pscxPath.ProviderPath, aName)) { this.ErrorHandler.WriteAlternateDataStreamDoentExist(aName, pscxPath.ProviderPath); continue; } AlternateDataStreamInfo streamInfo = FileSystem.GetAlternateDataStream(pscxPath.ProviderPath, aName); WriteObject(streamInfo); } } } catch (SecurityException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (UnauthorizedAccessException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (PipelineStoppedException) { throw; } catch (Exception ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.NotSpecified, pscxPath.ProviderPath)); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { try { if (FileSystem.AlternateDataStreamExists(pscxPath.ProviderPath, _adsName)) { string filename = System.IO.Path.GetFileName(pscxPath.ProviderPath); if (this.ShouldProcess(filename, "unblocking file")) { FileSystem.DeleteAlternateDataStream(pscxPath.ProviderPath, _adsName); } } else { WriteWarning(String.Format(Properties.Resources.UnblockedAlready_F1, pscxPath.ProviderPath)); } if (this.PassThru) { WriteObject(base.InputObject); } } catch (SecurityException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (UnauthorizedAccessException ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.SecurityError, pscxPath.ProviderPath)); } catch (PipelineStoppedException) { throw; } catch (Exception ex) { WriteError(new ErrorRecord(ex, "FileError", ErrorCategory.NotSpecified, pscxPath.ProviderPath)); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { PortableExecutableInfo info = null; string filePath = pscxPath.ProviderPath; try { info = new PortableExecutableInfo(filePath); } catch (PipelineStoppedException) { throw; } catch(Exception exc) { WriteError(new ErrorRecord(exc, "InvalidPEImage", ErrorCategory.InvalidData, filePath)); } if(info != null) { ProcessImage(info); } }
public void ProcessPath(PscxPathInfo pscxPath) { _command.WriteVerbose("Add/update " + pscxPath); try { if (_command.InvokeProvider.Item.IsContainer(pscxPath.ToString())) { //_zip.AddDirectory(pscxPath.ProviderPath); } else { string fileName = pscxPath.ProviderPath; if (_command.FlattenPaths.IsPresent) { fileName = Path.GetFileName(pscxPath.ProviderPath); _command.WriteVerbose(String.Format("Flattened '{0}' to '{1}'", pscxPath.ProviderPath, fileName)); //_zip.Add(pscxPath.ProviderPath, fileName); // new overload to SZL 0.86 (fixes -append -flattenpath bug) } else { //_zip.Add(fileName); } } } catch (PipelineStoppedException) { throw; } catch (Exception ex) { var error = new ErrorRecord(ex, "ZipAddOrUpdateFail", ErrorCategory.WriteError, pscxPath); // perhaps allow erroraction to control whether terminating or not _command.ThrowTerminatingError(error); } }
protected override void ProcessPath(PscxPathInfo pscxPath) { DisplayFileAsHex(pscxPath.ProviderPath); }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; if (ShouldProcess(filePath + ". Update " + _updateType + " time.")) { ChangeFileTimes(filePath); if (_passThru) { WriteObject(new FileInfo(filePath)); } } }
protected override void ProcessPath(PscxPathInfo pscxPath) { // FileSystemProvider should be enforced on deriving commands since // this code assumes Path points to a file. FileHandler.ProcessText(pscxPath.ProviderPath, ProcessTextReader); }
protected override void ProcessPath(PscxPathInfo pscxPath) { var archive = new FileInfo(pscxPath.ProviderPath); ProcessArchive(archive); }
/// <summary> /// /// </summary> /// <param name="pscxPath"></param> /// <param name="pathType"></param> /// <returns></returns> public static bool Exists(PscxPathInfo pscxPath, ref PscxPathType pathType) { string qualifiedPath = pscxPath.ToString(); pathType = PscxPathType.Unknown; string pathArg = (pscxPath.IsUnresolved) ? "LiteralPath" : "Path"; if (Exists(pscxPath)) { bool isLeaf = PipelineHelper.ExecuteScalar<bool>( new Command("Test-Path"), new CommandArgument() {Name = pathArg, Value = qualifiedPath}, new CommandArgument() {Name = "PathType", Value = "Leaf"}); if (isLeaf) { pathType = PscxPathType.Leaf; } else { bool isContainer = PipelineHelper.ExecuteScalar<bool>( new Command("Test-Path"), new CommandArgument() {Name = pathArg, Value = qualifiedPath}, new CommandArgument() {Name = "PathType", Value = "Container"}); if (isContainer) { pathType = PscxPathType.Container; } } return true; } return false; }
private void ValidatePathType(string parameterName, PscxPathInfo pscxPath, PscxPathType pathType, PscxPathType expectedPathType) { WriteDebug("ValidatePathType: expecting " + pathType); if ((pathType & expectedPathType) != pathType) { // TODO: localize string description = String.Format("Path type is {0}; expecting {1}", pathType, expectedPathType); // path type violation (terminating) OnPscxPathError(parameterName, description, PscxPathState.InvalidPathType, pscxPath); } }
/// <summary> /// /// </summary> /// <param name="parameterName"></param> /// <param name="pathAttrib"></param> /// <param name="pscxPath"></param> protected void CheckProviderConstraints(PscxPathInfo pscxPath, PscxPathAttribute pathAttrib, string parameterName) { WriteDebug("CheckProviderConstraints"); // get cmdlet-level policy. ProviderConstraintPolicy effectivePolicy = this._defaultPolicy; if (pathAttrib != null && (pathAttrib.ConstraintPolicy != ProviderConstraintPolicy.Default)) { effectivePolicy = pathAttrib.ConstraintPolicy; } var violations = new Collection<Pair<PscxPathInfo, Type>>(); var constraints = new List<Type>(); if (_defaultProviderConstraint != null) { constraints.AddRange(_defaultProviderConstraint.ProviderTypes); } if (pathAttrib != null && (pathAttrib.ProviderTypes != null)) { constraints.AddRange(pathAttrib.ProviderTypes); } // TODO: localize string description = String.Format( "The path '{0}' supplied for {1} is not contained in a provider compatible with {2}.", pscxPath, parameterName, this.CmdletName); bool constrained = false; Type providerType = pscxPath.Provider.ImplementingType; foreach (Type typeConstraint in constraints) { if (!typeConstraint.IsAssignableFrom(providerType)) { constrained = true; if (effectivePolicy == ProviderConstraintPolicy.EnforceAll) { // enforcing all, so notify now. // write verbose reason for fail WriteVerbose(String.Format("The constraint check for the interface or base class '{0}' against the provider '{1}' failed.", typeConstraint, pscxPath.Provider.Name)); // terminating error OnPscxPathError(parameterName, description, PscxPathState.ProviderConstraintFailure, pscxPath); } else { // enforcing only one; a subsequent check may pass. violations.Add(new Pair<PscxPathInfo, Type>(pscxPath, typeConstraint)); } } else { constrained = false; if (effectivePolicy == ProviderConstraintPolicy.EnforceOne) { // we passed at least one, so stop checking. break; } } } // if all checks failed (and enforcing all), then fail. if (constrained && (effectivePolicy == ProviderConstraintPolicy.EnforceOne)) { foreach (Pair<PscxPathInfo, Type> violation in violations) { // write out verbose reason for failure. WriteVerbose(String.Format("The constraint check for the interface or base class '{0}' against the provider '{1}' failed.", violation.Second, pscxPath.Provider.Name)); } // terminating error OnPscxPathError(parameterName, description, PscxPathState.ProviderConstraintFailure, pscxPath); } }
private void ValidateExists(string parameterName, PscxPathInfo pscxPath, ref PscxPathType pathType) { WriteDebug("ValidateExists"); bool exists = PscxPathInfo.Exists(pscxPath, ref pathType); if (!exists) { // TODO: localize string description = String.Format( "The path '{0}' supplied for {1} must exist.", pscxPath, parameterName); // terminates by default (unless overridden) OnPscxPathError(parameterName, description, PscxPathState.NotExist, pscxPath); } }
private void ValidatePscxPath(string parameterName, PscxPathAttribute pathAttrib, PscxPathInfo pscxPath) { WriteDebug(String.Format("ValidatePscxPath: parameter {0} ; pscxPath {1}", parameterName, pscxPath)); if (pscxPath.IsValid == false) { // todo: localize string description = String.Format( "The path '{0}' supplied for {1} is invalid.", pscxPath, parameterName); // path syntax error OnPscxPathError(parameterName, description, PscxPathState.Invalid, pscxPath); } PscxPathType pathType = PscxPathType.Unknown; // explicit true or unset if (pathAttrib.ShouldExist || (pathAttrib._shouldExist == null)) { if (pathAttrib.ShouldExist) { // explicit true, so check existance ValidateExists(parameterName, pscxPath, ref pathType); } else { // shouldexist not specified, so grab path type via invokeprovider pathType = this.InvokeProvider.Item.IsContainer(pscxPath.ToString()) ? PscxPathType.Container : PscxPathType.Leaf; } PscxPathType expectedPathType = pathAttrib.PathType; // do we have a path type constraint? if (expectedPathType != PscxPathType.None) { ValidatePathType(parameterName, pscxPath, pathType, expectedPathType); } } else // shouldexist explicit false { // NOTE: for Pscx developers Trace.Assert(pathAttrib.PathType == PscxPathType.None, String.Format( "Pscx Developer Error: {0}\n\nIf a PathType constraint is placed on a parameter, " + "ShouldExist cannot be explicitly set to false. Remove " + "the ShouldExist condition from the attribute, or set it " + "explicitly to true.\n\nIf you are seeing this message " + "as a Pscx end-user, please log an issue on " + "http://www.codeplex.com/powershellcx", CmdletName)); } // any provider constraints defined on the PscxPath attribute, // or on a Type-level ProviderConstraint attribute? if ((pathAttrib.ProviderTypes != null) || (_defaultProviderConstraint != null)) { CheckProviderConstraints(pscxPath, pathAttrib, parameterName); } }
protected override void ProcessRecord() { // changed to use separate backing variables for Path and LiteralPath // so PscxCmdlet's ValidatePscxPath routines can detect the parameterset // in use without knowledge of this derived class. (oisin) PscxPathInfo[] paths = (this.ParameterSetName == ParameterSetPath) ? _paths : _literalPaths; CurrentPscxPathInfo = null; foreach (PscxPathInfo pscxPath in paths) { WriteDebug(String.Format("{0} processing pscxPath '{1}'", this.CmdletName, pscxPath)); CurrentPscxPathInfo = pscxPath; ProcessPath(pscxPath); } }
/// <summary> /// /// </summary> /// <param name="pscxPath"></param> protected virtual void ProcessPath(PscxPathInfo pscxPath) { }
/// <summary> /// Terminating error. /// </summary> /// <param name="parameterName"></param> /// <param name="description"></param> /// <param name="reason"></param> /// <param name="pscxPath"></param> protected virtual void OnPscxPathError(string parameterName, string description, PscxPathState reason, PscxPathInfo pscxPath) { string errorMessage = String.Format("{0}'s {1} parameter has an invalid path of '{2}': {3}", this.CmdletName, parameterName, pscxPath.SourcePath, description); var exception = new PSArgumentException(errorMessage, parameterName); this.ThrowTerminatingError( new ErrorRecord(exception, reason.ToString(), ErrorCategory.InvalidArgument, parameterName)); }
protected override void ProcessPath(PscxPathInfo pscxPath) { string filePath = pscxPath.ProviderPath; WriteVerbose(this.CmdletName + " " + filePath); using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { // Determine encoding of file if it wasn't specified via the Encoding parameter. Encoding encoding; if (this.Encoding.IsPresent) { encoding = this.Encoding.ToEncoding(); } else { // Attempt to auto-detect encoding using StreamReader var detectReader = new StreamReader(stream, true); var buffer = new char[1]; if (detectReader.Read(buffer, 0, buffer.Length) == buffer.Length) { encoding = detectReader.CurrentEncoding; // Handle UTF8 here because StreamReader's auto-detect return UTF8 for plain ASCII (no BOM) if (!(encoding is ASCIIEncoding) && !(encoding is UnicodeEncoding) && !(encoding is UTF8Encoding)) { var ex = new Exception("Encoding not supported: " + encoding.GetType().Name); var error = new ErrorRecord(ex, "TailContentFail", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } } else { // Default to Unicode since PowerShell outputs to files in Unicode by default encoding = System.Text.Encoding.Unicode; } detectReader.DiscardBufferedData(); } byte[] lineTerminatorByteSequence = encoding.GetBytes(this.LineTerminator); int numTerminatorBytes = lineTerminatorByteSequence.Length; var content = new List<byte>(); int numLines = this.Count; bool initialSeek = true; long initLength = stream.Length; long seekOffset = stream.Length - 1; while ((numLines > 0) && (seekOffset >= 0)) { stream.Seek(seekOffset--, SeekOrigin.Begin); int ch = stream.ReadByte(); // If this is unicode, sync up the byte pointer to beginning of a unicode char if (initialSeek && (encoding is UnicodeEncoding)) { while ((ch != 0) && (seekOffset >= 0)) { stream.Seek(seekOffset--, SeekOrigin.Begin); initLength -= 1; ch = stream.ReadByte(); } } initialSeek = false; content.Insert(0, (byte)ch); // Determine if we have a found a line terminator sequence. Note: Ignore the // first line terminator from the end of the file. if ((content.Count > numTerminatorBytes) && Array.Exists(lineTerminatorByteSequence, item => item == (byte)ch)) { bool foundCompleteLineTerminationSequence = true; for (int i = 0; i < numTerminatorBytes; i++) { if (content[i] != lineTerminatorByteSequence[i]) { foundCompleteLineTerminationSequence = false; break; } } // Don't count the last line terminator in the file (if there is one) against the numLines count if (foundCompleteLineTerminationSequence) { numLines--; } } } // Strip Unicode and UTF8 BOMs if they exist if ((content.Count >= 2) && (content[0] == 0xFF) && (content[1] == 0xFE)) { content.RemoveRange(0, 2); } else if ((content.Count >= 3) && (content[0] == 0xEF) && (content[1] == 0xBB) && (content[2] == 0xBF)) { content.RemoveRange(0, 3); } string output = encoding.GetString(content.ToArray()); if (output.StartsWith(this.LineTerminator)) { output = output.Substring(this.LineTerminator.Length); } if (!this.Wait) { if (output.EndsWith(this.LineTerminator)) { output = output.Substring(0, output.Length - this.LineTerminator.Length); } WriteObject(output); } else { Host.UI.Write(output); // To support Unicode, the buffer size must be a multiple of 2. var buffer = new byte[8192]; stream.Seek(initLength, SeekOrigin.Begin); // User presses Ctrl+C to break out of this while (!this.Stopping) { // Take snapshot of length since it is mostly likely growing long fileLength = stream.Length; if (fileLength > initLength) { long numBytesAvailable = fileLength - initLength; long numBytesToRead = numBytesAvailable - (encoding is UnicodeEncoding ? (numBytesAvailable % 2) : 0); do { int readCount = (int)Math.Min(buffer.Length, numBytesToRead); int numRead = stream.Read(buffer, 0, readCount); // For Unicode support the numRead better not ever be odd (will get out of codepoint sync) Debug.Assert(!(encoding is UnicodeEncoding) || (numRead % 2 == 0)); string chars = encoding.GetString(buffer, 0, numRead); Host.UI.Write(chars); numBytesToRead -= numRead; initLength += numRead; } while (numBytesToRead > 0); } // Be kind to the CPU - don't suck up unnecessary cycles Thread.Sleep(200); } } } }
private void ValidatePscxPaths() { _boundPaths = new List<Pair<PropertyInfo, PscxPathAttribute>>(); var visitor = new Visitor(this); visitor.VisitType(GetType()); foreach (var boundPath in _boundPaths) { PropertyInfo parameter = boundPath.First; string parameterName = parameter.Name; // retrieve [PscxPath] attribute PscxPathAttribute pathAttrib = boundPath.Second; // get property value object value = parameter.GetValue(this, null); if ((value != null) && // allow runtime modification from derived classes OnValidatePscxPath(parameterName, pathAttrib)) { WriteDebug("Validating " + parameterName); PscxPathInfo[] pscxPaths = null; // may be array if (value is Array) { pscxPaths = value as PscxPathInfo[]; } else { var pscxPath = value as PscxPathInfo; if (pscxPath != null) { pscxPaths = new PscxPathInfo[] { pscxPath }; } } if (pscxPaths != null) { foreach (PscxPathInfo pscxPath in pscxPaths) { ValidatePscxPath(parameterName, pathAttrib, pscxPath); } } } else { WriteDebug("Skipping " + parameterName); } } }