File size: 24,980 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The base class for the */content commands.
/// </summary>
public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command.
/// </summary>
[Parameter(Position = 0, ParameterSetName = "Path",
Mandatory = true, ValueFromPipelineByPropertyName = true)]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets the literal path parameter to the command.
/// </summary>
[Parameter(ParameterSetName = "LiteralPath",
Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath", "LP")]
public string[] LiteralPath
{
get
{
return Path;
}
set
{
base.SuppressWildcardExpansion = true;
Path = value;
}
}
/// <summary>
/// Gets or sets the filter property.
/// </summary>
[Parameter]
public override string Filter
{
get { return base.Filter; }
set { base.Filter = value; }
}
/// <summary>
/// Gets or sets the include property.
/// </summary>
[Parameter]
public override string[] Include
{
get { return base.Include; }
set { base.Include = value; }
}
/// <summary>
/// Gets or sets the exclude property.
/// </summary>
[Parameter]
public override string[] Exclude
{
get { return base.Exclude; }
set { base.Exclude = value; }
}
/// <summary>
/// Gets or sets the force property.
/// </summary>
/// <remarks>
/// Gives the provider guidance on how vigorous it should be about performing
/// the operation. If true, the provider should do everything possible to perform
/// the operation. If false, the provider should attempt the operation but allow
/// even simple errors to terminate the operation.
/// For example, if the user tries to copy a file to a path that already exists and
/// the destination is read-only, if force is true, the provider should copy over
/// the existing read-only file. If force is false, the provider should write an error.
/// </remarks>
[Parameter]
public override SwitchParameter Force
{
get { return base.Force; }
set { base.Force = value; }
}
#endregion Parameters
#region parameter data
#endregion parameter data
#region protected members
/// <summary>
/// An array of content holder objects that contain the path information
/// and content readers/writers for the item represented by the path information.
/// </summary>
internal List<ContentHolder> contentStreams = new();
/// <summary>
/// Wraps the content into a PSObject and adds context information as notes.
/// </summary>
/// <param name="content">
/// The content being written out.
/// </param>
/// <param name="readCount">
/// The number of blocks that have been read so far.
/// </param>
/// <param name="pathInfo">
/// The context the content was retrieved from.
/// </param>
/// <param name="context">
/// The context the command is being run under.
/// </param>
internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
content != null,
"The caller should verify the content.");
Dbg.Diagnostics.Assert(
pathInfo != null,
"The caller should verify the pathInfo.");
Dbg.Diagnostics.Assert(
context != null,
"The caller should verify the context.");
PSObject result = PSObject.AsPSObject(content);
Dbg.Diagnostics.Assert(
result != null,
"A PSObject should always be constructed.");
// Use the cached notes if the cache exists and the path is still the same
PSNoteProperty note;
if (_currentContentItem != null &&
((_currentContentItem.PathInfo == pathInfo) ||
string.Equals(
pathInfo.Path,
_currentContentItem.PathInfo.Path,
StringComparison.OrdinalIgnoreCase)))
{
result = _currentContentItem.AttachNotes(result);
}
else
{
// Generate a new cache item and cache the notes
_currentContentItem = new ContentPathsCache(pathInfo);
// Construct a provider qualified path as the Path note
string psPath = pathInfo.Path;
note = new PSNoteProperty("PSPath", psPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath);
_currentContentItem.PSPath = psPath;
try
{
// Now get the parent path and child name
string parentPath = null;
if (pathInfo.Drive != null)
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context);
}
else
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, string.Empty, context);
}
note = new PSNoteProperty("PSParentPath", parentPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath);
_currentContentItem.ParentPath = parentPath;
// Get the child name
string childName = SessionState.Path.ParseChildName(pathInfo.Path, context);
note = new PSNoteProperty("PSChildName", childName);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName);
_currentContentItem.ChildName = childName;
}
catch (NotSupportedException)
{
// Ignore. The object just won't have ParentPath or ChildName set.
}
// PSDriveInfo
if (pathInfo.Drive != null)
{
PSDriveInfo drive = pathInfo.Drive;
note = new PSNoteProperty("PSDrive", drive);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive);
_currentContentItem.Drive = drive;
}
// ProviderInfo
ProviderInfo provider = pathInfo.Provider;
note = new PSNoteProperty("PSProvider", provider);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider);
_currentContentItem.Provider = provider;
}
// Add the ReadCount note
note = new PSNoteProperty("ReadCount", readCount);
result.Properties.Add(note, true);
WriteObject(result);
}
/// <summary>
/// A cache of the notes that get added to the content items as they are written
/// to the pipeline.
/// </summary>
private ContentPathsCache _currentContentItem;
/// <summary>
/// A class that stores a cache of the notes that get attached to content items
/// as they get written to the pipeline. An instance of this cache class is
/// only valid for a single path.
/// </summary>
internal sealed class ContentPathsCache
{
/// <summary>
/// Constructs a content cache item.
/// </summary>
/// <param name="pathInfo">
/// The path information for which the cache will be bound.
/// </param>
public ContentPathsCache(PathInfo pathInfo)
{
PathInfo = pathInfo;
}
/// <summary>
/// The path information for the cached item.
/// </summary>
public PathInfo PathInfo { get; }
/// <summary>
/// The cached PSPath of the item.
/// </summary>
public string PSPath { get; set; }
/// <summary>
/// The cached parent path of the item.
/// </summary>
public string ParentPath { get; set; }
/// <summary>
/// The cached drive for the item.
/// </summary>
public PSDriveInfo Drive { get; set; }
/// <summary>
/// The cached provider of the item.
/// </summary>
public ProviderInfo Provider { get; set; }
/// <summary>
/// The cached child name of the item.
/// </summary>
public string ChildName { get; set; }
/// <summary>
/// Attaches the cached notes to the specified PSObject.
/// </summary>
/// <param name="content">
/// The PSObject to attached the cached notes to.
/// </param>
/// <returns>
/// The PSObject that was passed in with the cached notes added.
/// </returns>
public PSObject AttachNotes(PSObject content)
{
// Construct a provider qualified path as the Path note
PSNoteProperty note = new("PSPath", PSPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath);
// Now attach the parent path and child name
note = new PSNoteProperty("PSParentPath", ParentPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath);
// Attach the child name
note = new PSNoteProperty("PSChildName", ChildName);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName);
// PSDriveInfo
if (PathInfo.Drive != null)
{
note = new PSNoteProperty("PSDrive", Drive);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive);
}
// ProviderInfo
note = new PSNoteProperty("PSProvider", Provider);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider);
return content;
}
}
/// <summary>
/// A struct to hold the path information and the content readers/writers
/// for an item.
/// </summary>
internal readonly struct ContentHolder
{
internal ContentHolder(
PathInfo pathInfo,
IContentReader reader,
IContentWriter writer)
{
if (pathInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pathInfo));
}
PathInfo = pathInfo;
Reader = reader;
Writer = writer;
}
internal PathInfo PathInfo { get; }
internal IContentReader Reader { get; }
internal IContentWriter Writer { get; }
}
/// <summary>
/// Closes the content readers and writers in the content holder array.
/// </summary>
internal void CloseContent(List<ContentHolder> contentHolders, bool disposing)
{
if (contentHolders == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(contentHolders));
}
foreach (ContentHolder holder in contentHolders)
{
try
{
holder.Writer?.Close();
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
try
{
holder.Reader?.Close();
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
}
}
/// <summary>
/// Overridden by derived classes to support ShouldProcess with
/// the appropriate information.
/// </summary>
/// <param name="path">
/// The path to the item from which the content writer will be
/// retrieved.
/// </param>
/// <returns>
/// True if the action should continue or false otherwise.
/// </returns>
internal virtual bool CallShouldProcess(string path)
{
return true;
}
/// <summary>
/// Gets the IContentReaders for the current path(s)
/// </summary>
/// <returns>
/// An array of IContentReaders for the current path(s)
/// </returns>
internal List<ContentHolder> GetContentReaders(
string[] readerPaths,
CmdletProviderContext currentCommandContext)
{
// Resolve all the paths into PathInfo objects
Collection<PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext);
// Create the results array
List<ContentHolder> results = new();
foreach (PathInfo pathInfo in pathInfos)
{
// For each path, get the content writer
Collection<IContentReader> readers = null;
try
{
string pathToProcess = WildcardPattern.Escape(pathInfo.Path);
if (currentCommandContext.SuppressWildcardExpansion)
{
pathToProcess = pathInfo.Path;
}
readers =
InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (readers != null && readers.Count > 0)
{
if (readers.Count == 1 && readers[0] != null)
{
ContentHolder holder =
new(pathInfo, readers[0], null);
results.Add(holder);
}
}
}
return results;
}
/// <summary>
/// Resolves the specified paths to PathInfo objects.
/// </summary>
/// <param name="pathsToResolve">
/// The paths to be resolved. Each path may contain glob characters.
/// </param>
/// <param name="allowNonexistingPaths">
/// If true, resolves the path even if it doesn't exist.
/// </param>
/// <param name="allowEmptyResult">
/// If true, allows a wildcard that returns no results.
/// </param>
/// <param name="currentCommandContext">
/// The context under which the command is running.
/// </param>
/// <returns>
/// An array of PathInfo objects that are the resolved paths for the
/// <paramref name="pathsToResolve"/> parameter.
/// </returns>
internal Collection<PathInfo> ResolvePaths(
string[] pathsToResolve,
bool allowNonexistingPaths,
bool allowEmptyResult,
CmdletProviderContext currentCommandContext)
{
Collection<PathInfo> results = new();
foreach (string path in pathsToResolve)
{
bool pathNotFound = false;
bool filtersHidPath = false;
ErrorRecord pathNotFoundErrorRecord = null;
try
{
// First resolve each of the paths
Collection<PathInfo> pathInfos =
SessionState.Path.GetResolvedPSPathFromPSPath(
path,
currentCommandContext);
if (pathInfos.Count == 0)
{
pathNotFound = true;
// If the item simply did not exist,
// we would have got an ItemNotFoundException.
// If we get here, it's because the filters
// excluded the file.
if (!currentCommandContext.SuppressWildcardExpansion)
{
filtersHidPath = true;
}
}
foreach (PathInfo pathInfo in pathInfos)
{
results.Add(pathInfo);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
}
catch (ItemNotFoundException pathNotFoundException)
{
pathNotFound = true;
pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException);
}
if (pathNotFound)
{
if (allowNonexistingPaths &&
(!filtersHidPath) &&
(currentCommandContext.SuppressWildcardExpansion ||
(!WildcardPattern.ContainsWildcardCharacters(path))))
{
ProviderInfo provider = null;
PSDriveInfo drive = null;
string unresolvedPath =
SessionState.Path.GetUnresolvedProviderPathFromPSPath(
path,
currentCommandContext,
out provider,
out drive);
PathInfo pathInfo =
new(
drive,
provider,
unresolvedPath,
SessionState);
results.Add(pathInfo);
}
else
{
if (pathNotFoundErrorRecord == null)
{
// Detect if the path resolution failed to resolve to a file.
string error = StringUtil.Format(NavigationResources.ItemNotFound, Path);
Exception e = new(error);
pathNotFoundErrorRecord = new ErrorRecord(
e,
"ItemNotFound",
ErrorCategory.ObjectNotFound,
Path);
}
WriteError(pathNotFoundErrorRecord);
}
}
}
return results;
}
#endregion protected members
#region IDisposable
internal void Dispose(bool isDisposing)
{
if (isDisposing)
{
CloseContent(contentStreams, true);
contentStreams = new List<ContentHolder>();
}
}
/// <summary>
/// Dispose method in IDisposable.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable
}
}
|