Skip to content

Commit 0bae625

Browse files
committedApr 23, 2014
Adds Wim images management script
1 parent ab803b9 commit 0bae625

File tree

1 file changed

+1085
-0
lines changed

1 file changed

+1085
-0
lines changed
 

‎WimFileInfo.ps1

+1,085
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,1085 @@
1+
<#
2+
.NOTES
3+
MICROSOFT LIMITED PUBLIC LICENSE version 1.1
4+
This license governs use of code marked as “sample” or “example” available on this web site without a license agreement, as provided under the section above titled “NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEB SITE.” If you use such code (the “software”), you accept this license. If you do not accept the license, do not use the software.
5+
6+
1. Definitions
7+
The terms “reproduce,” “reproduction,” “derivative works,” and “distribution” have the same meaning here as under U.S. copyright law.
8+
A “contribution” is the original software, or any additions or changes to the software.
9+
A “contributor” is any person that distributes its contribution under this license.
10+
“Licensed patents” are a contributor’s patent claims that read directly on its contribution.
11+
12+
2. Grant of Rights
13+
(A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
14+
(B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
15+
16+
3. Conditions and Limitations
17+
(A) No Trademark License- This license does not grant you rights to use any contributors’ name, logo, or trademarks.
18+
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
19+
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
20+
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
21+
(E) The software is licensed “as-is.” You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
22+
(F) Platform Limitation - The licenses granted in sections 2(A) and 2(B) extend only to the software or derivative works that you create that run directly on a Microsoft Windows operating system product, Microsoft run-time technology (such as the .NET Framework or Silverlight), or Microsoft application platform (such as Microsoft Office or Microsoft Dynamics).
23+
#>
24+
25+
$code = @"
26+
/*
27+
From: http://gallery.technet.microsoft.com/scriptcenter/Convert-WindowsImageps1-0fe23a8f
28+
*/
29+
30+
using System;
31+
using System.Collections.Generic;
32+
using System.Collections.ObjectModel;
33+
using System.ComponentModel;
34+
using System.Globalization;
35+
using System.IO;
36+
using System.Linq;
37+
using System.Runtime.InteropServices;
38+
using System.Security;
39+
using System.Text;
40+
using System.Text.RegularExpressions;
41+
using System.Threading;
42+
using System.Xml.Linq;
43+
using System.Xml.XPath;
44+
using Microsoft.Win32.SafeHandles;
45+
46+
namespace WIMInterop {
47+
48+
/// <summary>
49+
/// P/Invoke methods and associated enums, flags, and structs.
50+
/// </summary>
51+
public class
52+
NativeMethods {
53+
54+
#region Delegates and Callbacks
55+
#region WIMGAPI
56+
57+
///<summary>
58+
///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function.
59+
///</summary>
60+
///<param name="MessageId">Specifies the message being sent.</param>
61+
///<param name="wParam">Specifies additional message information. The contents of this parameter depend on the value of the
62+
///MessageId parameter.</param>
63+
///<param name="lParam">Specifies additional message information. The contents of this parameter depend on the value of the
64+
///MessageId parameter.</param>
65+
///<param name="UserData">Specifies the user-defined value passed to RegisterCallback.</param>
66+
///<returns>
67+
///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS.
68+
///To prevent other subscribers from receiving the message, return WIM_MSG_DONE.
69+
///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message.
70+
///</returns>
71+
public delegate uint
72+
WimMessageCallback(
73+
uint MessageId,
74+
IntPtr wParam,
75+
IntPtr lParam,
76+
IntPtr UserData
77+
);
78+
79+
public static void
80+
RegisterMessageCallback(
81+
WimFileHandle hWim,
82+
WimMessageCallback callback) {
83+
84+
uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero);
85+
int rc = Marshal.GetLastWin32Error();
86+
if (0 != rc) {
87+
// Throw an exception if something bad happened on the Win32 end.
88+
throw
89+
new InvalidOperationException(
90+
string.Format(
91+
CultureInfo.CurrentCulture,
92+
"Unable to register message callback."
93+
));
94+
}
95+
}
96+
97+
public static void
98+
UnregisterMessageCallback(
99+
WimFileHandle hWim,
100+
WimMessageCallback registeredCallback) {
101+
102+
bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback);
103+
int rc = Marshal.GetLastWin32Error();
104+
if (!status) {
105+
throw
106+
new InvalidOperationException(
107+
string.Format(
108+
CultureInfo.CurrentCulture,
109+
"Unable to unregister message callback."
110+
));
111+
}
112+
}
113+
114+
#endregion WIMGAPI
115+
#endregion Delegates and Callbacks
116+
117+
#region Constants
118+
119+
#region WIMGAPI
120+
121+
public const uint WIM_FLAG_VERIFY = 0x00000002;
122+
public const uint WIM_FLAG_INDEX = 0x00000004;
123+
124+
public const uint WM_APP = 0x00008000;
125+
126+
#endregion WIMGAPI
127+
128+
#endregion Constants
129+
130+
#region WIMGAPI
131+
132+
[FlagsAttribute]
133+
internal enum
134+
WimCreateFileDesiredAccess
135+
: uint {
136+
WimQuery = 0x00000000,
137+
WimGenericRead = 0x80000000
138+
}
139+
140+
/// <summary>
141+
/// Specifies how the file is to be treated and what features are to be used.
142+
/// </summary>
143+
[FlagsAttribute]
144+
internal enum
145+
WimApplyFlags
146+
: uint {
147+
/// <summary>
148+
/// No flags.
149+
/// </summary>
150+
WimApplyFlagsNone = 0x00000000,
151+
/// <summary>
152+
/// Reserved.
153+
/// </summary>
154+
WimApplyFlagsReserved = 0x00000001,
155+
/// <summary>
156+
/// Verifies that files match original data.
157+
/// </summary>
158+
WimApplyFlagsVerify = 0x00000002,
159+
/// <summary>
160+
/// Specifies that the image is to be sequentially read for caching or performance purposes.
161+
/// </summary>
162+
WimApplyFlagsIndex = 0x00000004,
163+
/// <summary>
164+
/// Applies the image without physically creating directories or files. Useful for obtaining a list of files and directories in the image.
165+
/// </summary>
166+
WimApplyFlagsNoApply = 0x00000008,
167+
/// <summary>
168+
/// Disables restoring security information for directories.
169+
/// </summary>
170+
WimApplyFlagsNoDirAcl = 0x00000010,
171+
/// <summary>
172+
/// Disables restoring security information for files
173+
/// </summary>
174+
WimApplyFlagsNoFileAcl = 0x00000020,
175+
/// <summary>
176+
/// The .wim file is opened in a mode that enables simultaneous reading and writing.
177+
/// </summary>
178+
WimApplyFlagsShareWrite = 0x00000040,
179+
/// <summary>
180+
/// Sends a WIM_MSG_FILEINFO message during the apply operation.
181+
/// </summary>
182+
WimApplyFlagsFileInfo = 0x00000080,
183+
/// <summary>
184+
/// Disables automatic path fixups for junctions and symbolic links.
185+
/// </summary>
186+
WimApplyFlagsNoRpFix = 0x00000100,
187+
/// <summary>
188+
/// Returns a handle that cannot commit changes, regardless of the access level requested at mount time.
189+
/// </summary>
190+
WimApplyFlagsMountReadOnly = 0x00000200,
191+
/// <summary>
192+
/// Reserved.
193+
/// </summary>
194+
WimApplyFlagsMountFast = 0x00000400,
195+
/// <summary>
196+
/// Reserved.
197+
/// </summary>
198+
WimApplyFlagsMountLegacy = 0x00000800
199+
}
200+
201+
public enum WimMessage : uint {
202+
WIM_MSG = WM_APP + 0x1476,
203+
WIM_MSG_TEXT,
204+
///<summary>
205+
///Indicates an update in the progress of an image application.
206+
///</summary>
207+
WIM_MSG_PROGRESS,
208+
///<summary>
209+
///Enables the caller to prevent a file or a directory from being captured or applied.
210+
///</summary>
211+
WIM_MSG_PROCESS,
212+
///<summary>
213+
///Indicates that volume information is being gathered during an image capture.
214+
///</summary>
215+
WIM_MSG_SCANNING,
216+
///<summary>
217+
///Indicates the number of files that will be captured or applied.
218+
///</summary>
219+
WIM_MSG_SETRANGE,
220+
///<summary>
221+
///Indicates the number of files that have been captured or applied.
222+
///</summary>
223+
WIM_MSG_SETPOS,
224+
///<summary>
225+
///Indicates that a file has been either captured or applied.
226+
///</summary>
227+
WIM_MSG_STEPIT,
228+
///<summary>
229+
///Enables the caller to prevent a file resource from being compressed during a capture.
230+
///</summary>
231+
WIM_MSG_COMPRESS,
232+
///<summary>
233+
///Alerts the caller that an error has occurred while capturing or applying an image.
234+
///</summary>
235+
WIM_MSG_ERROR,
236+
///<summary>
237+
///Enables the caller to align a file resource on a particular alignment boundary.
238+
///</summary>
239+
WIM_MSG_ALIGNMENT,
240+
WIM_MSG_RETRY,
241+
///<summary>
242+
///Enables the caller to align a file resource on a particular alignment boundary.
243+
///</summary>
244+
WIM_MSG_SPLIT,
245+
WIM_MSG_SUCCESS = 0x00000000,
246+
WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF
247+
}
248+
249+
internal enum
250+
WimCreationDisposition
251+
: uint {
252+
WimOpenExisting = 0x00000003,
253+
}
254+
255+
internal enum
256+
WimActionFlags
257+
: uint {
258+
WimIgnored = 0x00000000
259+
}
260+
261+
internal enum
262+
WimCompressionType
263+
: uint {
264+
WimIgnored = 0x00000000
265+
}
266+
267+
internal enum
268+
WimCreationResult
269+
: uint {
270+
WimCreatedNew = 0x00000000,
271+
WimOpenedExisting = 0x00000001
272+
}
273+
274+
#endregion WIMGAPI
275+
276+
#region WIMGAPI P/Invoke
277+
278+
#region SafeHandle wrappers for WimFileHandle and WimImageHandle
279+
280+
public sealed class WimFileHandle : SafeHandle {
281+
282+
public WimFileHandle(
283+
string wimPath)
284+
: base(IntPtr.Zero, true) {
285+
286+
if (String.IsNullOrEmpty(wimPath)) {
287+
throw new ArgumentNullException("wimPath");
288+
}
289+
290+
if (!File.Exists(Path.GetFullPath(wimPath))) {
291+
throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
292+
}
293+
294+
NativeMethods.WimCreationResult creationResult;
295+
296+
this.handle = NativeMethods.WimCreateFile(
297+
wimPath,
298+
NativeMethods.WimCreateFileDesiredAccess.WimGenericRead,
299+
NativeMethods.WimCreationDisposition.WimOpenExisting,
300+
NativeMethods.WimActionFlags.WimIgnored,
301+
NativeMethods.WimCompressionType.WimIgnored,
302+
out creationResult
303+
);
304+
305+
// Check results.
306+
if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) {
307+
throw new Win32Exception();
308+
}
309+
310+
if (this.handle == IntPtr.Zero) {
311+
throw new Win32Exception();
312+
}
313+
314+
// Set the temporary path.
315+
NativeMethods.WimSetTemporaryPath(
316+
this,
317+
Environment.ExpandEnvironmentVariables("%TEMP%")
318+
);
319+
}
320+
321+
protected override bool ReleaseHandle() {
322+
return NativeMethods.WimCloseHandle(this.handle);
323+
}
324+
325+
public override bool IsInvalid {
326+
get { return this.handle == IntPtr.Zero; }
327+
}
328+
}
329+
330+
public sealed class WimImageHandle : SafeHandle {
331+
public WimImageHandle(
332+
WimFile Container,
333+
uint ImageIndex)
334+
: base(IntPtr.Zero, true) {
335+
336+
if (null == Container) {
337+
throw new ArgumentNullException("Container");
338+
}
339+
340+
if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
341+
throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
342+
}
343+
344+
if (ImageIndex > Container.ImageCount) {
345+
throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
346+
}
347+
348+
this.handle = NativeMethods.WimLoadImage(
349+
Container.Handle.DangerousGetHandle(),
350+
ImageIndex);
351+
}
352+
353+
protected override bool ReleaseHandle() {
354+
return NativeMethods.WimCloseHandle(this.handle);
355+
}
356+
357+
public override bool IsInvalid {
358+
get { return this.handle == IntPtr.Zero; }
359+
}
360+
}
361+
362+
#endregion SafeHandle wrappers for WimFileHandle and WimImageHandle
363+
364+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")]
365+
internal static extern IntPtr
366+
WimCreateFile(
367+
[In, MarshalAs(UnmanagedType.LPWStr)] string WimPath,
368+
[In] WimCreateFileDesiredAccess DesiredAccess,
369+
[In] WimCreationDisposition CreationDisposition,
370+
[In] WimActionFlags FlagsAndAttributes,
371+
[In] WimCompressionType CompressionType,
372+
[Out, Optional] out WimCreationResult CreationResult
373+
);
374+
375+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")]
376+
[return: MarshalAs(UnmanagedType.Bool)]
377+
internal static extern bool
378+
WimCloseHandle(
379+
[In] IntPtr Handle
380+
);
381+
382+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")]
383+
internal static extern IntPtr
384+
WimLoadImage(
385+
[In] IntPtr Handle,
386+
[In] uint ImageIndex
387+
);
388+
389+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")]
390+
internal static extern uint
391+
WimGetImageCount(
392+
[In] WimFileHandle Handle
393+
);
394+
395+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMApplyImage")]
396+
internal static extern bool
397+
WimApplyImage(
398+
[In] WimImageHandle Handle,
399+
[In, Optional, MarshalAs(UnmanagedType.LPWStr)] string Path,
400+
[In] WimApplyFlags Flags
401+
);
402+
403+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")]
404+
[return: MarshalAs(UnmanagedType.Bool)]
405+
internal static extern bool
406+
WimGetImageInformation(
407+
[In] SafeHandle Handle,
408+
[Out] out StringBuilder ImageInfo,
409+
[Out] out uint SizeOfImageInfo
410+
);
411+
412+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")]
413+
[return: MarshalAs(UnmanagedType.Bool)]
414+
internal static extern bool
415+
WimSetTemporaryPath(
416+
[In] WimFileHandle Handle,
417+
[In] string TempPath
418+
);
419+
420+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
421+
internal static extern uint
422+
WimRegisterMessageCallback(
423+
[In, Optional] WimFileHandle hWim,
424+
[In] WimMessageCallback MessageProc,
425+
[In, Optional] IntPtr ImageInfo
426+
);
427+
428+
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
429+
[return: MarshalAs(UnmanagedType.Bool)]
430+
internal static extern bool
431+
WimUnregisterMessageCallback(
432+
[In, Optional] WimFileHandle hWim,
433+
[In] WimMessageCallback MessageProc
434+
);
435+
436+
437+
#endregion WIMGAPI P/Invoke
438+
}
439+
440+
#region WIM Interop
441+
442+
public class WimFile {
443+
444+
internal XDocument m_xmlInfo;
445+
internal List<WimImage> m_imageList;
446+
447+
private static NativeMethods.WimMessageCallback wimMessageCallback;
448+
449+
#region Events
450+
451+
/// <summary>
452+
/// DefaultImageEvent handler
453+
/// </summary>
454+
public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e);
455+
456+
///<summary>
457+
///ProcessFileEvent handler
458+
///</summary>
459+
public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e);
460+
461+
///<summary>
462+
///Enable the caller to prevent a file resource from being compressed during a capture.
463+
///</summary>
464+
public event ProcessFileEventHandler ProcessFileEvent;
465+
466+
///<summary>
467+
///Indicate an update in the progress of an image application.
468+
///</summary>
469+
public event DefaultImageEventHandler ProgressEvent;
470+
471+
///<summary>
472+
///Alert the caller that an error has occurred while capturing or applying an image.
473+
///</summary>
474+
public event DefaultImageEventHandler ErrorEvent;
475+
476+
///<summary>
477+
///Indicate that a file has been either captured or applied.
478+
///</summary>
479+
public event DefaultImageEventHandler StepItEvent;
480+
481+
///<summary>
482+
///Indicate the number of files that will be captured or applied.
483+
///</summary>
484+
public event DefaultImageEventHandler SetRangeEvent;
485+
486+
///<summary>
487+
///Indicate the number of files that have been captured or applied.
488+
///</summary>
489+
public event DefaultImageEventHandler SetPosEvent;
490+
491+
#endregion Events
492+
493+
private
494+
enum
495+
ImageEventMessage : uint {
496+
///<summary>
497+
///Enables the caller to prevent a file or a directory from being captured or applied.
498+
///</summary>
499+
Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS,
500+
///<summary>
501+
///Notification sent to enable the caller to prevent a file or a directory from being captured or applied.
502+
///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile().
503+
///</summary>
504+
Process = NativeMethods.WimMessage.WIM_MSG_PROCESS,
505+
///<summary>
506+
///Enables the caller to prevent a file resource from being compressed during a capture.
507+
///</summary>
508+
Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS,
509+
///<summary>
510+
///Alerts the caller that an error has occurred while capturing or applying an image.
511+
///</summary>
512+
Error = NativeMethods.WimMessage.WIM_MSG_ERROR,
513+
///<summary>
514+
///Enables the caller to align a file resource on a particular alignment boundary.
515+
///</summary>
516+
Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT,
517+
///<summary>
518+
///Enables the caller to align a file resource on a particular alignment boundary.
519+
///</summary>
520+
Split = NativeMethods.WimMessage.WIM_MSG_SPLIT,
521+
///<summary>
522+
///Indicates that volume information is being gathered during an image capture.
523+
///</summary>
524+
Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING,
525+
///<summary>
526+
///Indicates the number of files that will be captured or applied.
527+
///</summary>
528+
SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE,
529+
///<summary>
530+
///Indicates the number of files that have been captured or applied.
531+
/// </summary>
532+
SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS,
533+
///<summary>
534+
///Indicates that a file has been either captured or applied.
535+
///</summary>
536+
StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT,
537+
///<summary>
538+
///Success.
539+
///</summary>
540+
Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS,
541+
///<summary>
542+
///Abort.
543+
///</summary>
544+
Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE
545+
}
546+
547+
///<summary>
548+
///Event callback to the Wimgapi events
549+
///</summary>
550+
private
551+
uint
552+
ImageEventMessagePump(
553+
uint MessageId,
554+
IntPtr wParam,
555+
IntPtr lParam,
556+
IntPtr UserData) {
557+
558+
uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS;
559+
560+
DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData);
561+
562+
switch ((ImageEventMessage)MessageId) {
563+
564+
case ImageEventMessage.Progress:
565+
ProgressEvent(this, eventArgs);
566+
break;
567+
568+
case ImageEventMessage.Process:
569+
if (null != ProcessFileEvent) {
570+
string fileToImage = Marshal.PtrToStringUni(wParam);
571+
ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam);
572+
ProcessFileEvent(this, fileToProcess);
573+
574+
if (fileToProcess.Abort == true) {
575+
status = (uint)ImageEventMessage.Abort;
576+
}
577+
}
578+
break;
579+
580+
case ImageEventMessage.Error:
581+
if (null != ErrorEvent) {
582+
ErrorEvent(this, eventArgs);
583+
}
584+
break;
585+
586+
case ImageEventMessage.SetRange:
587+
if (null != SetRangeEvent) {
588+
SetRangeEvent(this, eventArgs);
589+
}
590+
break;
591+
592+
case ImageEventMessage.SetPos:
593+
if (null != SetPosEvent) {
594+
SetPosEvent(this, eventArgs);
595+
}
596+
break;
597+
598+
case ImageEventMessage.StepIt:
599+
if (null != StepItEvent) {
600+
StepItEvent(this, eventArgs);
601+
}
602+
break;
603+
604+
default:
605+
break;
606+
}
607+
return status;
608+
609+
}
610+
611+
/// <summary>
612+
/// Constructor.
613+
/// </summary>
614+
/// <param name="wimPath">Path to the WIM container.</param>
615+
public
616+
WimFile(string wimPath) {
617+
if (string.IsNullOrEmpty(wimPath)) {
618+
throw new ArgumentNullException("wimPath");
619+
}
620+
621+
if (!File.Exists(Path.GetFullPath(wimPath))) {
622+
throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
623+
}
624+
625+
Handle = new NativeMethods.WimFileHandle(wimPath);
626+
627+
// Hook up the events before we return.
628+
//wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump);
629+
//NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback);
630+
}
631+
632+
/// <summary>
633+
/// Closes the WIM file.
634+
/// </summary>
635+
public void
636+
Close() {
637+
foreach (WimImage image in Images) {
638+
image.Close();
639+
}
640+
641+
if (null != wimMessageCallback) {
642+
NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback);
643+
wimMessageCallback = null;
644+
}
645+
646+
if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
647+
Handle.Close();
648+
}
649+
}
650+
651+
/// <summary>
652+
/// Provides a list of WimImage objects, representing the images in the WIM container file.
653+
/// </summary>
654+
public List<WimImage>
655+
Images {
656+
get {
657+
if (null == m_imageList) {
658+
659+
int imageCount = (int)ImageCount;
660+
m_imageList = new List<WimImage>(imageCount);
661+
for (int i = 0; i < imageCount; i++) {
662+
663+
// Load up each image so it's ready for us.
664+
m_imageList.Add(
665+
new WimImage(this, (uint)i + 1));
666+
}
667+
}
668+
669+
return m_imageList;
670+
}
671+
}
672+
673+
/// <summary>
674+
/// Provides a list of names of the images in the specified WIM container file.
675+
/// </summary>
676+
public List<string>
677+
ImageNames {
678+
get {
679+
List<string> nameList = new List<string>();
680+
foreach (WimImage image in Images) {
681+
nameList.Add(image.ImageName);
682+
}
683+
return nameList;
684+
}
685+
}
686+
687+
/// <summary>
688+
/// Indexer for WIM images inside the WIM container, indexed by the image number.
689+
/// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that.
690+
/// this[1] returns the 0th image in the WIM container.
691+
/// </summary>
692+
/// <param name="ImageIndex">The 1-based index of the image to retrieve.</param>
693+
/// <returns>WinImage object.</returns>
694+
public WimImage
695+
this[int ImageIndex] {
696+
get { return Images[ImageIndex - 1]; }
697+
}
698+
699+
/// <summary>
700+
/// Indexer for WIM images inside the WIM container, indexed by the image name.
701+
/// WIMs created by different processes sometimes contain different information - including the name.
702+
/// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field.
703+
/// We take all of those into account in while searching the WIM.
704+
/// </summary>
705+
/// <param name="ImageName"></param>
706+
/// <returns></returns>
707+
public WimImage
708+
this[string ImageName] {
709+
get {
710+
return
711+
Images.Where(i => (
712+
i.ImageName.ToUpper() == ImageName.ToUpper() ||
713+
i.ImageFlags.ToUpper() == ImageName.ToUpper() ))
714+
.DefaultIfEmpty(null)
715+
.FirstOrDefault<WimImage>();
716+
}
717+
}
718+
719+
/// <summary>
720+
/// Returns the number of images in the WIM container.
721+
/// </summary>
722+
internal uint
723+
ImageCount {
724+
get { return NativeMethods.WimGetImageCount(Handle); }
725+
}
726+
727+
/// <summary>
728+
/// Returns an XDocument representation of the XML metadata for the WIM container and associated images.
729+
/// </summary>
730+
internal XDocument
731+
XmlInfo {
732+
get {
733+
734+
if (null == m_xmlInfo) {
735+
StringBuilder builder;
736+
uint bytes;
737+
if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
738+
throw new Win32Exception();
739+
}
740+
741+
// Ensure the length of the returned bytes to avoid garbage characters at the end.
742+
int charCount = (int)bytes / sizeof(char);
743+
if (null != builder) {
744+
// Get rid of the unicode file marker at the beginning of the XML.
745+
builder.Remove(0, 1);
746+
builder.EnsureCapacity(charCount - 1);
747+
builder.Length = charCount - 1;
748+
749+
// This isn't likely to change while we have the image open, so cache it.
750+
m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
751+
} else {
752+
m_xmlInfo = null;
753+
}
754+
}
755+
756+
return m_xmlInfo;
757+
}
758+
}
759+
760+
public NativeMethods.WimFileHandle Handle {
761+
get;
762+
private set;
763+
}
764+
}
765+
766+
public class
767+
WimImage {
768+
769+
internal XDocument m_xmlInfo;
770+
771+
public
772+
WimImage(
773+
WimFile Container,
774+
uint ImageIndex) {
775+
776+
if (null == Container) {
777+
throw new ArgumentNullException("Container");
778+
}
779+
780+
if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
781+
throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
782+
}
783+
784+
if (ImageIndex > Container.ImageCount) {
785+
throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
786+
}
787+
788+
Handle = new NativeMethods.WimImageHandle(Container, ImageIndex);
789+
}
790+
791+
public enum
792+
Architectures : uint {
793+
x86 = 0x0,
794+
ARM = 0x5,
795+
IA64 = 0x6,
796+
AMD64 = 0x9
797+
}
798+
799+
public void
800+
Close() {
801+
if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
802+
Handle.Close();
803+
}
804+
}
805+
806+
public void
807+
Apply(
808+
string ApplyToPath) {
809+
810+
if (string.IsNullOrEmpty(ApplyToPath)) {
811+
throw new ArgumentNullException("ApplyToPath");
812+
}
813+
814+
ApplyToPath = Path.GetFullPath(ApplyToPath);
815+
816+
if (!Directory.Exists(ApplyToPath)) {
817+
throw new DirectoryNotFoundException("The WIM cannot be applied because the specified directory was not found.");
818+
}
819+
820+
if (!NativeMethods.WimApplyImage(
821+
this.Handle,
822+
ApplyToPath,
823+
NativeMethods.WimApplyFlags.WimApplyFlagsNone
824+
)) {
825+
throw new Win32Exception();
826+
}
827+
}
828+
829+
public NativeMethods.WimImageHandle
830+
Handle {
831+
get;
832+
private set;
833+
}
834+
835+
internal XDocument
836+
XmlInfo {
837+
get {
838+
839+
if (null == m_xmlInfo) {
840+
StringBuilder builder;
841+
uint bytes;
842+
if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
843+
throw new Win32Exception();
844+
}
845+
846+
// Ensure the length of the returned bytes to avoid garbage characters at the end.
847+
int charCount = (int)bytes / sizeof(char);
848+
if (null != builder) {
849+
// Get rid of the unicode file marker at the beginning of the XML.
850+
builder.Remove(0, 1);
851+
builder.EnsureCapacity(charCount - 1);
852+
builder.Length = charCount - 1;
853+
854+
// This isn't likely to change while we have the image open, so cache it.
855+
m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
856+
} else {
857+
m_xmlInfo = null;
858+
}
859+
}
860+
861+
return m_xmlInfo;
862+
}
863+
}
864+
865+
public string
866+
ImageIndex {
867+
get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; }
868+
}
869+
870+
public string
871+
ImageName {
872+
get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; }
873+
}
874+
875+
public string
876+
ImageEditionId {
877+
get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; }
878+
}
879+
880+
public string
881+
ImageFlags {
882+
get { return XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; }
883+
}
884+
885+
public string
886+
ImageProductType {
887+
get {
888+
return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value;
889+
}
890+
}
891+
892+
public string
893+
ImageInstallationType {
894+
get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; }
895+
}
896+
897+
public string
898+
ImageDescription {
899+
get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; }
900+
}
901+
902+
public ulong
903+
ImageSize {
904+
get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); }
905+
}
906+
907+
public Architectures
908+
ImageArchitecture {
909+
get {
910+
int arch = -1;
911+
try {
912+
arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value);
913+
} catch { }
914+
915+
return (Architectures)arch;
916+
}
917+
}
918+
919+
public string
920+
ImageDefaultLanguage {
921+
get {
922+
string lang = null;
923+
try {
924+
lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value;
925+
} catch { }
926+
927+
return lang;
928+
}
929+
}
930+
931+
public Version
932+
ImageVersion {
933+
get {
934+
int major = 0;
935+
int minor = 0;
936+
int build = 0;
937+
int revision = 0;
938+
939+
try {
940+
major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value);
941+
minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value);
942+
build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value);
943+
revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value);
944+
} catch { }
945+
946+
return (new Version(major, minor, build, revision));
947+
}
948+
}
949+
950+
public string
951+
ImageDisplayName {
952+
get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; }
953+
}
954+
955+
public string
956+
ImageDisplayDescription {
957+
get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; }
958+
}
959+
}
960+
961+
///<summary>
962+
///Describes the file that is being processed for the ProcessFileEvent.
963+
///</summary>
964+
public class
965+
DefaultImageEventArgs : EventArgs {
966+
///<summary>
967+
///Default constructor.
968+
///</summary>
969+
public
970+
DefaultImageEventArgs(
971+
IntPtr wideParameter,
972+
IntPtr leftParameter,
973+
IntPtr userData) {
974+
975+
WideParameter = wideParameter;
976+
LeftParameter = leftParameter;
977+
UserData = userData;
978+
}
979+
980+
///<summary>
981+
///wParam
982+
///</summary>
983+
public IntPtr WideParameter {
984+
get;
985+
private set;
986+
}
987+
988+
///<summary>
989+
///lParam
990+
///</summary>
991+
public IntPtr LeftParameter {
992+
get;
993+
private set;
994+
}
995+
996+
///<summary>
997+
///UserData
998+
///</summary>
999+
public IntPtr UserData {
1000+
get;
1001+
private set;
1002+
}
1003+
}
1004+
1005+
///<summary>
1006+
///Describes the file that is being processed for the ProcessFileEvent.
1007+
///</summary>
1008+
public class
1009+
ProcessFileEventArgs : EventArgs {
1010+
///<summary>
1011+
///Default constructor.
1012+
///</summary>
1013+
///<param name="file">Fully qualified path and file name. For example: c:\file.sys.</param>
1014+
///<param name="skipFileFlag">Default is false - skip file and continue.
1015+
///Set to true to abort the entire image capture.</param>
1016+
public
1017+
ProcessFileEventArgs(
1018+
string file,
1019+
IntPtr skipFileFlag) {
1020+
1021+
m_FilePath = file;
1022+
m_SkipFileFlag = skipFileFlag;
1023+
}
1024+
1025+
///<summary>
1026+
///Skip file from being imaged.
1027+
///</summary>
1028+
public void
1029+
SkipFile() {
1030+
byte[] byteBuffer = {
1031+
0
1032+
};
1033+
int byteBufferSize = byteBuffer.Length;
1034+
Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize);
1035+
}
1036+
1037+
///<summary>
1038+
///Fully qualified path and file name.
1039+
///</summary>
1040+
public string
1041+
FilePath {
1042+
get {
1043+
string stringToReturn = "";
1044+
if (m_FilePath != null) {
1045+
stringToReturn = m_FilePath;
1046+
}
1047+
return stringToReturn;
1048+
}
1049+
}
1050+
1051+
///<summary>
1052+
///Flag to indicate if the entire image capture should be aborted.
1053+
///Default is false - skip file and continue. Setting to true will
1054+
///abort the entire image capture.
1055+
///</summary>
1056+
public bool Abort {
1057+
set { m_Abort = value; }
1058+
get { return m_Abort; }
1059+
}
1060+
1061+
private string m_FilePath;
1062+
private bool m_Abort;
1063+
private IntPtr m_SkipFileFlag;
1064+
}
1065+
1066+
#endregion WIM Interop
1067+
}
1068+
"@
1069+
1070+
Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Xml","System.Linq","System.Xml.Linq"
1071+
1072+
function Get-WimFileImagesInfo
1073+
{
1074+
[CmdletBinding()]
1075+
param
1076+
(
1077+
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
1078+
[string]$WimFilePath = "D:\Sources\install.wim"
1079+
)
1080+
PROCESS
1081+
{
1082+
$w = new-object WIMInterop.WimFile -ArgumentList $WimFilePath
1083+
return $w.Images
1084+
}
1085+
}

0 commit comments

Comments
 (0)
Please sign in to comment.