File size: 357,578 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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using System.Diagnostics;

using Microsoft.PowerShell.Cmdletization;

using Dbg = System.Management.Automation.Diagnostics;

//
// Now define the set of commands for manipulating modules.
//

namespace Microsoft.PowerShell.Commands
{
    #region ModuleCmdletBase class

    /// <summary>
    /// This is the base class for some of the module cmdlets. It contains a number of
    /// utility functions for these classes.
    /// </summary>
    public class ModuleCmdletBase : PSCmdlet
    {
        /// <summary>
        /// Flags defining how a module manifest should be processed.
        /// </summary>
        [Flags]
        internal enum ManifestProcessingFlags
        {
            /// <summary>
            /// Write errors (otherwise no non-terminating-errors are written)
            /// </summary>
            WriteErrors = 0x1,

            /// <summary>
            /// Return null on first error (otherwise we try to process other elements of the manifest)
            /// </summary>
            NullOnFirstError = 0x2,

            /// <summary>
            /// Load elements of the manifest (i.e. types/format.ps1xml, nested modules, etc.)
            /// </summary>
            LoadElements = 0x4,

            /// <summary>
            /// Write warnings.
            /// </summary>
            WriteWarnings = 0x8,

            /// <summary>
            /// Force full module manifest processing.
            /// </summary>
            Force = 0x10,

            /// <summary>
            /// Ignore PowerShellHostName and PowerShellHostVersion while
            /// processing Manifest fields.
            /// This is used for GetModule where loading elements does not happen.
            /// </summary>
            IgnoreHostNameAndHostVersion = 0x20,
        }

        /// <summary>
        /// Options set during module import.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
        protected internal struct ImportModuleOptions
        {
            /// <summary>
            /// Holds the value of NoClobber parameter in Import-Module
            /// This is used when importing modules.
            /// </summary>
            internal bool NoClobber;

            /// <summary>
            /// If Scope parameter is Local, this is true.
            /// </summary>
            internal bool Local;

            /// <summary>
            /// Lets nested module import to export all of its functions, regardless of language boundaries.
            /// This will be allowed when the manifest explicitly exports functions which will limit all visible module functions.
            /// </summary>
            internal bool AllowNestedModuleFunctionsToExport;

            /// <summary>
            /// Flag that controls Export-PSSession -AllowClobber parameter in generating proxy modules from remote sessions.
            /// Historically -AllowClobber in these scenarios was set as True.
            /// </summary>
            internal bool NoClobberExportPSSession;

            /// <summary>
            /// Flag that controls skipping the System32 module path when searching a module in module paths. It also suppresses
            /// writing out errors when specified.
            /// </summary>
            internal bool SkipSystem32ModulesAndSuppressError;
        }

        /// <summary>
        /// This parameter specified a prefix used to modify names of imported commands.
        /// </summary>
        internal string BasePrefix { get; set; } = string.Empty;

        /// <summary>
        /// Flags -force operations.
        /// </summary>
        internal bool BaseForce { get; set; }

        /// <summary>
        /// Flags -global operations (affects what gets returned by TargetSessionState)
        /// </summary>
        internal bool BaseGlobal { get; set; }

        /// <summary>
        /// If set, CompatiblePSEditions checking will be disabled for modules on the System32 path.
        /// </summary>
        internal bool BaseSkipEditionCheck { get; set; }

        internal SessionState TargetSessionState
        {
            get
            {
                if (BaseGlobal)
                {
                    return this.Context.TopLevelSessionState.PublicSessionState;
                }
                else
                {
                    return this.Context.SessionState;
                }
            }
        }

        /// <summary>
        /// Flags -passthru operations.
        /// </summary>
        internal bool BasePassThru { get; set; }

        /// <summary>
        /// Flags -passthru operations.
        /// </summary>
        internal bool BaseAsCustomObject { get; set; }

        /// <summary>
        /// Wildcard patterns for the function to import.
        /// </summary>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
        internal List<WildcardPattern> BaseFunctionPatterns { get; set; }

        /// <summary>
        /// Wildcard patterns for the cmdlets to import.
        /// </summary>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
        internal List<WildcardPattern> BaseCmdletPatterns { get; set; }

        /// <summary>
        /// Wildcard patterns for the variables to import.
        /// </summary>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
        internal List<WildcardPattern> BaseVariablePatterns { get; set; }

        /// <summary>
        /// Wildcard patterns for the aliases to import.
        /// </summary>
        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
        internal List<WildcardPattern> BaseAliasPatterns { get; set; }

        /// <summary>
        /// The minimum version number to check the module against. Used the underlying property
        /// for derived cmdlet parameters.
        /// </summary>
        internal Version BaseMinimumVersion { get; set; }

        /// <summary>
        /// The maximum version number to check the module against. Used the underlying property
        /// for derived cmdlet parameters.
        /// </summary>
        internal Version BaseMaximumVersion { get; set; }

        /// <summary>
        /// The version number to check the module against. Used the underlying property
        /// for derived cmdlet parameters.
        /// </summary>
        internal Version BaseRequiredVersion { get; set; }

        /// <summary>
        /// The Guid to check the module against. Used the underlying property
        /// for derived cmdlet parameters.
        /// </summary>
        internal Guid? BaseGuid { get; set; }

        /// <summary>
        /// The arguments to pass to the scriptblock used to create the module.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
        protected object[] BaseArgumentList { get; set; }

        /// <summary>
        /// Disable warnings on cmdlet and function names that have non-standard verbs
        /// or non-standard characters in the noun.
        /// </summary>
        protected bool BaseDisableNameChecking { get; set; } = true;

        /// <summary>
        /// Add module path to app domain level module path cache if name is not rooted.
        /// </summary>
        protected bool AddToAppDomainLevelCache { get; set; } = false;

        /// <summary>
        /// A handy match all pattern used to initialize various import and export lists...
        /// </summary>
        internal List<WildcardPattern> MatchAll
        {
            get
            {
                if (_matchAll == null)
                {
                    _matchAll = new List<WildcardPattern>();
                    _matchAll.Add(WildcardPattern.Get("*", WildcardOptions.IgnoreCase));
                }

                return _matchAll;
            }
        }

        private List<WildcardPattern> _matchAll;

        // The list of commands permitted in a module manifest
        internal static readonly string[] PermittedCmdlets = new string[] {
            "Import-LocalizedData", "ConvertFrom-StringData", "Write-Host", "Out-Host", "Join-Path" };

        internal static readonly string[] ModuleManifestMembers = new string[] {
            "ModuleToProcess",
            "NestedModules",
            "GUID",
            "Author",
            "CompanyName",
            "Copyright",
            "ModuleVersion",
            "Description",
            "PowerShellVersion",
            "PowerShellHostName",
            "PowerShellHostVersion",
            "CLRVersion",
            "DotNetFrameworkVersion",
            "ProcessorArchitecture",
            "RequiredModules",
            "TypesToProcess",
            "FormatsToProcess",
            "ScriptsToProcess",
            "PrivateData",
            "RequiredAssemblies",
            "ModuleList",
            "FileList",
            "FunctionsToExport",
            "VariablesToExport",
            "AliasesToExport",
            "CmdletsToExport",
            "DscResourcesToExport",
            "CompatiblePSEditions",
            "HelpInfoURI",
            "RootModule",
            "DefaultCommandPrefix"
        };

        private static readonly string[] s_moduleVersionMembers = new string[] {
            "ModuleName",
            "GUID",
            "ModuleVersion"
        };

        /// <summary>
        /// List of PowerShell built-in modules that are shipped with PowerShell only, not on PS Gallery.
        /// </summary>
        protected static readonly HashSet<string> BuiltInModules = new(StringComparer.OrdinalIgnoreCase)
        {
            "CimCmdlets",
            "Microsoft.PowerShell.Diagnostics",
            "Microsoft.PowerShell.Host",
            "Microsoft.PowerShell.Management",
            "Microsoft.PowerShell.Security",
            "Microsoft.PowerShell.Utility",
            "Microsoft.WSMan.Management",
            "PSDiagnostics",
        };

        /// <summary>
        /// When module manifests lack a CompatiblePSEditions field,
        /// they will be treated as if they have this value.
        /// The PSModuleInfo will still reflect the lack of value.
        /// </summary>
        internal static IReadOnlyList<string> DefaultCompatiblePSEditions { get; } = new string[]
        {
            "Desktop"
        };

        /// <summary>
        /// A counter for modules that are loaded using WindowsPS compat session.
        /// </summary>
        internal static int s_WindowsPowerShellCompatUsageCounter = 0;

        /// <summary>
        /// Session name for WindowsPS compat remoting session.
        /// </summary>
        internal const string WindowsPowerShellCompatRemotingSessionName = "WinPSCompatSession";

        /// <summary>
        /// Synchronization object for creation/cleanup of WindowsPS compat remoting session.
        /// </summary>
        internal static readonly object s_WindowsPowerShellCompatSyncObject = new object();

        private readonly Dictionary<string, PSModuleInfo> _currentlyProcessingModules = new Dictionary<string, PSModuleInfo>();

        internal bool LoadUsingModulePath(
            IEnumerable<string> modulePath,
            string name,
            SessionState ss,
            ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags,
            out PSModuleInfo module)
        {
            return LoadUsingModulePath(parentModule: null, modulePath, name, ss, options, manifestProcessingFlags, out module);
        }

        internal bool LoadUsingModulePath(
            PSModuleInfo parentModule,
            IEnumerable<string> modulePath,
            string name,
            SessionState ss,
            ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags,
            out PSModuleInfo module)
        {
            string extension = Path.GetExtension(name);
            string fileBaseName;
            module = null;
            if (string.IsNullOrEmpty(extension) || !ModuleIntrinsics.IsPowerShellModuleExtension(extension))
            {
                fileBaseName = name;
                extension = null;
            }
            else
            {
                fileBaseName = name.Substring(0, name.Length - extension.Length);
            }

            // Now search using the module path...
            bool found = false;
            foreach (string path in modulePath)
            {
                if (options.SkipSystem32ModulesAndSuppressError && ModuleUtils.IsOnSystem32ModulePath(path))
                {
                    continue;
                }
#if UNIX
                foreach (string folder in Directory.EnumerateDirectories(path))
                {
                    string moduleName = Path.GetFileName(folder);
                    if (string.Equals(moduleName, fileBaseName, StringComparison.OrdinalIgnoreCase))
                    {
                        fileBaseName = moduleName;
#endif
                string qualifiedPath = Path.Combine(path, fileBaseName);
                module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found);
                if (!found)
                {
                    if (name.AsSpan().IndexOfAny('\\', '/') == -1)
                    {
                        qualifiedPath = Path.Combine(qualifiedPath, fileBaseName);
                    }
                    else if (Directory.Exists(qualifiedPath))
                    {
                        // if it points to a directory, add the basename back onto the path...
                        qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName));
                    }

                    module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found);
                }

                if (found)
                {
                    break;
                }
#if UNIX
                    }
                }

                if (found)
                {
                    break;
                }
#endif
            }

            if (found)
            {
                // Cache the module's exported commands after importing it, or if the -Refresh flag is used on "Get-Module -List"
                if ((module != null) && !module.HadErrorsLoading)
                {
                    AnalysisCache.CacheModuleExports(module, Context);
                }
            }

            return found;
        }

        /// <summary>
        /// Loads the latest valid version if moduleBase is a multi-versioned module directory.
        /// </summary>
        /// <param name="moduleBase">Module directory path.</param>
        /// <param name="manifestProcessingFlags">The flag that indicate manifest processing option.</param>
        /// <param name="importModuleOptions">The set of options that are used while importing a module.</param>
        /// <param name="found">True if a module was found.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadUsingMultiVersionModuleBase(string moduleBase, ManifestProcessingFlags manifestProcessingFlags, ImportModuleOptions importModuleOptions, out bool found)
        {
            PSModuleInfo foundModule = null;
            found = false;

            foreach (var version in ModuleUtils.GetModuleVersionSubfolders(moduleBase))
            {
                // Skip the version folder if it is not equal to the required version or does not satisfy the minimum/maximum version criteria
                if (!ModuleIntrinsics.IsVersionMatchingConstraints(version, BaseRequiredVersion, BaseMinimumVersion, BaseMaximumVersion))
                {
                    continue;
                }

                var qualifiedPathWithVersion = Path.Combine(moduleBase,
                                                            Path.Combine(version.ToString(), Path.GetFileName(moduleBase)));
                string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension;
                var isValidModuleVersion = false;
                if (File.Exists(manifestPath))
                {
                    isValidModuleVersion = version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath));

                    if (isValidModuleVersion)
                    {
                        foundModule = LoadUsingExtensions(null, moduleBase, qualifiedPathWithVersion,
                                                            StringLiterals.PowerShellDataFileExtension,
                                                            null,
                                                            this.BasePrefix, /*SessionState*/ null,
                                                            importModuleOptions,
                                                            manifestProcessingFlags,
                                                            out found);
                        if (found)
                        {
                            break;
                        }
                    }
                }

                if (!isValidModuleVersion)
                {
                    WriteVerbose(string.Format(CultureInfo.InvariantCulture, Modules.SkippingInvalidModuleVersionFolder,
                                                version.ToString(), moduleBase));
                }
            }

            return foundModule;
        }

        /// <summary>
        /// Load and execute the manifest psd1 file or a localized manifest psd1 file.
        /// </summary>
        private Hashtable LoadModuleManifestData(
            ExternalScriptInfo scriptInfo,
            string[] validMembers,
            ManifestProcessingFlags manifestProcessingFlags,
            ref bool containedErrors)
        {
            try
            {
                return LoadModuleManifestData(scriptInfo.Path, scriptInfo.ScriptBlock, validMembers, manifestProcessingFlags, ref containedErrors);
            }
            catch (RuntimeException pe)
            {
                if ((manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0)
                {
                    string message = StringUtil.Format(Modules.InvalidModuleManifest, scriptInfo.Path, pe.Message);
                    MissingMemberException mm = new MissingMemberException(message);
                    ErrorRecord er = new ErrorRecord(mm, "Modules_InvalidManifest",
                        ErrorCategory.ResourceUnavailable, scriptInfo.Path);
                    WriteError(er);
                }

                containedErrors = true;
                return null;
            }
        }

        /// <summary>
        /// Extra variables that are allowed to be referenced in module manifest file.
        /// </summary>
        private static readonly string[] s_extraAllowedVariables = new string[] { SpecialVariables.PSScriptRoot, SpecialVariables.PSEdition, SpecialVariables.EnabledExperimentalFeatures };

        /// <summary>
        /// Load and execute the manifest psd1 file or a localized manifest psd1 file.
        /// </summary>
        internal Hashtable LoadModuleManifestData(
            string moduleManifestPath,
            ScriptBlock scriptBlock,
            string[] validMembers,
            ManifestProcessingFlags manifestProcessingFlags,
            ref bool containedErrors)
        {
            string message;

            var importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0;
            var writingErrors = (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0;

            // Load the data file(s) to get the module info...
            try
            {
                scriptBlock.CheckRestrictedLanguage(PermittedCmdlets, s_extraAllowedVariables, true);
            }
            catch (RuntimeException pe)
            {
                if (writingErrors)
                {
                    message = StringUtil.Format(Modules.InvalidModuleManifest, moduleManifestPath, pe.Message);
                    MissingMemberException mm = new MissingMemberException(message);
                    ErrorRecord er = new ErrorRecord(mm, "Modules_InvalidManifest",
                        ErrorCategory.ResourceUnavailable, moduleManifestPath);
                    WriteError(er);
                }

                containedErrors = true;
                return null;
            }

            object result;
            object oldPSScriptRoot = Context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
            object oldPSCommandPath = Context.GetVariableValue(SpecialVariables.PSCommandPathVarPath);
            ArrayList errors = (ArrayList)Context.GetVariableValue(SpecialVariables.ErrorVarPath);
            int oldErrorCount = errors.Count;

            try
            {
                // Set the PSScriptRoot variable in the modules session state
                Context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(moduleManifestPath));
                Context.SetVariable(SpecialVariables.PSCommandPathVarPath, moduleManifestPath);

                result = PSObject.Base(scriptBlock.InvokeReturnAsIs());
            }
            finally
            {
                Context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPSScriptRoot);
                Context.SetVariable(SpecialVariables.PSCommandPathVarPath, oldPSCommandPath);

                // We do not want any exceptions to show up in user's session state. So, we are removing errors in the finally block.
                // If we're not loading the manifest (and are examining it), prevent errors from showing up in
                // the user's session.
                if (!importingModule)
                {
                    while (errors.Count > oldErrorCount) { errors.RemoveAt(0); }
                }
            }

            Hashtable data = result as Hashtable;
            if (data == null)
            {
                if (writingErrors)
                {
                    message = StringUtil.Format(Modules.EmptyModuleManifest, moduleManifestPath);
                    ArgumentException ae = new ArgumentException(message);
                    ErrorRecord er = new ErrorRecord(ae, "Modules_InvalidManifest",
                        ErrorCategory.ResourceUnavailable, moduleManifestPath);
                    WriteError(er);
                }

                containedErrors = true;
                return null;
            }

            // MSFT:873446 Create a case insensitive comparer based hashtable to help
            // with case-insensitive comparison of keys.
            data = new Hashtable(data, StringComparer.OrdinalIgnoreCase);
            if (validMembers != null && !ValidateManifestHash(data, validMembers, moduleManifestPath, manifestProcessingFlags))
            {
                containedErrors = true;
                if ((manifestProcessingFlags & ManifestProcessingFlags.NullOnFirstError) != 0)
                    return null;
            }

            return data;
        }

        /// <summary>
        /// Verify the hash contains only valid members.  Write an error and return false if it is not valid.
        /// </summary>
        private bool ValidateManifestHash(
            Hashtable data,
            string[] validMembers,
            string moduleManifestPath,
            ManifestProcessingFlags manifestProcessingFlags)
        {
            bool result = true;

            StringBuilder badKeys = new StringBuilder();
            foreach (string s in data.Keys)
            {
                bool found = false;

                foreach (string member in validMembers)
                {
                    if (s.Equals(member, StringComparison.OrdinalIgnoreCase))
                    {
                        found = true;
                    }
                }

                if (!found)
                {
                    if (badKeys.Length > 0)
                        badKeys.Append(", ");
                    badKeys.Append('\'');
                    badKeys.Append(s);
                    badKeys.Append('\'');
                }
            }

            if (badKeys.Length > 0)
            {
                result = false;
                string message = null;

                if ((manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0)
                {
                    // Check for PowerShell Version before checking other keys
                    // If a PowerShellVersion exists and does not match the requirements, then the error is InsufficientPowerShellVersion
                    // Else, the error is InvalidManifestMember
                    Version powerShellVersion;
                    Version currentPowerShellVersion = PSVersionInfo.PSVersion;
                    if (GetScalarFromData<Version>(data, moduleManifestPath, "PowerShellVersion", manifestProcessingFlags, out powerShellVersion) &&
                        currentPowerShellVersion < powerShellVersion)
                    {
                        message = StringUtil.Format(Modules.ModuleManifestInsufficientPowerShellVersion,
                                                    currentPowerShellVersion,
                                                    moduleManifestPath, powerShellVersion);
                        InvalidOperationException ioe = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(ioe, "Modules_InsufficientPowerShellVersion",
                                                         ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        WriteError(er);
                    }
                    else
                    {
                        StringBuilder validMembersString = new StringBuilder("'");
                        validMembersString.Append(validMembers[0]);
                        for (int i = 1; i < validMembers.Length; i++)
                        {
                            validMembersString.Append("', '");
                            validMembersString.Append(validMembers[i]);
                        }

                        validMembersString.Append('\'');
                        message = StringUtil.Format(Modules.InvalidModuleManifestMember, moduleManifestPath, validMembersString, badKeys);
                        InvalidOperationException ioe = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidManifestMember",
                            ErrorCategory.InvalidData, moduleManifestPath);
                        WriteError(er);
                    }
                }
            }

            return result;
        }

        private PSModuleInfo LoadModuleNamedInManifest(
            PSModuleInfo parentModule,
            ModuleSpecification moduleSpecification,
            string moduleBase,
            bool searchModulePath,
            string prefix,
            SessionState ss,
            ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags,
            object privateData,
            out bool found,
            string shortModuleName,
            PSLanguageMode? manifestLanguageMode)
        {
            PSModuleInfo module = null;
            PSModuleInfo tempModuleInfoFromVerification = null;
            found = false;
            bool moduleFileFound = false;
            bool wasRooted = false;
            Version savedBaseMinimumVersion = BaseMinimumVersion;
            Version savedBaseMaximumVersion = BaseMaximumVersion;
            Version savedBaseRequiredVersion = BaseRequiredVersion;
            Guid? savedBaseGuid = BaseGuid;

            var importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements);
            string extension = Path.GetExtension(moduleSpecification.Name);

            // First check for fully-qualified paths - either absolute or relative
            string rootedPath = ResolveRootedFilePath(moduleSpecification.Name, this.Context);
            if (string.IsNullOrEmpty(rootedPath))
            {
                // Use the name of the parent module if it's specified, otherwise, use the current module name.
                //  - If the current module is a nested module, then the parent module will be specified.
                //  - If the current module is a root module, then the parent module will not be specified.
                string moduleName = parentModule?.Name ?? ModuleIntrinsics.GetModuleName(moduleSpecification.Name);
                rootedPath = FixFileName(moduleName, moduleBase, moduleSpecification.Name, extension: null, canLoadAssembly: importingModule);
            }
            else
            {
                wasRooted = true;
            }

            try
            {
                this.Context.Modules.IncrementModuleNestingDepth(this, rootedPath);
                BaseMinimumVersion = null;
                BaseMaximumVersion = null;
                BaseRequiredVersion = null;
                BaseGuid = null;

                // See if it's one of the powershell module extensions...
                if (!ModuleIntrinsics.IsPowerShellModuleExtension(extension))
                {
                    // If the file exits, and it does not have a powershell module extension, we know for sure that the file is not a valid module
                    if (File.Exists(rootedPath))
                    {
                        PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException(
                                                                Modules.ManifestMemberNotValid,
                                                                moduleSpecification.Name,
                                                                "NestedModules",
                                                                parentModule?.Path,
                                                                StringUtil.Format(Modules.InvalidModuleExtension, extension, moduleSpecification.Name),
                                                                                    ModuleIntrinsics.GetModuleName(parentModule?.Path));
                        invalidOperation.SetErrorId("Modules_InvalidModuleExtension");
                        throw invalidOperation;
                    }

                    extension = null;
                }

                // Now load the module from the module directory first...
                if (extension == null)
                {
                    // No extension so we'll have to search using the extensions
                    //
                    if (VerifyIfNestedModuleIsAvailable(moduleSpecification, rootedPath, /*extension*/null, out tempModuleInfoFromVerification))
                    {
                        module = LoadUsingExtensions(
                            parentModule,
                            moduleSpecification.Name,
                            fileBaseName: rootedPath,
                            extension: null,
                            moduleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
                            prefix,
                            ss,
                            options,
                            manifestProcessingFlags,
                            out found,
                            out moduleFileFound);
                    }

                    // Win8: 262157 - Import-Module is giving errors while loading Nested Modules. (This is a V2 bug)
                    // NestedModules = 'test2' ---> test2 is a directory under current module directory (e.g - Test1)
                    // We also need to look for Test1\Test2\Test2.(psd1/psm1/dll)
                    // With the call above, we are only looking at Test1\Test2.(psd1/psm1/dll)
                    if (!found && !moduleFileFound)
                    {
                        string newRootedPath = Path.Combine(rootedPath, moduleSpecification.Name);
                        string newModuleBase = Path.Combine(moduleBase, moduleSpecification.Name);
                        if (VerifyIfNestedModuleIsAvailable(moduleSpecification, newRootedPath, /*extension*/null, out tempModuleInfoFromVerification))
                        {
                            module = LoadUsingExtensions(
                                parentModule,
                                moduleSpecification.Name,
                                fileBaseName: newRootedPath,
                                extension: null,
                                newModuleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
                                prefix,
                                ss,
                                options,
                                manifestProcessingFlags,
                                out found,
                                out moduleFileFound);
                        }
                    }
                }
                else
                {
                    // Ok - we have a complete file name so load that...
                    if (VerifyIfNestedModuleIsAvailable(moduleSpecification, rootedPath, extension, out tempModuleInfoFromVerification))
                    {
                        module = LoadModule(
                            parentModule,
                            rootedPath, // fileName
                            moduleBase, // not using base from tempModuleInfoFromVerification as we have a complete file name
                            prefix,
                            ss,
                            privateData,
                            ref options,
                            manifestProcessingFlags,
                            out found,
                            out moduleFileFound);
                    }

                    // Win8: 262157 - Import-Module is giving errors while loading Nested Modules. (This is a V2 bug)
                    // Only look for the file if the file was not found with the previous search
                    if (!found && !moduleFileFound)
                    {
                        string newRootedPath = Path.Combine(rootedPath, moduleSpecification.Name);
                        string newModuleBase = Path.Combine(moduleBase, moduleSpecification.Name);
                        if (VerifyIfNestedModuleIsAvailable(moduleSpecification, newRootedPath, extension, out tempModuleInfoFromVerification))
                        {
                            module = LoadModule(
                                parentModule,
                                newRootedPath, // fileName
                                newModuleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
                                prefix,
                                ss,
                                privateData,
                                ref options,
                                manifestProcessingFlags,
                                out found,
                                out moduleFileFound);
                        }
                    }
                }

                // The rooted files wasn't found, so don't search anymore...
                if (!found && wasRooted)
                    return null;

                if (searchModulePath && !found && !moduleFileFound)
                {
                    if (VerifyIfNestedModuleIsAvailable(moduleSpecification, null, null, out tempModuleInfoFromVerification))
                    {
                        IEnumerable<string> modulePath = null;
                        if (tempModuleInfoFromVerification != null)
                        {
                            var subdirName = Path.GetFileName(tempModuleInfoFromVerification.ModuleBase);
                            Version version;
                            if (Version.TryParse(subdirName, out version))
                            {
                                var moduleBaseWithoutVersion = Path.GetDirectoryName(tempModuleInfoFromVerification.ModuleBase);

                                modulePath = new string[]
                                {
                                    Path.GetDirectoryName(moduleBaseWithoutVersion),
                                    moduleBaseWithoutVersion
                                };
                            }
                            else
                            {
                                modulePath = new string[]
                                {
                                    Path.GetDirectoryName(tempModuleInfoFromVerification.ModuleBase),
                                    tempModuleInfoFromVerification.ModuleBase
                                };
                            }
                        }
                        else
                        {
                            modulePath = ModuleIntrinsics.GetModulePath(false, this.Context);
                        }

                        // Otherwise try the module path
                        found = LoadUsingModulePath(parentModule, modulePath,
                                                    moduleSpecification.Name, ss,
                                                    options, manifestProcessingFlags, out module);
                    }
                }

                if (manifestLanguageMode.HasValue && found && (module != null) && module.LanguageMode.HasValue)
                {
                    // Check for script module language mode consistency.  All loaded script modules must have the same language mode as the manifest.
                    // If not then this indicates a malformed module and a possible exploit to make trusted private functions visible in a
                    // Constrained Language session.
                    if (module.LanguageMode != manifestLanguageMode)
                    {
                        if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)
                        {
                            var languageModeError = PSTraceSource.NewInvalidOperationException(
                                Modules.MismatchedLanguageModes,
                                module.Name, manifestLanguageMode, module.LanguageMode);
                            languageModeError.SetErrorId("Modules_MismatchedLanguageModes");
                            throw languageModeError;
                        }

                        SystemPolicy.LogWDACAuditMessage(
                            context: Context,
                            title: Modules.WDACMismatchedLanguageModesTitle,
                            message: Modules.WDACMismatchedLanguageModesMessage,
                            fqid: "ModulesMismatchedLanguageModes",
                            dropIntoDebugger: true);
                    }
                }

                // At this point, we haven't found an actual module, so try loading it as a
                // PSSnapIn and then finally as an assembly in the GAC...
                if (!found && (moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.RequiredVersion == null) && (moduleSpecification.MaximumVersion == null))
                {
                    // If we are in module analysis and the parent module declares non-wildcarded ExportedCmdlets, then we don't need to
                    // actually process the binary module.
                    bool shouldLoadModule = true;

                    if ((parentModule != null) && !importingModule)
                    {
                        if ((parentModule.ExportedCmdlets != null) && (parentModule.ExportedCmdlets.Count > 0))
                        {
                            shouldLoadModule = false;

                            foreach (string exportedCmdlet in parentModule.ExportedCmdlets.Keys)
                            {
                                if (WildcardPattern.ContainsWildcardCharacters(exportedCmdlet))
                                {
                                    shouldLoadModule = true;
                                    break;
                                }
                            }

                            found = true;
                        }
                    }

                    if (shouldLoadModule)
                    {
                        try
                        {
                            // At this point, we are already exhaust all possible ways to load the nested module. The last option is to load it as a binary module/snapin.
                            module = LoadBinaryModule(
                                parentModule,
                                moduleSpecification.Name,
                                fileName: null,
                                assemblyToLoad: null,
                                moduleBase,
                                ss,
                                options,
                                manifestProcessingFlags,
                                prefix,
                                out found,
                                shortModuleName,
                                disableFormatUpdates: false);
                        }
                        catch (FileNotFoundException)
                        {
                            // Loading the nested module as a pssnapin or assembly is our last attempt to resolve the nested module.
                            // If we catch 'FileNotFoundException', it simply means that our last attempt failed because we couldn't find such a pssnapin or assembly.
                            // In this case, we can safely ignore this exception and throw a 'Modules_ModuleFileNotFound' error.
                        }

                        if ((module != null) && importingModule)
                        {
                            AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
                        }
                    }
                }

                return module;
            }
            finally
            {
                BaseMinimumVersion = savedBaseMinimumVersion;
                BaseMaximumVersion = savedBaseMaximumVersion;
                BaseRequiredVersion = savedBaseRequiredVersion;
                BaseGuid = savedBaseGuid;
                this.Context.Modules.DecrementModuleNestingCount();
            }
        }

        internal List<PSModuleInfo> GetModule(string[] names, bool all, bool refresh)
        {
            List<PSModuleInfo> modulesToReturn = new List<PSModuleInfo>();

            // Two lists - one to hold Module Paths and one to hold Module Names
            // For Module Paths, we don't do any path resolution
            List<string> modulePaths = new List<string>();
            List<string> moduleNames = new List<string>();

            if (names != null)
            {
                foreach (var n in names)
                {
                    if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator))
                    {
                        modulePaths.Add(n);
                    }
                    else
                    {
                        moduleNames.Add(n);
                    }
                }

                modulesToReturn.AddRange(GetModuleForRootedPaths(modulePaths, all, refresh));
            }

            // If no names were passed to this function, then this API will return list of all available modules
            if (names == null || moduleNames.Count > 0)
            {
                modulesToReturn.AddRange(GetModuleForNames(moduleNames, all, refresh));
            }

            return modulesToReturn;
        }

        private IEnumerable<PSModuleInfo> GetModuleForRootedPaths(List<string> modulePaths, bool all, bool refresh)
        {
            // This is to filter out duplicate modules
            var modules = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (string mp in modulePaths)
            {
                bool containsWildCards = false;

                string modulePath = mp.TrimEnd('\\');

                // If the given path contains wildcards, we won't throw error if no match module path is found.
                if (WildcardPattern.ContainsWildcardCharacters(modulePath))
                {
                    containsWildCards = true;
                }

                // Now we resolve the possible paths in case it is relative path/path contains wildcards
                var modulePathCollection = GetResolvedPathCollection(modulePath, this.Context);

                if (modulePathCollection != null)
                {
                    foreach (string resolvedModulePath in modulePathCollection)
                    {
                        string moduleName = Path.GetFileName(resolvedModulePath);

                        // If the given path is a valid module file, we will load the specific file
                        if (!Directory.Exists(resolvedModulePath) && ModuleIntrinsics.IsPowerShellModuleExtension(Path.GetExtension(moduleName)))
                        {
                            PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh);
                            if (module != null)
                            {
                                if (modules.Add(resolvedModulePath))
                                {
                                    yield return module;
                                }
                            }
                        }
                        else
                        {
                            // Given path is a directory, we first check if it is end with module version.
                            Version version;
                            if (Version.TryParse(moduleName, out version))
                            {
                                moduleName = Path.GetFileName(Directory.GetParent(resolvedModulePath).Name);
                            }

                            var availableModuleFiles = all
                                ? ModuleUtils.GetAllAvailableModuleFiles(resolvedModulePath)
                                : ModuleUtils.GetModuleFilesFromAbsolutePath(resolvedModulePath);

                            bool foundModule = false;
                            foreach (string file in availableModuleFiles)
                            {
                                PSModuleInfo module = CreateModuleInfoForGetModule(file, refresh);
                                if (module != null)
                                {
                                    if (string.Equals(moduleName, module.Name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        foundModule = true;
                                        // We need to list all versions of the module.
                                        string subModulePath = Path.GetDirectoryName(file);
                                        if (modules.Add(subModulePath))
                                        {
                                            yield return module;
                                        }
                                    }
                                }
                            }

                            // Write error only if Name has no wild cards
                            if (!foundModule && !containsWildCards)
                            {
                                WriteError(CreateModuleNotFoundError(resolvedModulePath));
                            }
                        }
                    }
                }
                else
                {
                    if (!containsWildCards)
                    {
                        WriteError(CreateModuleNotFoundError(modulePath));
                    }
                }
            }
        }

        private static ErrorRecord CreateModuleNotFoundError(string modulePath)
        {
            string errorMessage = StringUtil.Format(Modules.ModuleNotFoundForGetModule, modulePath);
            FileNotFoundException fnf = new FileNotFoundException(errorMessage);
            ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFoundForGetModule", ErrorCategory.ResourceUnavailable, modulePath);
            return er;
        }

        private IEnumerable<PSModuleInfo> GetModuleForNames(List<string> names, bool all, bool refresh)
        {
            IEnumerable<PSModuleInfo> allModules = null;
            HashSet<string> modulePathSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (string path in ModuleIntrinsics.GetModulePath(false, Context))
            {
                string uniquePath = path.TrimEnd(Utils.Separators.Directory);

                // Ignore repeated module path.
                if (!modulePathSet.Add(uniquePath))
                {
                    continue;
                }

                try
                {
                    IEnumerable<PSModuleInfo> modulesFound = GetModulesFromOneModulePath(
                        names, uniquePath, all, refresh).OrderBy(static m => m.Name);
                    allModules = allModules == null ? modulesFound : allModules.Concat(modulesFound);
                }
                catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
                {
                    // ignore directories that can't be accessed
                    continue;
                }
            }

            // Make sure we always return a non-null collection.
            return allModules ?? Array.Empty<PSModuleInfo>();
        }

        /// <summary>
        /// Get modules based on the given names and module files.
        /// </summary>
        private IEnumerable<PSModuleInfo> GetModulesFromOneModulePath(List<string> names, string modulePath, bool all, bool refresh)
        {
            const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            IEnumerable<WildcardPattern> namePatterns = null;
            if (names != null && names.Count > 0)
            {
                namePatterns = SessionStateUtilities.CreateWildcardsFromStrings(names, options);
            }

            IEnumerable<string> moduleFiles = all
                ? ModuleUtils.GetAllAvailableModuleFiles(modulePath)
                : ModuleUtils.GetDefaultAvailableModuleFiles(modulePath);

            foreach (string file in moduleFiles)
            {
                if (namePatterns == null ||
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        Path.GetFileNameWithoutExtension(file), namePatterns, defaultValue: true))
                {
                    PSModuleInfo module = CreateModuleInfoForGetModule(file, refresh);
                    if (module == null) { continue; }

                    if (all || !ModuleUtils.IsModuleInVersionSubdirectory(file, out Version directoryVersion) || directoryVersion == module.Version)
                    {
                        yield return module;
                    }
                }
            }

            ClearAnalysisCaches();
        }

        /// <summary>
        /// Get the version type of input string MaximumVersion, translate "*" if there's any.
        /// </summary>
        internal static Version GetMaximumVersion(string stringVersion)
        {
            Version maxVersion;
            // First, try to convert maxVersion to version directly
            if (System.Version.TryParse(stringVersion, out maxVersion))
            {
                return maxVersion;
            }
            else
            {
                // If first conversion fails, try to convert * to maximum version
                const string maxRange = "999999999";
                if (stringVersion[stringVersion.Length - 1] == '*')
                {
                    stringVersion = stringVersion.Substring(0, stringVersion.Length - 1);
                    stringVersion += maxRange;
                    int starNum = stringVersion.Count(static x => x == '.');
                    for (int i = 0; i < (3 - starNum); i++)
                    {
                        stringVersion = stringVersion + '.' + maxRange;
                    }
                }
            }

            if (Version.TryParse(stringVersion, out maxVersion))
            {
                return new Version(stringVersion);
            }
            else
            {
                string message = StringUtil.Format(Modules.MaximumVersionFormatIncorrect, stringVersion);
                throw new PSArgumentException(message);
            }
        }

        /// <summary>
        /// Helper function for building a module info for Get-Module -List.
        /// </summary>
        /// <param name="file">The module file.</param>
        /// <param name="refresh">True if we should update any cached module info for this module.</param>
        /// <returns></returns>
        private PSModuleInfo CreateModuleInfoForGetModule(string file, bool refresh)
        {
            // Ensure we don't have any recursion in module lookup
            PSModuleInfo moduleInfo = null;
            if (_currentlyProcessingModules.TryGetValue(file, out moduleInfo))
            {
                return moduleInfo;
            }

            _currentlyProcessingModules[file] = null;

            // Create a fake module info for this file
            string extension;
            file = file.TrimEnd();

            // In case the file is a Ngen Assembly.
            if (file.EndsWith(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase))
            {
                extension = StringLiterals.PowerShellNgenAssemblyExtension;
            }
            else
            {
                extension = Path.GetExtension(file);
            }

            ManifestProcessingFlags flags = ManifestProcessingFlags.NullOnFirstError;
            // We are creating the ModuleInfo for Get-Module..so ignoring
            // PowerShellHostName and PowerShellHostVersion.
            flags |= ManifestProcessingFlags.IgnoreHostNameAndHostVersion;
            if (refresh) { flags |= ManifestProcessingFlags.Force; }

            try
            {
                if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    string throwAwayScriptName;
                    ExternalScriptInfo scriptInfo = GetScriptInfoForFile(file, out throwAwayScriptName, true);

                    // At this place, we used to check if the module is already loaded. If so, return that.
                    // This was done to fix the issue where we were not getting the ExportedCommands since they are populated only after an import.
                    // But, after the auto-loading feature, we get ExportedCommands even before an import.
                    // Plus, the issue of returning the loaded module was introducing a formatting bug (Win8: 284599).
                    // So, removing that logic.
                    moduleInfo = LoadModuleManifest(
                            scriptInfo,
                            flags /* - don't write errors, don't load elements */,
                            minimumVersion: null,
                            maximumVersion: null,
                            requiredVersion: null,
                            requiredModuleGuid: null);
                }
                else
                {
                    // It's not a module manifest, process the individual module
                    ImportModuleOptions options = new ImportModuleOptions();
                    bool found = false;

                    moduleInfo = LoadModule(file, moduleBase: null, prefix: string.Empty, ss: null, ref options, flags, out found);
                }

                // return fake PSModuleInfo if can't read the file for any reason
                if (moduleInfo == null)
                {
                    moduleInfo = new PSModuleInfo(file, context: null, sessionState: null);
                    moduleInfo.HadErrorsLoading = true;     // Prevent analysis cache from caching a bad module.
                }

                if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    if (moduleInfo.RootModuleForManifest != null)
                    {
                        if (moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                            moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            moduleInfo.SetModuleType(ModuleType.Binary);
                        }
                        else if (moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            moduleInfo.SetModuleType(ModuleType.Script);
                        }
                        else if (moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            moduleInfo.SetModuleType(ModuleType.Cim);
                        }
                        else
                        {
                            moduleInfo.SetModuleType(ModuleType.Manifest);
                        }

                        moduleInfo.RootModule = moduleInfo.RootModuleForManifest;
                    }
                    else
                    {
                        moduleInfo.SetModuleType(ModuleType.Manifest);
                        moduleInfo.RootModule = moduleInfo.Path;
                    }
                }
                else if (extension.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                         extension.Equals(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                         extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
                {
                    moduleInfo.SetModuleType(ModuleType.Binary);
                    moduleInfo.RootModule = moduleInfo.Path;
                }
                else if (extension.Equals(StringLiterals.PowerShellCmdletizationFileExtension))
                {
                    moduleInfo.SetModuleType(ModuleType.Cim);

                    string moduleName;
                    ExternalScriptInfo scriptInfo = GetScriptInfoForFile(file, out moduleName, true);
                    var cmdletizationXmlReader = new StringReader(scriptInfo.ScriptContents);
                    var scriptWriter = new ScriptWriter(
                        cmdletizationXmlReader,
                        moduleName,
                        StringLiterals.DefaultCmdletAdapter,
                        this.MyInvocation,
                        ScriptWriter.GenerationOptions.HelpXml);
                    scriptWriter.PopulatePSModuleInfo(moduleInfo);
                    moduleInfo.RootModule = moduleInfo.Path;
                }
                else
                {
                    moduleInfo.SetModuleType(ModuleType.Script);
                    moduleInfo.RootModule = moduleInfo.Path;
                }
            }
            catch (Exception)
            {
                // 3rd-part call out, catch-all OK

                // return fake PSModuleInfo if can't read the file for any reason
                if (moduleInfo == null)
                {
                    moduleInfo = new PSModuleInfo(file, null, null);
                    moduleInfo.HadErrorsLoading = true;     // Prevent analysis cache from caching a bad module.
                }
            }

            if (!moduleInfo.HadErrorsLoading)
            {
                // Cache the module's exported commands
                AnalysisCache.CacheModuleExports(moduleInfo, Context);
            }
            else
            {
                ModuleIntrinsics.Tracer.WriteLine("Caching skipped for {0} because it had errors while loading.", moduleInfo.Name);
            }

            _currentlyProcessingModules[file] = moduleInfo;
            return moduleInfo;
        }

        /// <summary>
        /// Routine to process the module manifest data language script.
        /// </summary>
        /// <param name="scriptInfo">The script info for the manifest script.</param>
        /// <param name="manifestProcessingFlags">Processing flags (whether to write errors / load elements).</param>
        /// <param name="minimumVersion">The minimum version to check the manifest against.</param>
        /// <param name="maximumVersion">The maximum version to check the manifest against.</param>
        /// <param name="requiredVersion">The version to check the manifest against.</param>
        /// <param name="requiredModuleGuid">The module guid to check the manifest against.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadModuleManifest(
            ExternalScriptInfo scriptInfo,
            ManifestProcessingFlags manifestProcessingFlags,
            Version minimumVersion,
            Version maximumVersion,
            Version requiredVersion,
            Guid? requiredModuleGuid)
        {
            ImportModuleOptions options = new ImportModuleOptions();
            return LoadModuleManifest(scriptInfo, manifestProcessingFlags, minimumVersion, maximumVersion, requiredVersion, requiredModuleGuid, ref options);
        }

        /// <summary>
        /// Routine to process the module manifest data language script.
        /// </summary>
        /// <param name="scriptInfo">The script info for the manifest script.</param>
        /// <param name="manifestProcessingFlags">Processing flags (whether to write errors / load elements).</param>
        /// <param name="minimumVersion">The minimum version to check the manifest against.</param>
        /// <param name="maximumVersion">The maximum version to check the manifest against.</param>
        /// <param name="requiredVersion">The version to check the manifest against.</param>
        /// <param name="requiredModuleGuid">The module guid to check the manifest against.</param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadModuleManifest(
            ExternalScriptInfo scriptInfo,
            ManifestProcessingFlags manifestProcessingFlags,
            Version minimumVersion,
            Version maximumVersion,
            Version requiredVersion,
            Guid? requiredModuleGuid,
            ref ImportModuleOptions options)
        {
            Dbg.Assert(scriptInfo != null, "scriptInfo for module (.psd1) can't be null");
            bool containedErrors = false;

            Hashtable data = null;
            Hashtable localizedData = null;
            if (!LoadModuleManifestData(scriptInfo, manifestProcessingFlags, out data, out localizedData, ref containedErrors))
            {
                return null;
            }

            return LoadModuleManifest(scriptInfo.Path, scriptInfo, data, localizedData, manifestProcessingFlags, minimumVersion, maximumVersion, requiredVersion, requiredModuleGuid, ref options, ref containedErrors);
        }

        internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProcessingFlags manifestProcessingFlags, out Hashtable data, out Hashtable localizedData, ref bool containedErrors)
        {
            // load the .psd1 files into hashtables
            localizedData = null;
            data = LoadModuleManifestData(scriptInfo, ModuleManifestMembers, manifestProcessingFlags, ref containedErrors);
            if (data == null)
            {
                return false;
            }

            ExternalScriptInfo localizedScriptInfo = FindLocalizedModuleManifest(scriptInfo.Path);
            localizedData = null;
            if (localizedScriptInfo != null)
            {
                localizedData = LoadModuleManifestData(localizedScriptInfo, null, manifestProcessingFlags, ref containedErrors);
                if (localizedData == null)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Helper function to generate fake PSModuleInfo objects from ModuleSpecification objects.
        /// </summary>
        /// <param name="moduleSpecs">Collection of ModuleSpecification objects.</param>
        /// <returns>Collection of fake PSModuleInfo objects.</returns>
        private IEnumerable<PSModuleInfo> CreateFakeModuleObject(IEnumerable<ModuleSpecification> moduleSpecs)
        {
            foreach (ModuleSpecification moduleSpec in moduleSpecs)
            {
                var fakeModuleInfo = new PSModuleInfo(moduleSpec.Name, Context, null);
                if (moduleSpec.Guid.HasValue)
                {
                    fakeModuleInfo.SetGuid(moduleSpec.Guid.Value);
                }

                fakeModuleInfo.SetVersion(moduleSpec.RequiredVersion ?? moduleSpec.Version);
                yield return fakeModuleInfo;
            }
        }

        private static ErrorRecord GetErrorRecordIfUnsupportedRootCdxmlAndNestedModuleScenario(
            Hashtable data,
            string moduleManifestPath,
            string rootModulePath)
        {
            if (rootModulePath == null)
            {
                return null;
            }

            if (!rootModulePath.EndsWith(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                return null;
            }

            if (!data.ContainsKey("NestedModules"))
            {
                return null;
            }

            string nameOfRootModuleKey = data.ContainsKey("ModuleToProcess") ? "ModuleToProcess" : "RootModule";
            string message = StringUtil.Format(
                Modules.CmdletizationDoesSupportRexportingNestedModules,
                nameOfRootModuleKey,
                moduleManifestPath,
                rootModulePath);
            InvalidOperationException ioe = new InvalidOperationException(message);
            ErrorRecord er = new ErrorRecord(
                ioe,
                "Modules_CmdletizationDoesSupportRexportingNestedModules",
                ErrorCategory.InvalidOperation,
                moduleManifestPath);

            return er;
        }

        /// <summary>
        /// Routine to process the module manifest data language script.
        /// </summary>
        /// <param name="moduleManifestPath">The path to the manifest file.</param>
        /// <param name="manifestScriptInfo">The script info for the manifest script.</param>
        /// <param name="data">Contents of the module manifest.</param>
        /// <param name="localizedData">Contents of the localized module manifest.</param>
        /// <param name="manifestProcessingFlags">Processing flags (whether to write errors / load elements).</param>
        /// <param name="minimumVersion">The minimum version to check the manifest against.</param>
        /// <param name="maximumVersion">The maximum version to check the manifest against.</param>
        /// <param name="requiredVersion">The version to check the manifest against.</param>
        /// <param name="requiredModuleGuid">The module guid to check the manifest against.</param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="containedErrors">Tracks if there were errors in the file.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadModuleManifest(
            string moduleManifestPath,
            ExternalScriptInfo manifestScriptInfo,
            Hashtable data,
            Hashtable localizedData,
            ManifestProcessingFlags manifestProcessingFlags,
            Version minimumVersion,
            Version maximumVersion,
            Version requiredVersion,
            Guid? requiredModuleGuid,
            ref ImportModuleOptions options,
            ref bool containedErrors)
        {
            string message;

            var bailOnFirstError = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.NullOnFirstError);
            var importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements);
            var writingErrors = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.WriteErrors);

            Dbg.Assert(moduleManifestPath != null, "moduleManifestPath for module (.psd1) can't be null");
            string moduleBase = Path.GetDirectoryName(moduleManifestPath);
            string moduleName = ModuleIntrinsics.GetModuleName(moduleManifestPath);

            if ((manifestProcessingFlags &
                 (ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors |
                  ManifestProcessingFlags.WriteWarnings)) != 0)
            {
                Context.ModuleBeingProcessed = moduleManifestPath;
            }

            // START: Check if the ModuleToProcess is already loaded..if it is, ignore the this load manifest
            // call and return
            string moduleToProcess = null;

            if (!GetScalarFromData<string>(data, moduleManifestPath, "ModuleToProcess", manifestProcessingFlags, out moduleToProcess))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            string rootModule = null;
            if (!GetScalarFromData<string>(data, moduleManifestPath, "RootModule", manifestProcessingFlags, out rootModule))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            if (!string.IsNullOrEmpty(moduleToProcess))
            {
                // If we've found ourselves, then skip writing the warning and move on.
                // Win8: 297326
                if (string.IsNullOrEmpty(Context.ModuleBeingProcessed) ||
                    (!Context.ModuleBeingProcessed.Equals(moduleManifestPath, StringComparison.OrdinalIgnoreCase) ||
                     !Context.ModuleBeingProcessed.Equals(Context.PreviousModuleProcessed,
                         StringComparison.OrdinalIgnoreCase)))
                {
                    if ((manifestProcessingFlags & ManifestProcessingFlags.WriteWarnings) != 0)
                    {
                        WriteWarning(Modules.ModuleToProcessFieldDeprecated);
                    }
                }
            }

            if (!string.IsNullOrEmpty(moduleToProcess) && !string.IsNullOrEmpty(rootModule))
            {
                // If we've found ourselves, then skip writing the error and move on.
                // Win8 :330612
                if (string.IsNullOrEmpty(Context.ModuleBeingProcessed) ||
                    (!Context.ModuleBeingProcessed.Equals(moduleManifestPath, StringComparison.OrdinalIgnoreCase) ||
                     !Context.ModuleBeingProcessed.Equals(Context.PreviousModuleProcessed,
                         StringComparison.OrdinalIgnoreCase)))
                {
                    // Having both ModuleToProcess and RootModule is not allowed
                    if (writingErrors)
                    {
                        message = StringUtil.Format(Modules.ModuleManifestCannotContainBothModuleToProcessAndRootModule,
                            moduleManifestPath);
                        InvalidOperationException ioe = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(ioe,
                            "Modules_ModuleManifestCannotContainBothModuleToProcessAndRootModule",
                            ErrorCategory.InvalidOperation, moduleManifestPath);
                        WriteError(er);
                    }
                }

                if (bailOnFirstError) return null;
            }

            string actualRootModule = moduleToProcess ?? rootModule;

            // extract defaultCommandPrefix from the manifest
            string defaultCommandPrefix = null;
            if (
                !GetScalarFromData<string>(data, moduleManifestPath, "DefaultCommandPrefix", manifestProcessingFlags,
                    out defaultCommandPrefix))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            string resolvedCommandPrefix = string.Empty;

            if (!string.IsNullOrEmpty(defaultCommandPrefix))
            {
                resolvedCommandPrefix = defaultCommandPrefix;
            }

            if (!string.IsNullOrEmpty(this.BasePrefix))
            {
                resolvedCommandPrefix = this.BasePrefix;
            }

            if (!string.IsNullOrEmpty(actualRootModule))
            {
                if (WildcardPattern.ContainsWildcardCharacters(actualRootModule))
                {
                    PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException(
                        Modules.WildCardNotAllowedInModuleToProcessAndInNestedModules,
                        moduleManifestPath);
                    invalidOperation.SetErrorId("Modules_WildCardNotAllowedInModuleToProcessAndInNestedModules");
                    throw invalidOperation;
                }

                // See if this module is already loaded. Since the manifest entry may not
                // have an extension and the module table is indexed by full names, we
                // may have search through all the extensions.
                PSModuleInfo loadedModule = null;
                string rootedPath = null;

                // For a root module, we use its own module name instead of the manifest module name when calling 'FixFileName'.
                // This is because when actually loading the root module later, it won't have access to the parent manifest module,
                // and we will use its own name to query for already loaded assemblies from 'Context.AssemblyCache'.
                string rootModuleName = ModuleIntrinsics.GetModuleName(actualRootModule);
                string extension = Path.GetExtension(actualRootModule);
                if (!string.IsNullOrEmpty(extension) && ModuleIntrinsics.IsPowerShellModuleExtension(extension))
                {
                    rootedPath = FixFileName(rootModuleName, moduleBase, actualRootModule, extension: null, canLoadAssembly: importingModule);
                    TryGetFromModuleTable(rootedPath, out loadedModule);
                }
                else
                {
                    foreach (string extensionToTry in ModuleIntrinsics.PSModuleExtensions)
                    {
                        rootedPath = FixFileName(rootModuleName, moduleBase, actualRootModule, extensionToTry, canLoadAssembly: importingModule);
                        if (TryGetFromModuleTable(rootedPath, out loadedModule))
                        {
                            break;
                        }
                    }
                }

                if (importingModule && DoesAlreadyLoadedModuleSatisfyConstraints(loadedModule))
                {
                    if (!BaseForce)
                    {
                        AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, loadedModule);
                        // Even if the module has been loaded, import the specified members...
                        ImportModuleMembers(loadedModule, resolvedCommandPrefix, options);

                        return loadedModule;
                    }
                    // remove the module if force is specified  (and if module is already loaded)
                    else if (File.Exists(rootedPath))
                    {
                        RemoveModule(loadedModule);
                    }
                }
            }

            // END: Check if the ModuleToProcess is already loaded..
            string author = string.Empty;
            if (!GetScalarFromData(data, moduleManifestPath, "Author", manifestProcessingFlags, out author))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            string companyName = string.Empty;
            if (!GetScalarFromData(data, moduleManifestPath, "CompanyName", manifestProcessingFlags, out companyName))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            string copyright = string.Empty;
            if (!GetScalarFromData(data, moduleManifestPath, "Copyright", manifestProcessingFlags, out copyright))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            Guid? manifestGuid;
            if (!GetScalarFromData(data, moduleManifestPath, "guid", manifestProcessingFlags, out manifestGuid))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // Verify that the module manifest contains the module version information
            Version moduleVersion;
            if (
                !GetScalarFromData<Version>(data, moduleManifestPath, "ModuleVersion", manifestProcessingFlags,
                    out moduleVersion))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else
            {
                if (moduleVersion == null)
                {
                    containedErrors = true;
                    if (writingErrors)
                    {
                        message = StringUtil.Format(Modules.ModuleManifestMissingModuleVersion, moduleManifestPath);
                        MissingMemberException mm = new MissingMemberException(message);
                        ErrorRecord er = new ErrorRecord(mm, "Modules_InvalidManifest",
                            ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        WriteError(er);
                    }

                    if (bailOnFirstError) return null;
                }
                else if (!ModuleIntrinsics.AreModuleFieldsMatchingConstraints(
                    moduleGuid: manifestGuid,
                    moduleVersion: moduleVersion,
                    requiredGuid: requiredModuleGuid,
                    requiredVersion: requiredVersion,
                    minimumRequiredVersion: minimumVersion,
                    maximumRequiredVersion: maximumVersion))
                {
                    if (bailOnFirstError)
                    {
                        return null;
                    }
                }

                // Verify that the module version from the module manifest is equal to module version folder.
                DirectoryInfo parent = null;
                try
                {
                    parent = Directory.GetParent(moduleManifestPath);
                }
                catch (IOException)
                {
                }
                catch (UnauthorizedAccessException)
                {
                }
                catch (ArgumentException)
                {
                }

                Version moduleVersionFromFolderName;
                if (parent != null &&
                    Version.TryParse(parent.Name, out moduleVersionFromFolderName) &&
                    parent.Parent != null &&
                    parent.Parent.Name.Equals(Path.GetFileNameWithoutExtension(moduleManifestPath)))
                {
                    if (!moduleVersionFromFolderName.Equals(moduleVersion))
                    {
                        containedErrors = true;
                        if (writingErrors)
                        {
                            message = StringUtil.Format(Modules.InvalidModuleManifestVersion, moduleManifestPath,
                                moduleVersion.ToString(), parent.FullName);
                            var ioe = new InvalidOperationException(message);
                            var er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion",
                                ErrorCategory.InvalidArgument, moduleManifestPath);
                            WriteError(er);
                        }

                        if (bailOnFirstError) return null;
                    }
                }
            }

            // Test that the PowerShellVersion version is valid...
            Version powerShellVersion;
            if (
                !GetScalarFromData<Version>(data, moduleManifestPath, "PowerShellVersion", manifestProcessingFlags,
                    out powerShellVersion))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else if (powerShellVersion != null)
            {
                Version currentPowerShellVersion = PSVersionInfo.PSVersion;
                if (currentPowerShellVersion < powerShellVersion)
                {
                    containedErrors = true;
                    if (writingErrors)
                    {
                        message = StringUtil.Format(Modules.ModuleManifestInsufficientPowerShellVersion,
                            currentPowerShellVersion,
                            moduleManifestPath, powerShellVersion);
                        InvalidOperationException ioe = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(ioe, "Modules_InsufficientPowerShellVersion",
                            ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        WriteError(er);
                    }

                    if (bailOnFirstError) return null;
                }
            }

            // Test that the PowerShellHostVersion version is valid...
            string requestedHostName;
            if (
                !GetScalarFromData(data, moduleManifestPath, "PowerShellHostName", manifestProcessingFlags,
                    out requestedHostName))
            {
                containedErrors = true;
                // Ignore errors related to HostVersion as per the ManifestProcessingFlags
                // doing this at this place because we have to set "containedErrors"
                if (((manifestProcessingFlags & ManifestProcessingFlags.IgnoreHostNameAndHostVersion) == 0) &&
                    bailOnFirstError)
                    return null;
            }
            else if (requestedHostName != null)
            {
                string currentHostName = this.Context.InternalHost.Name;
                if (!string.Equals(currentHostName, requestedHostName, StringComparison.OrdinalIgnoreCase))
                {
                    containedErrors = true;
                    // Ignore errors related to HostVersion as per the ManifestProcessingFlags
                    // doing this at this place because we have to set "containedErrors"
                    if ((manifestProcessingFlags & ManifestProcessingFlags.IgnoreHostNameAndHostVersion) == 0)
                    {
                        if (writingErrors)
                        {
                            message = StringUtil.Format(Modules.InvalidPowerShellHostName,
                                currentHostName, moduleManifestPath, requestedHostName);
                            InvalidOperationException ioe = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidPowerShellHostName",
                                ErrorCategory.ResourceUnavailable, moduleManifestPath);
                            WriteError(er);
                        }

                        if (bailOnFirstError) return null;
                    }
                }
            }

            // Test that the PowerShellHostVersion version is valid...
            Version requestedHostVersion;
            if (
                !GetScalarFromData(data, moduleManifestPath, "PowerShellHostVersion", manifestProcessingFlags,
                    out requestedHostVersion))
            {
                containedErrors = true;
                // Ignore errors related to HostVersion as per the ManifestProcessingFlags
                // doing this at this place because we have to set "containedErrors"
                if (((manifestProcessingFlags & ManifestProcessingFlags.IgnoreHostNameAndHostVersion) == 0) &&
                    bailOnFirstError)
                    return null;
            }
            else if (requestedHostVersion != null)
            {
                Version currentHostVersion = this.Context.InternalHost.Version;
                if (currentHostVersion < requestedHostVersion)
                {
                    containedErrors = true;
                    // Ignore errors related to HostVersion as per the ManifestProcessingFlags
                    // doing this at this place because we have to set "containedErrors"
                    if ((manifestProcessingFlags & ManifestProcessingFlags.IgnoreHostNameAndHostVersion) == 0)
                    {
                        if (writingErrors)
                        {
                            string currentHostName = this.Context.InternalHost.Name;
                            message = StringUtil.Format(Modules.InvalidPowerShellHostVersion,
                                currentHostName, currentHostVersion, moduleManifestPath, requestedHostVersion);
                            InvalidOperationException ioe = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(ioe, "Modules_InsufficientPowerShellHostVersion",
                                ErrorCategory.ResourceUnavailable, moduleManifestPath);
                            WriteError(er);
                        }

                        if (bailOnFirstError) return null;
                    }
                }
            }

            // Test the required processor architecture
            ProcessorArchitecture requiredProcessorArchitecture;
            if (
                !GetScalarFromData(data, moduleManifestPath, "ProcessorArchitecture", manifestProcessingFlags,
                    out requiredProcessorArchitecture))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else if ((requiredProcessorArchitecture != ProcessorArchitecture.None) &&
                     (requiredProcessorArchitecture != ProcessorArchitecture.MSIL))
            {
                Architecture currentArchitecture = RuntimeInformation.ProcessArchitecture;

                if ((requiredProcessorArchitecture == ProcessorArchitecture.X86 && currentArchitecture != Architecture.X86) ||
                    (requiredProcessorArchitecture == ProcessorArchitecture.Amd64 && currentArchitecture != Architecture.X64) ||
                    (requiredProcessorArchitecture == ProcessorArchitecture.Arm && (currentArchitecture != Architecture.Arm && currentArchitecture != Architecture.Arm64)) ||
                    requiredProcessorArchitecture == ProcessorArchitecture.IA64)
                {
                    containedErrors = true;
                    if (writingErrors)
                    {
                        message = StringUtil.Format(Modules.InvalidProcessorArchitecture,
                            currentArchitecture, moduleManifestPath, requiredProcessorArchitecture);
                        InvalidOperationException ioe = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidProcessorArchitecture",
                            ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        WriteError(er);
                    }

                    if (bailOnFirstError) return null;
                }
            }

            // Test the required CLR version
            Version requestedClrVersion;
            if (
                !GetScalarFromData(data, moduleManifestPath, "CLRVersion", manifestProcessingFlags,
                    out requestedClrVersion))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // Test the required .NET Framework version
            Version requestedDotNetFrameworkVersion;
            if (
                !GetScalarFromData(data, moduleManifestPath, "DotNetFrameworkVersion", manifestProcessingFlags,
                    out requestedDotNetFrameworkVersion))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // HelpInfo URI
            string helpInfoUri = null;

            GetScalarFromData<string>(data, moduleManifestPath, "HelpInfoURI", manifestProcessingFlags, out helpInfoUri);

            List<PSModuleInfo> requiredModulesLoaded = new List<PSModuleInfo>();

            // In case of Get-Module -List and Test-ModuleManifest, we populate this list with fake PSModuleInfo for each of the required modules specified
            List<PSModuleInfo> requiredModulesSpecifiedInModuleManifest = new List<PSModuleInfo>();

            ModuleSpecification[] requiredModules;
            if (
                !GetScalarFromData(data, moduleManifestPath, "RequiredModules", manifestProcessingFlags,
                    out requiredModules))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else if ((requiredModules != null))
            {
                if (importingModule)
                {
                    // We need to pass in the moduleInfo of current module so that we can check for cyclic dependency in RequiredModules specification.
                    // When a module A that has a required module B is imported (either explicitly or via auto-loading),
                    // the current scope's module gets set to module A incorrectly. This leads to issues where the exported commands
                    // of a module that imports module A) get added to module A instead of the actual module that is getting imported.
                    // (Direct cause of Win8:336812)
                    PSModuleInfo fakeManifestInfo = new PSModuleInfo(moduleManifestPath, Context, null);
                    if (manifestGuid.HasValue)
                    {
                        fakeManifestInfo.SetGuid(manifestGuid.Value);
                    }

                    if (moduleVersion != null)
                    {
                        fakeManifestInfo.SetVersion(moduleVersion);
                    }

                    foreach (ModuleSpecification requiredModule in requiredModules)
                    {
                        // The required module name is essentially raw user input.
                        // We must process it so paths work.
                        ModuleSpecification normalizedRequiredModuleSpec = requiredModule?.WithNormalizedName(Context, moduleBase);

                        ErrorRecord error = null;
                        PSModuleInfo module = LoadRequiredModule(fakeManifestInfo, normalizedRequiredModuleSpec, moduleManifestPath,
                            manifestProcessingFlags, containedErrors, out error);
                        if (module == null && error != null)
                        {
                            WriteError(error);
                            return null;
                        }
                        // module can be null (in case the RequiredModule has already been added as a snapin.
                        // In that case, we just emit a warning and do not add the snapin to the list of requiredmodules)
                        if (module != null)
                        {
                            requiredModulesLoaded.Add(module);
                        }
                    }
                }
                else
                {
                    foreach (PSModuleInfo fakeRequiredModuleInfo in CreateFakeModuleObject(requiredModules))
                    {
                        requiredModulesSpecifiedInModuleManifest.Add(fakeRequiredModuleInfo);
                    }
                }
            }

            // Validate the list of nestedModules...
            ModuleSpecification[] tmpNestedModules;
            if (
                !GetScalarFromData(data, moduleManifestPath, "NestedModules", manifestProcessingFlags,
                    out tmpNestedModules))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            List<ModuleSpecification> nestedModules = new List<ModuleSpecification>();

            if (tmpNestedModules != null && tmpNestedModules.Length > 0)
            {
                foreach (ModuleSpecification s in tmpNestedModules)
                {
                    s.Name = GetAbsolutePath(moduleBase, s.Name);
                    if (WildcardPattern.ContainsWildcardCharacters(s.Name))
                    {
                        PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException(
                            Modules.WildCardNotAllowedInModuleToProcessAndInNestedModules,
                            moduleManifestPath);
                        invalidOperation.SetErrorId("Modules_WildCardNotAllowedInModuleToProcessAndInNestedModules");
                        throw invalidOperation;
                    }

                    nestedModules.Add(s);
                }

                Array.Clear(tmpNestedModules, 0, tmpNestedModules.Length);
            }

            // Set the private data member for the module if the manifest contains this member
            object privateData = data["PrivateData"];

            // Validate the 'ExperimentalFeatures' member of the manifest
            List<ExperimentalFeature> expFeatureList = null;
            if (privateData is Hashtable hashData && hashData["PSData"] is Hashtable psData)
            {
                if (!GetScalarFromData(psData, moduleManifestPath, "ExperimentalFeatures", manifestProcessingFlags, out Hashtable[] features))
                {
                    containedErrors = true;
                    if (bailOnFirstError) return null;
                }

                if (features != null && features.Length > 0)
                {
                    bool nameMissingOrEmpty = false;
                    var invalidNames = new List<string>();
                    expFeatureList = new List<ExperimentalFeature>(features.Length);

                    foreach (Hashtable feature in features)
                    {
                        string featureName = feature["Name"] as string;
                        if (string.IsNullOrEmpty(featureName))
                        {
                            nameMissingOrEmpty = true;
                        }
                        else if (ExperimentalFeature.IsModuleFeatureName(featureName, moduleName))
                        {
                            string featureDescription = feature["Description"] as string;
                            expFeatureList.Add(new ExperimentalFeature(featureName, featureDescription, moduleManifestPath,
                                                                       ExperimentalFeature.IsEnabled(featureName)));
                        }
                        else
                        {
                            invalidNames.Add(featureName);
                        }
                    }

                    if (nameMissingOrEmpty)
                    {
                        if (writingErrors)
                        {
                            WriteError(new ErrorRecord(new ArgumentException(Modules.ExperimentalFeatureNameMissingOrEmpty),
                                                       "Modules_ExperimentalFeatureNameMissingOrEmpty",
                                                       ErrorCategory.InvalidData, null));
                        }

                        containedErrors = true;
                        if (bailOnFirstError) { return null; }
                    }

                    if (invalidNames.Count > 0)
                    {
                        if (writingErrors)
                        {
                            string invalidNameStr = string.Join(", ", invalidNames);
                            string errorMsg = StringUtil.Format(Modules.InvalidExperimentalFeatureName, invalidNameStr);
                            WriteError(new ErrorRecord(new ArgumentException(errorMsg),
                                                       "Modules_InvalidExperimentalFeatureName",
                                                       ErrorCategory.InvalidData, null));
                        }

                        containedErrors = true;
                        if (bailOnFirstError) { return null; }
                    }
                }
            }

            // Process all of the exports...
            List<WildcardPattern> exportedFunctions;
            if (
                !GetListOfWildcardsFromData(data, moduleManifestPath, "FunctionsToExport", manifestProcessingFlags,
                    out exportedFunctions))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            List<WildcardPattern> exportedVariables;
            if (
                !GetListOfWildcardsFromData(data, moduleManifestPath, "VariablesToExport", manifestProcessingFlags,
                    out exportedVariables))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            List<WildcardPattern> exportedAliases;
            if (
                !GetListOfWildcardsFromData(data, moduleManifestPath, "AliasesToExport", manifestProcessingFlags,
                    out exportedAliases))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            List<WildcardPattern> exportedCmdlets;
            if (
                !GetListOfWildcardsFromData(data, moduleManifestPath, "CmdletsToExport", manifestProcessingFlags,
                    out exportedCmdlets))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            List<WildcardPattern> exportedDscResources;
            if (
                !GetListOfWildcardsFromData(data, moduleManifestPath, "DscResourcesToExport", manifestProcessingFlags,
                    out exportedDscResources))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            InitialSessionState iss = null;
            if (importingModule)
            {
                iss = InitialSessionState.Create();
                if (Context.InitialSessionState != null)
                {
                    iss.DisableFormatUpdates = Context.InitialSessionState.DisableFormatUpdates;
                }
                // We want the processing errors to terminate module import.
                iss.ThrowOnRunspaceOpenError = true;
            }

            // Indicates the ISS.Bind() should be called...
            bool doBind = false;

            if (!GetListOfStringsFromData(
                    data,
                    moduleManifestPath,
                    "RequiredAssemblies",
                    manifestProcessingFlags,
                    out List<string> assemblyList))
            {
                containedErrors = true;
                if (bailOnFirstError)
                {
                    return null;
                }
            }
            else if (assemblyList != null && importingModule)
            {
                foreach (string assembly in assemblyList)
                {
                    if (WildcardPattern.ContainsWildcardCharacters(assembly))
                    {
                        PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException(
                            Modules.WildCardNotAllowedInRequiredAssemblies,
                            moduleManifestPath);
                        invalidOperation.SetErrorId("Modules_WildCardNotAllowedInRequiredAssemblies");
                        throw invalidOperation;
                    }
                    else
                    {
                        string fileName = null;
                        string ext = Path.GetExtension(assembly);

                        // Note that we don't need to load the required assemblies eagerly because they will be loaded before
                        // processing type and format data. So, when calling 'FixupFileName', we only attempt to resolve the
                        // path, and avoid triggering the loading of the assembly.
                        if (ModuleIntrinsics.ProcessableAssemblyExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
                        {
                            fileName = FixFileNameWithoutLoadingAssembly(moduleBase, assembly, extension: null);
                        }
                        else
                        {
                            bool isPathResolved = false;
                            foreach (string extToTry in ModuleIntrinsics.ProcessableAssemblyExtensions)
                            {
                                fileName = FixFileNameWithoutLoadingAssembly(moduleBase, assembly, extToTry, out isPathResolved);
                                if (isPathResolved)
                                {
                                    break;
                                }
                            }

                            if (!isPathResolved)
                            {
                                // We didn't resolve the assembly path, so remove the '.exe' extension that was added in the
                                // last iteration of the above loop.
                                int index = fileName.LastIndexOf('.');
                                fileName = fileName.Substring(0, index);
                            }
                        }

                        WriteVerbose(StringUtil.Format(Modules.LoadingFile, "Assembly", fileName));

                        // Set a fake PSModuleInfo object to indicate the module it comes from.
                        var assemblyEntry = new SessionStateAssemblyEntry(assembly, fileName);
                        assemblyEntry.SetModule(new PSModuleInfo(moduleName, path: null, context: null, sessionState: null));

                        iss.Assemblies.Add(assemblyEntry);
                        doBind = true;
                    }
                }
            }

            // Set up to load any types files that have been specified...
            if (!GetListOfFilesFromData(
                data,
                moduleManifestPath,
                key: "TypesToProcess",
                manifestProcessingFlags,
                moduleBase,
                extension: ".ps1xml",
                verifyFilesExist: true,
                out List<string> exportedTypeFiles))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else
            {
                if ((exportedTypeFiles != null) && importingModule)
                {
                    foreach (string fileName in exportedTypeFiles)
                    {
                        string loadMessage = StringUtil.Format(Modules.LoadingFile, "TypesToProcess", fileName);
                        WriteVerbose(loadMessage);

                        bool isAlreadyLoaded = false;
                        string resolvedFileName = ResolveRootedFilePath(fileName, Context) ?? fileName;
                        foreach (var entry in Context.InitialSessionState.Types)
                        {
                            if (entry.FileName == null)
                            {
                                continue;
                            }

                            string resolvedEntryFileName = ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName;
                            if (resolvedEntryFileName.Equals(resolvedFileName, StringComparison.OrdinalIgnoreCase))
                            {
                                isAlreadyLoaded = true;
                                break;
                            }
                        }

                        if (!isAlreadyLoaded)
                        {
                            iss.Types.Add(new SessionStateTypeEntry(fileName));
                            doBind = true;
                        }
                    }
                }
            }

            // Set up to load any format files that have been specified...
            if (!GetListOfFilesFromData(
                data,
                moduleManifestPath,
                key: "FormatsToProcess",
                manifestProcessingFlags,
                moduleBase,
                extension: ".ps1xml",
                verifyFilesExist: true,
                out List<string> exportedFormatFiles))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else
            {
                if ((exportedFormatFiles != null) && importingModule)
                {
                    foreach (string fileName in exportedFormatFiles)
                    {
                        string loadMessage = StringUtil.Format(Modules.LoadingFile, "FormatsToProcess", fileName);
                        WriteVerbose(loadMessage);

                        bool isAlreadyLoaded = false;
                        foreach (var entry in Context.InitialSessionState.Formats)
                        {
                            if (entry.FileName == null)
                            {
                                continue;
                            }

                            if (entry.FileName.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                            {
                                isAlreadyLoaded = true;
                                break;
                            }
                        }

                        if (!isAlreadyLoaded)
                        {
                            iss.Formats.Add(new SessionStateFormatEntry(fileName));
                            doBind = true;
                        }
                    }
                }
            }

            // scripts to process
            if (!GetListOfFilesFromData(
                data,
                moduleManifestPath,
                key: "ScriptsToProcess",
                manifestProcessingFlags,
                moduleBase,
                extension: ".ps1",
                verifyFilesExist: true,
                out List<string> scriptsToProcess))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }
            else
            {
                if ((scriptsToProcess != null) && importingModule)
                {
                    foreach (string scriptFile in scriptsToProcess)
                    {
                        if (!Path.GetExtension(scriptFile).Equals(".ps1", StringComparison.OrdinalIgnoreCase))
                        {
                            string errorMessage = StringUtil.Format(Modules.ScriptsToProcessIncorrectExtension,
                                scriptFile);
                            InvalidOperationException ioe = new InvalidOperationException(errorMessage);
                            WriteInvalidManifestMemberError(this, "ScriptsToProcess", moduleManifestPath, ioe,
                                manifestProcessingFlags);

                            containedErrors = true;
                            if (bailOnFirstError) return null;
                        }
                    }
                }
            }

            // Now add the metadata to the module info object for the manifest...
            string description = string.Empty;
            if (data.Contains("Description"))
            {
                if (localizedData != null && localizedData.Contains("Description"))
                {
                    description = (string)LanguagePrimitives.ConvertTo(localizedData["Description"],
                        typeof(string), CultureInfo.InvariantCulture);
                }

                if (string.IsNullOrEmpty(description))
                {
                    description = (string)LanguagePrimitives.ConvertTo(data["Description"],
                        typeof(string), CultureInfo.InvariantCulture);
                }
            }

            // Process "FileList"
            if (!GetListOfFilesFromData(
                data,
                moduleManifestPath,
                key: "FileList",
                manifestProcessingFlags,
                moduleBase,
                extension: null,
                // Don't check file existence - don't want to change current behavior without feature team discussion.
                verifyFilesExist: false,
                out List<string> fileList))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // Process "ModuleList
            ModuleSpecification[] moduleList;
            if (
                !GetScalarFromData<ModuleSpecification[]>(data, moduleManifestPath, "ModuleList",
                    manifestProcessingFlags, out moduleList))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // Process "CompatiblePSEditions"
            string[] compatiblePSEditions;
            if (
                !GetScalarFromData<string[]>(data, moduleManifestPath, "CompatiblePSEditions",
                    manifestProcessingFlags, out compatiblePSEditions))
            {
                containedErrors = true;
                if (bailOnFirstError) return null;
            }

            // On Windows, we want to include any modules under %WINDIR%\System32\WindowsPowerShell\v1.0\Modules
            // that have declared compatibility with PS Core (or if the check is skipped)
            IEnumerable<string> inferredCompatiblePSEditions = compatiblePSEditions ?? DefaultCompatiblePSEditions;
            bool isConsideredCompatible = ModuleUtils.IsPSEditionCompatible(moduleManifestPath, inferredCompatiblePSEditions);
            if (!BaseSkipEditionCheck && !isConsideredCompatible)
            {
                if (PowerShellConfig.Instance.IsImplicitWinCompatEnabled())
                {
                    if (importingModule)
                    {
                        IList<PSModuleInfo> moduleProxies = ImportModulesUsingWinCompat(
                            moduleNames: new string[] { moduleManifestPath },
                            moduleFullyQualifiedNames: null,
                            importModuleOptions: options);

                        // We are loading by a single ManifestPath so expect max of 1
                        return moduleProxies.Count > 0 ? moduleProxies[0] : null;
                    }
                }
                else
                {
                    containedErrors = true;
                    if (writingErrors)
                    {
                        message = StringUtil.Format(
                            Modules.ImplicitWinCompatDisabled,
                            moduleManifestPath,
                            string.Join(',', inferredCompatiblePSEditions));

                        ErrorRecord er = new ErrorRecord(
                            new InvalidOperationException(message),
                            nameof(Modules) + "_" + nameof(Modules.ImplicitWinCompatDisabled),
                            ErrorCategory.ResourceUnavailable,
                            moduleManifestPath);

                        WriteError(er);
                    }

                    if (bailOnFirstError)
                    {
                        // If we're trying to load the module, return null so that caches
                        // are not polluted
                        if (importingModule)
                        {
                            return null;
                        }

                        // If we return null with Get-Module, a fake module info will be created. Since
                        // we want to suppress output of the module, we need to do that here.
                        return new PSModuleInfo(moduleManifestPath, context: null, sessionState: null)
                        {
                            HadErrorsLoading = true,
                            IsConsideredEditionCompatible = false,
                        };
                    }
                }
            }

            // Process format.ps1xml / types.ps1.xml / RequiredAssemblies
            // as late as possible, but before ModuleToProcess, ScriptToProcess, NestedModules
            if (importingModule)
            {
                // Do the InitialSessionState binding...
                if (doBind)
                {
                    try
                    {
                        iss.Bind(Context, updateOnly: true, module: null, noClobber: false, local: false, setLocation: false);
                    }
                    catch (Exception e)
                    {
                        this.RemoveTypesAndFormatting(exportedFormatFiles, exportedTypeFiles);
                        ErrorRecord er = new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation,
                            null);
                        if (bailOnFirstError)
                        {
                            this.ThrowTerminatingError(er);
                        }
                        else if (writingErrors)
                        {
                            this.WriteError(er);
                        }
                    }
                }
            }

            // Create a PSModuleInfo for psd1 file or take one from ModuleToProcess manifest field
            // SessionState is created for psd1 file or taken from ModuleToProcess module (unless it is a binary module)
            // If we're loading the manifest, allocate a session state object for it...
            var ss = importingModule ? new SessionState(Context, true, true) : null;
            var manifestInfo = new PSModuleInfo(moduleManifestPath, Context, ss);

            // Default to a Manifest module type...
            manifestInfo.SetModuleType(ModuleType.Manifest);

            if (importingModule)
            {
                SetModuleLoggingInformation(manifestInfo);
            }

            if (requiredModulesSpecifiedInModuleManifest != null && requiredModulesSpecifiedInModuleManifest.Count > 0)
            {
                foreach (var module in requiredModulesSpecifiedInModuleManifest)
                {
                    manifestInfo.AddRequiredModule(module);
                }
            }

            // If there is a session state, set up to import/export commands and variables
            if (ss != null)
            {
                ss.Internal.SetVariable(
                    SpecialVariables.PSScriptRootVarPath,
                    moduleBase,
                    asValue: true,
                    CommandOrigin.Internal);

                ss.Internal.SetVariable(
                    SpecialVariables.PSCommandPathVarPath,
                    moduleManifestPath,
                    asValue: true,
                    CommandOrigin.Internal);

                ss.Internal.Module = manifestInfo;

                // without ModuleToProcess a manifest will export everything by default
                // (otherwise we want to honour exports from ModuleToProcess)
                exportedAliases ??= MatchAll;
                exportedCmdlets ??= MatchAll;
                exportedDscResources ??= MatchAll;
                exportedFunctions ??= MatchAll;
                exportedVariables ??= MatchAll;
            }

            manifestInfo.Description = description;
            manifestInfo.PrivateData = privateData;
            manifestInfo.SetExportedTypeFiles(new ReadOnlyCollection<string>(exportedTypeFiles ?? new List<string>()));
            manifestInfo.SetExportedFormatFiles(new ReadOnlyCollection<string>(exportedFormatFiles ?? new List<string>()));
            manifestInfo.SetVersion(moduleVersion);
            manifestInfo.Author = author;
            manifestInfo.CompanyName = companyName;
            manifestInfo.Copyright = copyright;
            manifestInfo.DotNetFrameworkVersion = requestedDotNetFrameworkVersion;
            manifestInfo.ClrVersion = requestedClrVersion;
            manifestInfo.PowerShellHostName = requestedHostName;
            manifestInfo.PowerShellHostVersion = requestedHostVersion;
            manifestInfo.PowerShellVersion = powerShellVersion;
            manifestInfo.ProcessorArchitecture = requiredProcessorArchitecture;
            manifestInfo.Prefix = resolvedCommandPrefix;

            // A module is considered compatible if it's not on the System32 module path, or
            // if it is and declared "Core" as a compatible PSEdition.
            manifestInfo.IsConsideredEditionCompatible = isConsideredCompatible;

            if (expFeatureList != null)
            {
                manifestInfo.ExperimentalFeatures = new ReadOnlyCollection<ExperimentalFeature>(expFeatureList);
            }

            if (assemblyList != null)
            {
                foreach (var a in assemblyList)
                {
                    manifestInfo.AddRequiredAssembly(a);
                }
            }

            if (fileList != null)
            {
                foreach (var f in fileList)
                {
                    string absoluteFilePath = GetAbsolutePath(moduleBase, f);
                    manifestInfo.AddToFileList(absoluteFilePath);
                }
            }

            if (moduleList != null)
            {
                foreach (var m in moduleList)
                {
                    m.Name = GetAbsolutePath(moduleBase, m.Name);
                    manifestInfo.AddToModuleList(m);
                }
            }

            if (compatiblePSEditions != null)
            {
                manifestInfo.AddToCompatiblePSEditions(compatiblePSEditions);
            }

            if (scriptsToProcess != null)
            {
                foreach (var s in scriptsToProcess)
                {
                    manifestInfo.AddScript(s);
                }
            }

            manifestInfo.RootModule = actualRootModule;
            manifestInfo.RootModuleForManifest = actualRootModule;
            if (manifestGuid != null)
            {
                manifestInfo.SetGuid((Guid)manifestGuid);
            }

            if (helpInfoUri != null)
            {
                manifestInfo.SetHelpInfoUri(helpInfoUri);
            }

            foreach (PSModuleInfo module in requiredModulesLoaded)
            {
                manifestInfo.AddRequiredModule(module);
            }

            if (requiredModules != null)
            {
                foreach (ModuleSpecification moduleSpecification in requiredModules)
                {
                    manifestInfo.AddRequiredModuleSpecification(moduleSpecification);
                }
            }

            // Populate the RepositorySourceLocation property from PSGetModuleInfo.xml file if it is available under the module base folder.
            var psgetItemInfoXml = Path.Combine(moduleBase, "PSGetModuleInfo.xml");
            if (File.Exists(psgetItemInfoXml))
            {
                WriteVerbose(StringUtil.Format(Modules.PopulatingRepositorySourceLocation, manifestInfo.Name));
                try
                {
                    using (TextReader reader = File.OpenText(psgetItemInfoXml))
                    {
                        PSObject xml = PSSerializer.Deserialize(reader.ReadToEnd()) as PSObject;
                        if (xml != null && xml.Properties["RepositorySourceLocation"] != null)
                        {
                            var repositorySourceLocation = xml.Properties["RepositorySourceLocation"].Value.ToString();
                            Uri repositorySourceLocationUri;

                            if (!string.IsNullOrWhiteSpace(repositorySourceLocation) &&
                                Uri.TryCreate(repositorySourceLocation, UriKind.RelativeOrAbsolute,
                                    out repositorySourceLocationUri))
                            {
                                manifestInfo.RepositorySourceLocation = repositorySourceLocationUri;
                            }
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                }
                catch (ArgumentException)
                {
                }
                catch (PathTooLongException)
                {
                }
                catch (NotSupportedException)
                {
                }
                catch (InvalidOperationException)
                {
                }
                catch (System.Xml.XmlException)
                {
                }
            }

            // If there are any wildcards, or any of the exported* are empty,
            // we need to do static analysis.
            if (!importingModule)
            {
                bool usedWildcard = false;
                bool sawExportedFunctions = false;
                bool sawExportedCmdlets = false;
                bool sawExportedAliases = false;

                if (exportedFunctions != null)
                {
                    manifestInfo.DeclaredFunctionExports = new Collection<string>();

                    if (exportedFunctions.Count > 0)
                    {
                        foreach (WildcardPattern p in exportedFunctions)
                        {
                            string name = p.Pattern;
                            if (!WildcardPattern.ContainsWildcardCharacters(name))
                            {
                                manifestInfo.DeclaredFunctionExports.Add(AddPrefixToCommandName(name, defaultCommandPrefix));
                            }
                            else
                            {
                                usedWildcard = true;
                            }
                        }

                        if (manifestInfo.DeclaredFunctionExports.Count == 0)
                        {
                            manifestInfo.DeclaredFunctionExports = null;
                        }
                    }

                    sawExportedFunctions = true;
                }

                if (exportedCmdlets != null)
                {
                    manifestInfo.DeclaredCmdletExports = new Collection<string>();

                    if (exportedCmdlets.Count > 0)
                    {
                        foreach (WildcardPattern p in exportedCmdlets)
                        {
                            string name = p.Pattern;
                            if (!WildcardPattern.ContainsWildcardCharacters(name))
                            {
                                manifestInfo.DeclaredCmdletExports.Add(AddPrefixToCommandName(name, defaultCommandPrefix));
                            }
                            else
                            {
                                usedWildcard = true;
                            }
                        }

                        if (manifestInfo.DeclaredCmdletExports.Count == 0)
                        {
                            manifestInfo.DeclaredCmdletExports = null;
                        }
                    }

                    sawExportedCmdlets = true;
                }

                if (exportedAliases != null)
                {
                    manifestInfo.DeclaredAliasExports = new Collection<string>();

                    if (exportedAliases.Count > 0)
                    {
                        foreach (WildcardPattern p in exportedAliases)
                        {
                            string name = p.Pattern;
                            if (!WildcardPattern.ContainsWildcardCharacters(name))
                            {
                                manifestInfo.DeclaredAliasExports.Add(AddPrefixToCommandName(name, defaultCommandPrefix));
                            }
                            else
                            {
                                usedWildcard = true;
                            }
                        }

                        if (manifestInfo.DeclaredAliasExports.Count == 0)
                        {
                            manifestInfo.DeclaredAliasExports = null;
                        }
                    }

                    sawExportedAliases = true;
                }

                if (exportedVariables != null)
                {
                    manifestInfo.DeclaredVariableExports = new Collection<string>();

                    if (exportedVariables.Count > 0)
                    {
                        foreach (WildcardPattern p in exportedVariables)
                        {
                            string name = p.Pattern;
                            if (!WildcardPattern.ContainsWildcardCharacters(name))
                            {
                                manifestInfo.DeclaredVariableExports.Add(name);
                            }
                        }

                        if (manifestInfo.DeclaredVariableExports.Count == 0)
                        {
                            manifestInfo.DeclaredVariableExports = null;
                        }
                    }
                }

                // We have to further analyze the module if any wildcard characters are used.
                bool needToAnalyzeScriptModules = usedWildcard;

                // We can skip further analysis if 'FunctionsToExport', 'CmdletsToExport' and 'AliasesToExport'
                // are all declared and no wildcard character is used for them. But if any of 'FunctionsToExport',
                // 'CmdletsToExport' or 'AliasesToExport' were not given, we must check to see if more analysis is needed.
                if (!needToAnalyzeScriptModules && (!sawExportedCmdlets || !sawExportedFunctions || !sawExportedAliases))
                {
                    foreach (var nestedModule in nestedModules)
                    {
                        if (AnalysisCache.ModuleAnalysisViaGetModuleRequired(
                                nestedModule, sawExportedCmdlets, sawExportedFunctions, sawExportedAliases))
                        {
                            needToAnalyzeScriptModules = true;
                            break;
                        }
                    }

                    if (!needToAnalyzeScriptModules)
                    {
                        needToAnalyzeScriptModules = AnalysisCache.ModuleAnalysisViaGetModuleRequired(
                            actualRootModule, sawExportedCmdlets, sawExportedFunctions, sawExportedAliases);
                    }
                }

                bool etwEnabled = CommandDiscoveryEventSource.Log.IsEnabled();
                if (etwEnabled)
                {
                    CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(manifestInfo.Path, !needToAnalyzeScriptModules);
                }

                if (!needToAnalyzeScriptModules)
                {
                    // Add nested modules to the manifestInfo when no more analysis needs to be done
                    foreach (PSModuleInfo fakeNestedModuleInfo in CreateFakeModuleObject(nestedModules))
                    {
                        manifestInfo.AddNestedModule(fakeNestedModuleInfo);
                    }

                    return manifestInfo;
                }
            }

            if (scriptsToProcess != null)
            {
                Version savedBaseMinimumVersion = BaseMinimumVersion;
                Version savedBaseMaximumVersion = BaseMaximumVersion;
                Version savedBaseRequiredVersion = BaseRequiredVersion;
                Guid? savedBaseGuid = BaseGuid;

                try
                {
                    BaseMinimumVersion = null;
                    BaseMaximumVersion = null;
                    BaseRequiredVersion = null;
                    BaseGuid = null;

                    foreach (string scriptFile in scriptsToProcess)
                    {
                        bool found = false;
                        PSModuleInfo module = LoadModule(scriptFile,
                            moduleBase,
                            string.Empty, // prefix (-Prefix shouldn't be applied to dot sourced scripts)
                            null,
                            ref options,
                            manifestProcessingFlags,
                            out found);

                        // If we're in analysis, add the detected exports to this module's
                        // exports
                        if (found && (ss == null))
                        {
                            foreach (string detectedCmdlet in module.ExportedCmdlets.Keys)
                            {
                                manifestInfo.AddDetectedCmdletExport(detectedCmdlet);
                            }

                            foreach (string detectedFunction in module.ExportedFunctions.Keys)
                            {
                                manifestInfo.AddDetectedFunctionExport(detectedFunction);
                            }

                            foreach (string detectedAlias in module.ExportedAliases.Keys)
                            {
                                manifestInfo.AddDetectedAliasExport(detectedAlias,
                                    module.ExportedAliases[detectedAlias].Definition);
                            }
                        }
                    }
                }
                finally
                {
                    BaseMinimumVersion = savedBaseMinimumVersion;
                    BaseMaximumVersion = savedBaseMaximumVersion;
                    BaseRequiredVersion = savedBaseRequiredVersion;
                    BaseGuid = savedBaseGuid;
                }
            }

            // Process nested modules

            // If we have no session state and are loading a module, return an error
            if ((ss == null) && importingModule)
            {
                containedErrors = true;
                if (writingErrors)
                {
                    string errorMessage =
                        StringUtil.Format(Modules.ModuleManifestNestedModulesCantGoWithModuleToProcess,
                            moduleManifestPath);
                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(errorMessage),
                        "Modules_BinaryModuleAndNestedModules",
                        ErrorCategory.InvalidArgument,
                        moduleManifestPath);
                    this.WriteError(errorRecord);
                }
            }

            // We have a session state, or are in module analysis

            // Save the various base cmdlet parameters so that we can import
            // all of the exported members from each nested module into this module...
            bool oldPassThru = BasePassThru;
            BasePassThru = false;
            List<WildcardPattern> oldVariablePatterns = BaseVariablePatterns;
            List<WildcardPattern> oldFunctionPatterns = BaseFunctionPatterns;
            List<WildcardPattern> oldAliasPatterns = BaseAliasPatterns;
            List<WildcardPattern> oldCmdletPatterns = BaseCmdletPatterns;
            BaseVariablePatterns = BaseFunctionPatterns = BaseAliasPatterns = BaseCmdletPatterns = MatchAll;
            bool oldBaseDisableNameChecking = BaseDisableNameChecking;
            BaseDisableNameChecking = true;

            SessionStateInternal oldSessionState = Context.EngineSessionState;
            var exportedFunctionsContainsWildcards = ModuleIntrinsics.PatternContainsWildcard(exportedFunctions);
            try
            {
                if (importingModule)
                {
                    Dbg.Assert(ss != null, "ss should not be null");
                    Dbg.Assert(ss.Internal != null, "ss.Internal should not be null");
                }

                if (ss != null)
                {
                    ss.Internal.ManifestWithExplicitFunctionExport = !exportedFunctionsContainsWildcards;
                    Context.EngineSessionState = ss.Internal;
                }

                // Load all of the nested modules, which may have relative or absolute paths...

                // For nested modules, we need to set importmoduleoptions to false as they should not use the options set for parent module
                ImportModuleOptions nestedModuleOptions = new ImportModuleOptions();

                // If the nested manifest explicitly (no wildcards) specifies functions to be exported then allow all functions to be exported
                // into the session state function table (regardless of language boundaries), because the manifest will filter them later to the
                // specified function list.
                nestedModuleOptions.AllowNestedModuleFunctionsToExport = ((exportedFunctions != null) && !exportedFunctionsContainsWildcards);

                foreach (ModuleSpecification nestedModuleSpecification in nestedModules)
                {
                    bool found = false;
                    // Never load nested modules to the global scope.
                    bool oldGlobal = this.BaseGlobal;
                    this.BaseGlobal = false;

                    PSModuleInfo nestedModule = LoadModuleNamedInManifest(
                            parentModule: manifestInfo,
                            moduleSpecification: nestedModuleSpecification,
                            moduleBase: moduleBase,
                            searchModulePath: true,
                            prefix: string.Empty,
                            ss: null,
                            options: nestedModuleOptions,
                            manifestProcessingFlags: manifestProcessingFlags,
                            privateData: privateData,
                            found: out found,
                            shortModuleName: null,
                            manifestLanguageMode: ((manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null));

                    this.BaseGlobal = oldGlobal;

                    // If found, add it to the parent's list of NestedModules
                    if (found)
                    {
                        // If we're in analysis, add the detected exports to this module's
                        // exports
                        if ((ss == null) && (nestedModule != null))
                        {
                            foreach (string detectedCmdlet in nestedModule.ExportedCmdlets.Keys)
                            {
                                manifestInfo.AddDetectedCmdletExport(detectedCmdlet);
                            }

                            foreach (var detectedFunction in nestedModule.ExportedFunctions.Keys)
                            {
                                manifestInfo.AddDetectedFunctionExport(detectedFunction);
                            }

                            foreach (string detectedAlias in nestedModule.ExportedAliases.Keys)
                            {
                                manifestInfo.AddDetectedAliasExport(detectedAlias,
                                    nestedModule.ExportedAliases[detectedAlias].Definition);
                            }
                        }
                        // If the NestedModules was a .ps1 script no module object would have been generated
                        // so there's nothing to add, otherwise add it to the list.
                        // When we are in analysis mode and we do not analyze the nested module (because the parent module has explicit exports), the nested modules do not get added to the list
                        if (nestedModule != null)
                        {
                            manifestInfo.AddNestedModule(nestedModule);
                        }
                    }
                    else
                    {
                        containedErrors = true;
                        string errorMessage = StringUtil.Format(Modules.ManifestMemberNotFound,
                            nestedModuleSpecification.Name, "NestedModules", moduleManifestPath);
                        FileNotFoundException fnf = new FileNotFoundException(errorMessage);
                        PSInvalidOperationException invalidOperation = new PSInvalidOperationException(
                            errorMessage, fnf, "Modules_ModuleFileNotFound", ErrorCategory.ResourceUnavailable,
                            ModuleIntrinsics.GetModuleName(moduleManifestPath));
                        throw invalidOperation;
                    }
                }
            }
            catch (Exception)
            {
                // Remove the types and format files
                this.RemoveTypesAndFormatting(exportedFormatFiles, exportedTypeFiles);
                throw;
            }
            finally
            {
                // Restore the old session state object...
                Context.EngineSessionState = oldSessionState;

                // Restore the various cmdlet parameters to what the user passed in...
                BasePassThru = oldPassThru;
                BaseVariablePatterns = oldVariablePatterns;
                BaseFunctionPatterns = oldFunctionPatterns;
                BaseAliasPatterns = oldAliasPatterns;
                BaseCmdletPatterns = oldCmdletPatterns;
                BaseDisableNameChecking = oldBaseDisableNameChecking;
            }

            // Now see if the ModuleToProcess field was set. This radically
            // changes how the exports are done.
            if (actualRootModule != null)
            {
                PSModuleInfo newManifestInfo;

                // do not write out ModuleToProcess inside LoadModuleNamedInManifest
                // - wait until all attributes have been taken from psd1 into PSModuleInfo/manifestInfo
                // and then write out manifestInfo
                BasePassThru = false;

                // do not import anything from "ModuleToProcess" at this time
                // below we will call ImportModuleMembers(manifestInfo) after all nested modules have been processed
                BaseVariablePatterns = new List<WildcardPattern>();
                BaseFunctionPatterns = new List<WildcardPattern>();
                BaseAliasPatterns = new List<WildcardPattern>();
                BaseCmdletPatterns = new List<WildcardPattern>();

                try
                {
                    bool found;
                    newManifestInfo = LoadModuleNamedInManifest(
                        parentModule: null,
                        moduleSpecification: new ModuleSpecification(actualRootModule),
                        moduleBase: moduleBase,
                        searchModulePath: false,
                        prefix: resolvedCommandPrefix,
                        ss: ss,
                        options: options,
                        manifestProcessingFlags: manifestProcessingFlags,
                        privateData: privateData,
                        found: out found,
                        shortModuleName: null,
                        manifestLanguageMode: ((manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null));

                    if (!found || (newManifestInfo == null))
                    {
                        containedErrors = true;
                        string errorMessage = StringUtil.Format(Modules.ManifestMemberNotFound, actualRootModule,
                            "ModuleToProcess/RootModule", moduleManifestPath);
                        FileNotFoundException fnf = new FileNotFoundException(errorMessage);
                        PSInvalidOperationException invalidOperation = new PSInvalidOperationException(errorMessage, fnf,
                            "Modules_ModuleFileNotFound", ErrorCategory.ResourceUnavailable,
                            ModuleIntrinsics.GetModuleName(moduleManifestPath));
                        throw invalidOperation;
                    }

                    ErrorRecord errorRecord = GetErrorRecordIfUnsupportedRootCdxmlAndNestedModuleScenario(data,
                        moduleManifestPath, newManifestInfo.Path);
                    if (errorRecord != null)
                    {
                        containedErrors = true;
                        RemoveModule(newManifestInfo);
                        PSInvalidOperationException invalidOperation =
                            new PSInvalidOperationException(errorRecord.Exception.Message, errorRecord.Exception,
                                errorRecord.FullyQualifiedErrorId, ErrorCategory.InvalidOperation, moduleManifestPath);
                        throw invalidOperation;
                    }
                }
                catch (Exception)
                {
                    // Remove the types and format files
                    this.RemoveTypesAndFormatting(exportedFormatFiles, exportedTypeFiles);
                    throw;
                }
                finally
                {
                    // Restore the various cmdlet parameters to what the user passed in...
                    BasePassThru = oldPassThru;
                    BaseVariablePatterns = oldVariablePatterns;
                    BaseFunctionPatterns = oldFunctionPatterns;
                    BaseAliasPatterns = oldAliasPatterns;
                    BaseCmdletPatterns = oldCmdletPatterns;
                }

                // For most cases, 'newManifestInfo.SessionState' should be identical to 'ss':
                //  1. when 'importingModule == true', 'newManifestInfo' uses the same session state as 'ss' because we passed in 'ss' when loading the RootModule via 'LoadModuleNamedInManifest'.
                //  2. when 'importingModule == false', both session states will be null since we are in module analysis mode (Get-Module -ListAvailable).
                //
                // However, there is one exception when the RootModule is also put in NestedModules in the module manifest (ill-organized module structure).
                // For example, module folder 'test' contains two files: 'test.psd1' and 'test.psm1', and 'test.psd1' has the following content:
                //     "@{ ModuleVersion = '0.0.1'; RootModule = 'test'; NestedModules = @('test') }"
                //
                // In that case, the nested module will first be loaded with a different session state, and then when trying to load the RootModule via 'LoadModuleNamedInManifest',
                // the same loaded nested module will be reused for the RootModule by 'LoadModuleNamedInManifest'.

                // Change the module name to match the manifest name, not the original name.
                newManifestInfo.SetName(manifestInfo.Name);

                // Copy in any nested modules...
                foreach (PSModuleInfo nm in manifestInfo.NestedModules)
                {
                    newManifestInfo.AddNestedModule(nm);
                }

                // Copy the required modules...
                foreach (PSModuleInfo rm in manifestInfo.RequiredModules)
                {
                    newManifestInfo.AddRequiredModule(rm);
                }

                // Copy in the version number - this over-write anything extracted
                // from the dll in the case of a binary module
                newManifestInfo.SetVersion(manifestInfo.Version);

                // Set the various bits of metadata from the manifest
                if (string.IsNullOrEmpty(newManifestInfo.Description))
                {
                    newManifestInfo.Description = description;
                }

                if (newManifestInfo.Version.Equals(new Version(0, 0)))
                {
                    newManifestInfo.SetVersion(moduleVersion);
                }

                if (newManifestInfo.Guid.Equals(Guid.Empty) && (manifestGuid != null))
                {
                    newManifestInfo.SetGuid((Guid)manifestGuid);
                }

                if (newManifestInfo.HelpInfoUri == null && (helpInfoUri != null))
                {
                    newManifestInfo.SetHelpInfoUri(helpInfoUri);
                }

                if (requiredModules != null)
                {
                    foreach (ModuleSpecification moduleSpecification in requiredModules)
                    {
                        newManifestInfo.AddRequiredModuleSpecification(moduleSpecification);
                    }
                }

                newManifestInfo.RootModule ??= manifestInfo.RootModule;
                // If may be the case that a script has already set the PrivateData field in the module
                // info object, in which case we won't overwrite it.
                newManifestInfo.PrivateData ??= manifestInfo.PrivateData;

                // Assign the PowerShellGet related properties from the module manifest
                foreach (var tag in manifestInfo.Tags)
                {
                    newManifestInfo.AddToTags(tag);
                }

                newManifestInfo.ReleaseNotes = manifestInfo.ReleaseNotes;
                newManifestInfo.ProjectUri = manifestInfo.ProjectUri;
                newManifestInfo.LicenseUri = manifestInfo.LicenseUri;
                newManifestInfo.IconUri = manifestInfo.IconUri;
                newManifestInfo.RepositorySourceLocation = manifestInfo.RepositorySourceLocation;
                newManifestInfo.IsConsideredEditionCompatible = manifestInfo.IsConsideredEditionCompatible;

                newManifestInfo.ExperimentalFeatures = manifestInfo.ExperimentalFeatures;

                // If we are in module discovery, then fix the path.
                if (ss == null)
                {
                    newManifestInfo.Path = manifestInfo.Path;
                }

                if (string.IsNullOrEmpty(newManifestInfo.Author))
                {
                    newManifestInfo.Author = author;
                }

                if (string.IsNullOrEmpty(newManifestInfo.CompanyName))
                {
                    newManifestInfo.CompanyName = companyName;
                }

                if (string.IsNullOrEmpty(newManifestInfo.Copyright))
                {
                    newManifestInfo.Copyright = copyright;
                }

                if (newManifestInfo.PowerShellVersion == null)
                {
                    newManifestInfo.PowerShellVersion = powerShellVersion;
                }

                if (string.IsNullOrEmpty(newManifestInfo.PowerShellHostName))
                {
                    newManifestInfo.PowerShellHostName = requestedHostName;
                }

                if (newManifestInfo.PowerShellHostVersion == null)
                {
                    newManifestInfo.PowerShellHostVersion = requestedHostVersion;
                }

                if (newManifestInfo.DotNetFrameworkVersion == null)
                {
                    newManifestInfo.DotNetFrameworkVersion = requestedDotNetFrameworkVersion;
                }

                if (newManifestInfo.ClrVersion == null)
                {
                    newManifestInfo.ClrVersion = requestedClrVersion;
                }

                if (string.IsNullOrEmpty(newManifestInfo.Prefix))
                {
                    newManifestInfo.Prefix = resolvedCommandPrefix;
                }

                if (newManifestInfo.FileList == null || !newManifestInfo.FileList.Any())
                {
                    if (fileList != null)
                    {
                        foreach (var f in fileList)
                        {
                            newManifestInfo.AddToFileList(f);
                        }
                    }
                }

                if (newManifestInfo.ModuleList == null || !newManifestInfo.ModuleList.Any())
                {
                    if (moduleList != null)
                    {
                        foreach (var m in moduleList)
                        {
                            newManifestInfo.AddToModuleList(m);
                        }
                    }
                }

                if (newManifestInfo.CompatiblePSEditions == null || !newManifestInfo.CompatiblePSEditions.Any())
                {
                    if (compatiblePSEditions != null)
                    {
                        newManifestInfo.AddToCompatiblePSEditions(compatiblePSEditions);
                    }
                }

                if (newManifestInfo.ProcessorArchitecture == ProcessorArchitecture.None)
                {
                    newManifestInfo.ProcessorArchitecture = requiredProcessorArchitecture;
                }

                if (newManifestInfo.RequiredAssemblies == null || !newManifestInfo.RequiredAssemblies.Any())
                {
                    if (assemblyList != null)
                    {
                        foreach (var a in assemblyList)
                        {
                            newManifestInfo.AddRequiredAssembly(a);
                        }
                    }
                }

                if (newManifestInfo.Scripts == null || !newManifestInfo.Scripts.Any())
                {
                    if (scriptsToProcess != null)
                    {
                        foreach (var s in scriptsToProcess)
                        {
                            newManifestInfo.AddScript(s);
                        }
                    }
                }

                newManifestInfo.RootModuleForManifest ??= manifestInfo.RootModuleForManifest;

                if (newManifestInfo.DeclaredCmdletExports == null || newManifestInfo.DeclaredCmdletExports.Count == 0)
                {
                    newManifestInfo.DeclaredCmdletExports = manifestInfo.DeclaredCmdletExports;
                }

                if (manifestInfo.DetectedCmdletExports != null)
                {
                    foreach (string detectedExport in manifestInfo.DetectedCmdletExports)
                    {
                        newManifestInfo.AddDetectedCmdletExport(detectedExport);
                    }
                }

                if (newManifestInfo.DeclaredFunctionExports == null ||
                    newManifestInfo.DeclaredFunctionExports.Count == 0)
                {
                    newManifestInfo.DeclaredFunctionExports = manifestInfo.DeclaredFunctionExports;
                }

                if (manifestInfo.DetectedFunctionExports != null)
                {
                    foreach (string detectedExport in manifestInfo.DetectedFunctionExports)
                    {
                        newManifestInfo.AddDetectedFunctionExport(detectedExport);
                    }
                }

                if (newManifestInfo.DeclaredAliasExports == null || newManifestInfo.DeclaredAliasExports.Count == 0)
                {
                    newManifestInfo.DeclaredAliasExports = manifestInfo.DeclaredAliasExports;
                }

                if (manifestInfo.DetectedAliasExports != null)
                {
                    foreach (var pair in manifestInfo.DetectedAliasExports)
                    {
                        newManifestInfo.AddDetectedAliasExport(pair.Key, pair.Value);
                    }
                }

                if (newManifestInfo.DeclaredVariableExports == null ||
                    newManifestInfo.DeclaredVariableExports.Count == 0)
                {
                    newManifestInfo.DeclaredVariableExports = manifestInfo.DeclaredVariableExports;
                }

                // If there are types/formats entries in the ModuleToProcess use them
                // only if there are no entries from the manifest. The manifest entries
                // completely override the module's entries.
                if (manifestInfo.ExportedTypeFiles.Count > 0)
                {
                    newManifestInfo.SetExportedTypeFiles(manifestInfo.ExportedTypeFiles);
                }

                if (manifestInfo.ExportedFormatFiles.Count > 0)
                {
                    newManifestInfo.SetExportedFormatFiles(manifestInfo.ExportedFormatFiles);
                }

                // And switch to using the new manifest info
                manifestInfo = newManifestInfo;

                // mark the binary module exports...
                if (manifestInfo.ModuleType == ModuleType.Binary)
                {
                    if ((exportedCmdlets != null) && (ss != null))
                    {
                        manifestInfo.ExportedCmdlets.Clear();

                        // Mark stuff for export
                        if (ss != null)
                        {
                            ModuleIntrinsics.ExportModuleMembers(
                                this,
                                ss.Internal,
                                exportedFunctions,
                                exportedCmdlets,
                                exportedAliases,
                                exportedVariables,
                                doNotExportCmdlets: null);
                        }
                    }
                }
                else
                {
                    // If the script didn't call Export-ModuleMember explicitly, then
                    // implicitly export functions and cmdlets.
                    if ((ss != null) && (!ss.Internal.UseExportList))
                    {
                        // For cross language boundaries, implicitly import all functions only if
                        // this manifest *does* export functions explicitly.
                        List<WildcardPattern> fnMatchPattern = (
                                                                (manifestScriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) &&
                                                                (Context.LanguageMode != PSLanguageMode.FullLanguage) &&
                                                                (exportedFunctions == null)
                                                                ) ? null : MatchAll;

                        // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied.
                        if (fnMatchPattern == null && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit)
                        {
                            SystemPolicy.LogWDACAuditMessage(
                                context: Context,
                                title: Modules.WDACImplicitFunctionExportLogTitle,
                                message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, manifestScriptInfo.ModuleName),
                                fqid: "ModuleImplicitFunctionExportNotAllowed",
                                dropIntoDebugger: true);
                            fnMatchPattern = MatchAll;
                        }

                        ModuleIntrinsics.ExportModuleMembers(cmdlet: this,
                                                             sessionState: ss.Internal,
                                                             functionPatterns: fnMatchPattern,
                                                             cmdletPatterns: MatchAll,
                                                             aliasPatterns: null,
                                                             variablePatterns: null,
                                                             doNotExportCmdlets: null);
                    }

                    // Export* fields in .psd1 subset Export-ModuleMember calls from ModuleToProcess=psm1
                    if (exportedFunctions != null)
                    {
                        if (ss != null)
                        {
                            // If module (psm1) functions were not exported because of cross language boundary restrictions,
                            // then implicitly export them here so that they can be filtered by the exportedFunctions list.
                            // Unless exportedFunctions contains the wildcard character that isn't allowed across language
                            // boundaries.
                            if (!ss.Internal.FunctionsExported && !exportedFunctionsContainsWildcards)
                            {
                                ModuleIntrinsics.ExportModuleMembers(
                                    cmdlet: this,
                                    sessionState: ss.Internal,
                                    functionPatterns: MatchAll,
                                    cmdletPatterns: null,
                                    aliasPatterns: null,
                                    variablePatterns: null,
                                    doNotExportCmdlets: null);
                            }

                            Dbg.Assert(ss.Internal.ExportedFunctions != null,
                                "ss.Internal.ExportedFunctions should not be null");

                            // Update the exports to only contain things that are also in the manifest export list
                            UpdateCommandCollection<FunctionInfo>(ss.Internal.ExportedFunctions, exportedFunctions);
                        }
                        else
                        {
                            UpdateCommandCollection(manifestInfo.DeclaredFunctionExports, exportedFunctions);
                        }
                    }

                    if (exportedCmdlets != null)
                    {
                        if (ss != null)
                        {
                            Dbg.Assert(ss.Internal.ExportedCmdlets != null,
                                "ss.Internal.ExportedCmdlets should not be null");

                            // Update the exports to only contain things that are also in the manifest export list
                            UpdateCommandCollection<CmdletInfo>(manifestInfo.CompiledExports, exportedCmdlets);
                        }
                        else
                        {
                            UpdateCommandCollection(manifestInfo.DeclaredCmdletExports, exportedCmdlets);
                        }
                    }

                    if (exportedAliases != null)
                    {
                        if (ss != null)
                        {
                            Dbg.Assert(ss.Internal.ExportedAliases != null,
                                "ss.Internal.ExportedAliases should not be null");

                            // Update the exports to only contain things that are also in the manifest export list
                            UpdateCommandCollection<AliasInfo>(ss.Internal.ExportedAliases, exportedAliases);
                        }
                        else
                        {
                            UpdateCommandCollection(manifestInfo.DeclaredAliasExports, exportedAliases);
                        }
                    }

                    if (exportedVariables != null)
                    {
                        if (ss != null)
                        {
                            Dbg.Assert(ss.Internal.ExportedVariables != null,
                                       "ss.Internal.ExportedVariables should not be null");

                            // Update the exports to only contain things that are also in the manifest export list
                            List<PSVariable> updated = new List<PSVariable>();
                            foreach (PSVariable element in ss.Internal.ExportedVariables)
                            {
                                if (SessionStateUtilities.MatchesAnyWildcardPattern(
                                        element.Name,
                                        exportedVariables,
                                        defaultValue: false))
                                {
                                    updated.Add(element);
                                }
                            }

                            ss.Internal.ExportedVariables.Clear();
                            ss.Internal.ExportedVariables.AddRange(updated);
                        }
                    }
                }
            }
            else
            {
                if (ss != null)
                {
                    // In the case where there are only nested modules,
                    // the members of the manifest are canonical...
                    ModuleIntrinsics.ExportModuleMembers(
                        this,
                        sessionState: ss.Internal,
                        functionPatterns: exportedFunctions,
                        cmdletPatterns: exportedCmdlets,
                        aliasPatterns: exportedAliases,
                        variablePatterns: exportedVariables,
                        doNotExportCmdlets: null);
                }
            }

            PropagateExportedTypesFromNestedModulesToRootModuleScope(options, manifestInfo);
            SetDeclaredDscResources(exportedDscResources, manifestInfo);

            // And import the members from this module into the callers context...
            if (importingModule)
            {
                ImportModuleMembers(manifestInfo, resolvedCommandPrefix, options);
            }

            manifestInfo.LanguageMode = (manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode : (PSLanguageMode?)null;

            return manifestInfo;
        }

        private static void PropagateExportedTypesFromNestedModulesToRootModuleScope(ImportModuleOptions options, PSModuleInfo manifestInfo)
        {
            if (manifestInfo.NestedModules == null)
            {
                return;
            }

            if (manifestInfo.SessionState == null)
            {
                // i.e. Get-Module -ListAvailable, there is no state.
                return;
            }

            var scope = options.Local
                        ? manifestInfo.SessionState.Internal.CurrentScope
                        : manifestInfo.SessionState.Internal.ModuleScope;

            // The last one name wins! It's the same for command names in nested modules.
            // For rootModule C with Two nested modules (A, B) the order is: A, B, C
            // We re-adding rootModule types to the scope again to override any possible name collision.
            var modulesToProcess = manifestInfo.NestedModules.ToList();
            modulesToProcess.Add(manifestInfo);

            foreach (var nestedModule in modulesToProcess)
            {
                if (nestedModule != null)
                {
                    var exportedTypes = nestedModule.GetExportedTypeDefinitions();
                    if (exportedTypes != null && exportedTypes.Count > 0)
                    {
                        foreach (var t in exportedTypes)
                        {
                            scope.AddType(t.Key, t.Value.Type);
                        }
                    }
                }
            }
        }

        private static void SetDeclaredDscResources(List<WildcardPattern> exportedDscResources, PSModuleInfo manifestInfo)
        {
            if (exportedDscResources != null)
            {
                manifestInfo._declaredDscResourceExports = new Collection<string>();

                if (exportedDscResources.Count > 0)
                {
                    foreach (WildcardPattern p in exportedDscResources)
                    {
                        string name = p.Pattern;
                        if (!WildcardPattern.ContainsWildcardCharacters(name))
                        {
                            manifestInfo._declaredDscResourceExports.Add(name);
                        }
                    }
                }
            }

            // if it is empty it means there is a wildcard pattern
            if (manifestInfo._declaredDscResourceExports != null && manifestInfo._declaredDscResourceExports.Count == 0)
            {
                var exportedTypes = manifestInfo.GetExportedTypeDefinitions();
                var exportedClassDscResources = exportedTypes.Values.Where(typeAst =>
                {
                    for (int i = 0; i < typeAst.Attributes.Count; i++)
                    {
                        var a = typeAst.Attributes[i];
                        if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))
                        {
                            return true;
                        }
                    }

                    return false;
                });
                foreach (var exportedResource in exportedClassDscResources)
                {
                    manifestInfo._declaredDscResourceExports.Add(exportedResource.Name);
                }
            }
        }

        private static void UpdateCommandCollection<T>(List<T> list, List<WildcardPattern> patterns) where T : CommandInfo
        {
            List<T> updated = new List<T>();
            foreach (T element in list)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, patterns, false))
                {
                    updated.Add(element);
                }
            }

            list.Clear();
            list.AddRange(updated);
        }

        private static void UpdateCommandCollection(Collection<string> list, List<WildcardPattern> patterns)
        {
            if (list == null)
            {
                return;
            }

            List<string> updated = new List<string>();

            // Add any patterns that don't have wildcard characters - they
            // may have been declared but then created in a way that we couldn't detect
            // them statically
            foreach (WildcardPattern pattern in patterns)
            {
                if (!WildcardPattern.ContainsWildcardCharacters(pattern.Pattern))
                {
                    if (!list.Contains(pattern.Pattern, StringComparer.OrdinalIgnoreCase))
                    {
                        list.Add(pattern.Pattern);
                    }
                }
            }

            foreach (string element in list)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(element, patterns, false))
                {
                    updated.Add(element);
                }
            }

            list.Clear();

            foreach (string element in updated)
            {
                list.Add(element);
            }
        }

        private static void WriteInvalidManifestMemberError(
            PSCmdlet cmdlet,
            string manifestElement,
            string moduleManifestPath,
            Exception e,
            ManifestProcessingFlags manifestProcessingFlags)
        {
            if ((manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0)
            {
                ErrorRecord er = GenerateInvalidModuleMemberErrorRecord(manifestElement, moduleManifestPath, e);
                cmdlet.WriteError(er);
            }
        }

        private static ErrorRecord GenerateInvalidModuleMemberErrorRecord(string manifestElement, string moduleManifestPath, Exception e)
        {
            string message = StringUtil.Format(Modules.ModuleManifestInvalidManifestMember, manifestElement, e.Message, moduleManifestPath);
            ArgumentException newAe = new ArgumentException(message);
            ErrorRecord er = new ErrorRecord(newAe, "Modules_InvalidManifest",
                ErrorCategory.ResourceUnavailable, moduleManifestPath);
            return er;
        }

        /// <summary>
        /// Check if a module has been loaded.
        /// If loadElements is false, we check requireModule for correctness but do
        /// not check if the modules are loaded.
        /// </summary>
        /// <param name="context">Execution Context.</param>
        /// <param name="requiredModule">Either a string or a hash of ModuleName, optional Guid, and ModuleVersion.</param>
        /// <param name="matchFailureReason">The reason the module failed to load, or null on success.</param>
        /// <param name="loaded">Sets if the module/snapin is already present.</param>
        /// <returns>Null if the module is not loaded or loadElements is false, the loaded module otherwise.</returns>
        internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecification requiredModule, out ModuleMatchFailure matchFailureReason, out bool loaded)
        {
            loaded = false;
            Dbg.Assert(requiredModule != null, "Caller should verify requiredModuleSpecification != null");

            // Assume the module is not loaded.
            object result = null;

            Dbg.Assert(requiredModule.Name != null, "GetModuleSpecification should guarantee that moduleName != null");
            ModuleMatchFailure matchFailure = ModuleMatchFailure.None;
            foreach (PSModuleInfo module in context.Modules.GetModules(new string[] { "*" }, false))
            {
                // Check that the module meets the module constraints give
                if (ModuleIntrinsics.IsModuleMatchingModuleSpec(out matchFailure, module, requiredModule))
                {
                    result = module;
                    loaded = true;
                    break;
                }
            }

            // If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using InitialSessionState.CreateDefault())
            if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name))
            {
                result = context.CurrentRunspace.InitialSessionState.GetPSSnapIn(requiredModule.Name);
                if (result != null)
                {
                    loaded = true;
                }
            }

            matchFailureReason = matchFailure;
            return result;
        }

        /// <summary>
        /// Check if a module has been loaded.
        /// If loadElements is false, we check requireModule for correctness but do
        /// not check if the modules are loaded.
        /// </summary>
        /// <param name="currentModule">The current module being loaded.</param>
        /// <param name="requiredModule">Either a string or a hash of ModuleName, optional Guid, and ModuleVersion.</param>
        /// <param name="moduleManifestPath">Used for error messages.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="containedErrors">Set if any errors are found.</param>
        /// <param name="error">Contains error record information.</param>
        /// <returns>Null if the module is not loaded or loadElements is false, the loaded module otherwise.</returns>
        internal PSModuleInfo LoadRequiredModule(PSModuleInfo currentModule, ModuleSpecification requiredModule, string moduleManifestPath, ManifestProcessingFlags manifestProcessingFlags, bool containedErrors, out ErrorRecord error)
        {
            Dbg.Assert(moduleManifestPath != null, "Caller should verify moduleManifestPath != null");
            error = null;
            if (!containedErrors)
            {
                return LoadRequiredModule(Context, currentModule, requiredModule, moduleManifestPath, manifestProcessingFlags, out error);
            }

            return null;
        }

        /// <summary>
        /// Check if a module has been loaded.
        /// If loadElements is false, we check requireModule for correctness but do
        /// not check if the modules are loaded.
        /// </summary>
        /// <param name="context">Execution Context.</param>
        /// <param name="currentModule">The current module being loaded.</param>
        /// <param name="requiredModuleSpecification">Either a string or a hash of ModuleName, optional Guid, and ModuleVersion.</param>
        /// <param name="moduleManifestPath">Used for error messages.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="error">Contains error record information.</param>
        /// <returns>Null if the module is not loaded or loadElements is false, the loaded module otherwise.</returns>
        internal static PSModuleInfo LoadRequiredModule(ExecutionContext context,
            PSModuleInfo currentModule,
            ModuleSpecification requiredModuleSpecification,
            string moduleManifestPath,
            ManifestProcessingFlags manifestProcessingFlags,
            out ErrorRecord error)
        {
            Dbg.Assert((manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0, "LoadRequiredModule / RequiredModules checks should only be done when actually loading a module");

            error = null;

            string moduleName = requiredModuleSpecification.Name;
            Guid? moduleGuid = requiredModuleSpecification.Guid;
            PSModuleInfo result = null;

            ModuleMatchFailure loadFailureReason = ModuleMatchFailure.None;
            bool loaded = false;
            object loadedModule = IsModuleLoaded(context, requiredModuleSpecification, out loadFailureReason, out loaded);

            if (loadedModule == null)
            {
                // Load the module
                PSModuleInfo requiredModuleInfo = null;
                Collection<PSModuleInfo> moduleInfo = GetModuleIfAvailable(requiredModuleSpecification);

                if (moduleInfo != null && moduleInfo.Count > 0)
                {
                    requiredModuleInfo = moduleInfo[0];

                    // Check for cyclic references of RequiredModule
                    bool hasRequiredModulesCyclicReference = false;
                    Dictionary<ModuleSpecification, List<ModuleSpecification>> requiredModules = new Dictionary<ModuleSpecification, List<ModuleSpecification>>(new ModuleSpecificationComparer());
                    if (currentModule != null)
                    {
                        requiredModules.Add(new ModuleSpecification(currentModule), new List<ModuleSpecification> { requiredModuleSpecification });
                    }

                    if (requiredModuleSpecification != null)
                    {
                        requiredModules.Add(requiredModuleSpecification, new List<ModuleSpecification>(requiredModuleInfo.RequiredModulesSpecification));
                    }

                    // We always need to check against the module name and not the file name
                    hasRequiredModulesCyclicReference = HasRequiredModulesCyclicReference(requiredModuleSpecification,
                                                                                          new List<ModuleSpecification>(requiredModuleInfo.RequiredModulesSpecification),
                                                                                          new Collection<PSModuleInfo> { requiredModuleInfo },
                                                                                          requiredModules,
                                                                                          out error);
                    if (!hasRequiredModulesCyclicReference)
                    {
                        result = ImportRequiredModule(context, requiredModuleSpecification, out error);
                    }
                    else
                    {
                        // Error Record
                        if (moduleManifestPath != null)
                        {
                            Dbg.Assert(error != null, "Error message should be populated if there is cyclic dependency");
                            MissingMemberException mm = null;
                            if (error != null && error.Exception != null)
                            {
                                mm = new MissingMemberException(error.Exception.Message);
                            }

                            error = new ErrorRecord(mm, "Modules_InvalidManifest",
                                                    ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        }
                    }
                }
                else
                {
                    string message;
                    if (moduleManifestPath != null)
                    {
                        if ((manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0)
                        {
                            switch (loadFailureReason)
                            {
                                case ModuleMatchFailure.RequiredVersion:
                                    message = StringUtil.Format(
                                        Modules.RequiredModuleNotLoadedWrongVersion,
                                        moduleManifestPath,
                                        moduleName,
                                        requiredModuleSpecification.RequiredVersion);
                                    break;

                                case ModuleMatchFailure.MinimumVersion:
                                    // If both max and min versions were specified, use a different error message
                                    if (requiredModuleSpecification.MaximumVersion == null)
                                    {
                                        message = StringUtil.Format(
                                            Modules.RequiredModuleNotLoadedWrongVersion,
                                            moduleManifestPath, moduleName,
                                            requiredModuleSpecification.Version);
                                    }
                                    else
                                    {
                                        message = StringUtil.Format(
                                            Modules.RequiredModuleNotLoadedWrongMinimumVersionAndMaximumVersion,
                                            moduleManifestPath,
                                            moduleName,
                                            requiredModuleSpecification.Version,
                                            requiredModuleSpecification.MaximumVersion);
                                    }

                                    break;

                                case ModuleMatchFailure.MaximumVersion:
                                    // If both max and min versions were specified, use a different error message
                                    if (requiredModuleSpecification.Version == null)
                                    {
                                        message = StringUtil.Format(
                                            Modules.RequiredModuleNotLoadedWrongMaximumVersion,
                                            moduleManifestPath,
                                            moduleName,
                                            requiredModuleSpecification.MaximumVersion);
                                    }
                                    else
                                    {
                                        message = StringUtil.Format(
                                            Modules.RequiredModuleNotLoadedWrongMinimumVersionAndMaximumVersion,
                                            moduleManifestPath,
                                            moduleName,
                                            requiredModuleSpecification.Version,
                                            requiredModuleSpecification.MaximumVersion);
                                    }

                                    break;

                                case ModuleMatchFailure.Guid:
                                    message = StringUtil.Format(
                                        Modules.RequiredModuleNotLoadedWrongGuid,
                                        moduleManifestPath,
                                        moduleName,
                                        moduleGuid.Value);
                                    break;

                                default:
                                    message = StringUtil.Format(
                                        Modules.RequiredModuleNotLoaded,
                                        moduleManifestPath,
                                        moduleName);
                                    break;
                            }

                            MissingMemberException mm = new MissingMemberException(message);
                            error = new ErrorRecord(mm, "Modules_InvalidManifest",
                                                    ErrorCategory.ResourceUnavailable, moduleManifestPath);
                        }
                    }
                    else
                    {
                        message = StringUtil.Format(Modules.RequiredModuleNotFound, requiredModuleSpecification.Name);
                        MissingMemberException mm = new MissingMemberException(message);
                        error = new ErrorRecord(mm, "Modules_RequiredModuleNotFound", ErrorCategory.ResourceUnavailable, null);
                    }
                }
            }
            else
            {
                // Either module/snapin is already loaded
                if (loadedModule is PSModuleInfo)
                {
                    result = (PSModuleInfo)loadedModule;
                }
                else if (!loaded)
                {
                    // This should never happen because one of the two should be true
                    // 1) loadedModule should either be PSModuleInfo
                    // 2) loaded = true
                    Dbg.Assert(false, "loadedModule should either be PSModuleInfo or loaded should be true");
                }
            }

            return result;
        }

        private static PSModuleInfo ImportRequiredModule(ExecutionContext context, ModuleSpecification requiredModule, out ErrorRecord error)
        {
            error = null;
            PSModuleInfo result = null;
            using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powerShell.AddCommand("Import-Module");
                powerShell.AddParameter("Name", requiredModule.Name);

                if (requiredModule.RequiredVersion != null)
                {
                    powerShell.AddParameter("RequiredVersion", requiredModule.RequiredVersion);
                }
                else if (requiredModule.MaximumVersion != null)
                {
                    powerShell.AddParameter("MaximumVersion", requiredModule.MaximumVersion);
                }
                else
                {
                    powerShell.AddParameter("Version", requiredModule.Version);
                }

                powerShell.Invoke();
                if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0)
                {
                    error = powerShell.Streams.Error[0];
                }
                else
                {
                    // Check if the correct module is loaded using Version , Guid Information.
                    string moduleNameToCheckAgainst = requiredModule.Name;
                    string manifestPath = string.Empty;
                    if (moduleNameToCheckAgainst.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
                    {
                        manifestPath = moduleNameToCheckAgainst;
                        moduleNameToCheckAgainst = Path.GetFileNameWithoutExtension(moduleNameToCheckAgainst);
                    }

                    ModuleSpecification ms = new ModuleSpecification(moduleNameToCheckAgainst);
                    if (requiredModule.Guid != null)
                    {
                        ms.Guid = requiredModule.Guid.Value;
                    }

                    if (requiredModule.RequiredVersion != null)
                    {
                        ms.RequiredVersion = requiredModule.RequiredVersion;
                    }

                    if (requiredModule.Version != null)
                    {
                        ms.Version = requiredModule.Version;
                    }

                    if (requiredModule.MaximumVersion != null)
                    {
                        ms.MaximumVersion = requiredModule.MaximumVersion;
                    }

                    ModuleMatchFailure loadFailureReason;
                    bool loaded = false;
                    object r = IsModuleLoaded(context, ms, out loadFailureReason, out loaded);

                    Dbg.Assert(r is PSModuleInfo, "The returned value should be PSModuleInfo");

                    result = r as PSModuleInfo;
                    if (result == null)
                    {
                        string message = StringUtil.Format(Modules.RequiredModuleNotFound, moduleNameToCheckAgainst);
                        if (!string.IsNullOrEmpty(manifestPath))
                        {
                            MissingMemberException mm = new MissingMemberException(message);
                            error = new ErrorRecord(mm, "Modules_InvalidManifest",
                                                    ErrorCategory.ResourceUnavailable, manifestPath);
                        }
                        else
                        {
                            InvalidOperationException ioe = new InvalidOperationException(message);
                            error = new ErrorRecord(ioe, "Modules_RequiredModuleNotLoadedWithoutManifest", ErrorCategory.InvalidOperation, requiredModule);
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Verifies if a nested module is available using GetModuleIfAvailable.
        /// <paramref name="extension"/> and <paramref name="rootedModulePath"/>
        /// will be used to create module name for searching.
        /// If <paramref name="rootedModulePath"/> is null, the name specified in
        /// nestedModuleSpec will be used.
        /// </summary>
        /// <param name="nestedModuleSpec"></param>
        /// <param name="rootedModulePath"></param>
        /// <param name="extension"></param>
        /// <param name="nestedModuleInfoIfAvailable"></param>
        /// <returns></returns>
        internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSpec,
            string rootedModulePath,
            string extension,
            out PSModuleInfo nestedModuleInfoIfAvailable)
        {
            Dbg.Assert(nestedModuleSpec != null, "nestedModuleSpec cannot be null.");
            nestedModuleInfoIfAvailable = null;
            if ((nestedModuleSpec.Guid != null) || (nestedModuleSpec.Version != null) || (nestedModuleSpec.RequiredVersion != null) || (nestedModuleSpec.MaximumVersion != null))
            {
                if (!string.IsNullOrEmpty(extension) &&
                    (!string.Equals(extension, StringLiterals.PowerShellDataFileExtension)))
                {
                    // A module can declare its GUID/Version only in the PSD1 file.
                    return false;
                }

                string tempModuleName = rootedModulePath;
                if (string.IsNullOrEmpty(extension))
                {
                    tempModuleName = rootedModulePath + StringLiterals.PowerShellDataFileExtension;
                }

                ModuleSpecification tempSpec = new ModuleSpecification(
                    string.IsNullOrEmpty(rootedModulePath) ? nestedModuleSpec.Name : tempModuleName);
                if (nestedModuleSpec.Guid.HasValue)
                {
                    tempSpec.Guid = nestedModuleSpec.Guid.Value;
                }

                if (nestedModuleSpec.Version != null)
                {
                    tempSpec.Version = nestedModuleSpec.Version;
                }

                if (nestedModuleSpec.RequiredVersion != null)
                {
                    tempSpec.RequiredVersion = nestedModuleSpec.RequiredVersion;
                }

                if (nestedModuleSpec.MaximumVersion != null)
                {
                    tempSpec.MaximumVersion = nestedModuleSpec.MaximumVersion;
                }

                Collection<PSModuleInfo> availableModules = GetModuleIfAvailable(tempSpec);

                // With Side-b-Side module version support, more than one module will be returned by GetModuleIfAvailable
                if (availableModules.Count < 1)
                {
                    return false;
                }

                // First element is the highest available version under a module base folder
                nestedModuleInfoIfAvailable = availableModules[0];
            }

            return true;
        }

        // Checks if module is available to be loaded
        // ModuleName ---> checks if module can be loaded using Module loading rules
        // ModuleManifest --> checks if manifest is valid
        internal static Collection<PSModuleInfo> GetModuleIfAvailable(ModuleSpecification requiredModule,
            Runspace rsToUse = null)
        {
            Collection<PSModuleInfo> result = new Collection<PSModuleInfo>();
            Collection<PSModuleInfo> tempResult = null;
            System.Management.Automation.PowerShell powerShell = null;
            if (rsToUse == null)
            {
                powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
            }
            else
            {
                powerShell = System.Management.Automation.PowerShell.Create();
                powerShell.Runspace = rsToUse;
            }

            using (powerShell)
            {
                if (requiredModule.Name.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
                {
                    powerShell.AddCommand("Test-ModuleManifest");
                    powerShell.AddParameter("Path", requiredModule.Name);
                }
                else
                {
                    powerShell.AddCommand("Get-Module");
                    powerShell.AddParameter("Name", requiredModule.Name);
                    powerShell.AddParameter("ListAvailable");
                }

                tempResult = powerShell.Invoke<PSModuleInfo>();
            }

            // Check if the available module is of the correct version and GUID. The name is already checked.
            // GH #8204: The required name here may be the full path, while the module name may be just the module,
            //           so comparing them may fail incorrectly.
            foreach (var module in tempResult)
            {
                if (ModuleIntrinsics.IsModuleMatchingConstraints(
                    module,
                    guid: requiredModule.Guid,
                    requiredVersion: requiredModule.RequiredVersion,
                    minimumVersion: requiredModule.Version,
                    maximumVersion: requiredModule.MaximumVersion == null ? null : GetMaximumVersion(requiredModule.MaximumVersion)))
                {
                    result.Add(module);
                }
            }

            return result;
        }

        private static bool HasRequiredModulesCyclicReference(ModuleSpecification currentModuleSpecification, List<ModuleSpecification> requiredModules, IEnumerable<PSModuleInfo> moduleInfoList, Dictionary<ModuleSpecification, List<ModuleSpecification>> nonCyclicRequiredModules, out ErrorRecord error)
        {
            error = null;
            if (requiredModules == null || requiredModules.Count == 0 || currentModuleSpecification == null)
            {
                return false;
            }

            foreach (var requiredModuleSpecification in requiredModules)
            {
                // The dictionary holds the key-value pair with the following convention
                // Key --> Module
                // Values --> RequiredModules
                // If we find that the module we are trying to import is already present in the dictionary, there is a cyclic reference

                // No cycle
                // 1---->2------>3-------->4
                //       |--> 5             |--> 5

                // Cycle
                // 1 --->2---->3---->4---> 2
                if (nonCyclicRequiredModules.ContainsKey(requiredModuleSpecification))
                {
                    // Error out saying there is a cyclic reference
                    PSModuleInfo mo = null;
                    foreach (var i in moduleInfoList)
                    {
                        if (i.Name.Equals(currentModuleSpecification.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            mo = i;
                            break;
                        }
                    }

                    Dbg.Assert(mo != null, "The moduleInfo should be present");
                    string message = StringUtil.Format(Modules.RequiredModulesCyclicDependency, currentModuleSpecification.ToString(), requiredModuleSpecification.ToString(), mo.Path);
                    MissingMemberException mm = new MissingMemberException(message);
                    error = new ErrorRecord(mm, "Modules_InvalidManifest", ErrorCategory.ResourceUnavailable, mo.Path);
                    return true;
                }
                else // Go for recursive check for the RequiredModules of current requiredModuleSpecification
                {
                    Collection<PSModuleInfo> availableModules = GetModuleIfAvailable(requiredModuleSpecification);
                    if (availableModules.Count == 1)
                    {
                        List<ModuleSpecification> list = new List<ModuleSpecification>(availableModules[0].RequiredModulesSpecification);
                        // Only add if this required module has nested required modules (meaning, it could lead to a circular reference)
                        if (list.Count > 0)
                        {
                            nonCyclicRequiredModules.Add(requiredModuleSpecification, list);
                            // We always need to check against the module specification and not the file name
                            if (HasRequiredModulesCyclicReference(requiredModuleSpecification, list, availableModules, nonCyclicRequiredModules, out error))
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            // Once nested recursive calls are complete, we should remove the current module from the nonCyclicRequiredModules check list.
            // This prevents non related modules from getting involved in the cycle list.
            nonCyclicRequiredModules.Remove(currentModuleSpecification); // this uses ModuleSpecificationComparer equality comparer
            return false;
        }

        /// <summary>
        /// Search for a localized psd1 manifest file, using the same algorithm
        /// as Import-LocalizedData.
        /// </summary>
        private static ExternalScriptInfo FindLocalizedModuleManifest(string path)
        {
            string dir = Path.GetDirectoryName(path);
            string file = Path.GetFileName(path);
            string localizedFile = null;

            CultureInfo culture = System.Globalization.CultureInfo.CurrentUICulture;
            CultureInfo currentCulture = culture;
            while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name))
            {
                StringBuilder stringBuilder = new StringBuilder(dir);
                stringBuilder.Append('\\');
                stringBuilder.Append(currentCulture.Name);
                stringBuilder.Append('\\');
                stringBuilder.Append(file);

                string filePath = stringBuilder.ToString();

                if (File.Exists(filePath))
                {
                    localizedFile = filePath;
                    break;
                }

                currentCulture = currentCulture.Parent;
            }

            ExternalScriptInfo result = null;
            if (localizedFile != null)
            {
                result = new ExternalScriptInfo(Path.GetFileName(localizedFile), localizedFile);
            }

            return result;
        }

        /// <summary>
        /// Checks to see if the module manifest contains the specified key.
        /// If it does and it's valid, it returns true otherwise it returns false.
        /// If the key wasn't there or wasn't valid, then <paramref name="list"/> is set to <see langword="null"/>
        /// </summary>
        /// <param name="data">The hashtable to look for the key in.</param>
        /// <param name="moduleManifestPath">The manifest that generated the hashtable.</param>
        /// <param name="key">The table key to use.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="list">Returns the extracted version.</param>
        /// <returns></returns>
        internal bool GetListOfStringsFromData(
            Hashtable data,
            string moduleManifestPath,
            string key,
            ManifestProcessingFlags manifestProcessingFlags,
            out List<string> list)
        {
            list = null;
            if (data.Contains(key))
            {
                if (data[key] != null)
                {
                    try
                    {
                        string[] stringData = (string[])LanguagePrimitives.ConvertTo(data[key], typeof(string[]), CultureInfo.InvariantCulture);
                        list = new List<string>(stringData);
                    }
                    catch (Exception e)
                    {
                        WriteInvalidManifestMemberError(this, key, moduleManifestPath, e, manifestProcessingFlags);
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Checks to see if the module manifest contains the specified key.
        /// If it does and it's valid, it returns true otherwise it returns false.
        /// If the key wasn't there or wasn't valid, then <paramref name="list"/> is set to <see langword="null"/>.
        /// </summary>
        /// <param name="data">The hashtable to look for the key in.</param>
        /// <param name="moduleManifestPath">The manifest that generated the hashtable.</param>
        /// <param name="key">The table key to use.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="list">Returns the extracted version.</param>
        /// <returns></returns>
        private bool GetListOfWildcardsFromData(
            Hashtable data,
            string moduleManifestPath,
            string key,
            ManifestProcessingFlags manifestProcessingFlags,
            out List<WildcardPattern> list)
        {
            list = null;

            List<string> listOfStrings;
            if (!GetListOfStringsFromData(data, moduleManifestPath, key, manifestProcessingFlags, out listOfStrings))
            {
                return false;
            }

            if (listOfStrings != null)
            {
                list = new List<WildcardPattern>();
                foreach (string s in listOfStrings)
                {
                    // Win8: 622263
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }

                    try
                    {
                        list.Add(WildcardPattern.Get(s, WildcardOptions.IgnoreCase));
                    }
                    catch (Exception e)
                    {
                        list = null;
                        WriteInvalidManifestMemberError(this, key, moduleManifestPath, e, manifestProcessingFlags);
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Checks to see if the module manifest contains the specified key.
        /// If it does and it's valid, it returns true otherwise it returns false.
        /// If the key wasn't there or wasn't valid, then <paramref name="list"/> is set to <see langword="null"/>
        /// </summary>
        /// <param name="data">The hashtable to look for the key in.</param>
        /// <param name="moduleManifestPath">The manifest that generated the hashtable.</param>
        /// <param name="key">The table key to use.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="moduleBase">Base directory of a module.</param>
        /// <param name="extension">Expected file extension (added to strings that didn't have an extension).</param>
        /// <param name="verifyFilesExist">If <see langword="true"/> then we want to error out if the specified files don't exist.</param>
        /// <param name="list">Returns the extracted version.</param>
        /// <returns></returns>
        private bool GetListOfFilesFromData(
            Hashtable data,
            string moduleManifestPath,
            string key,
            ManifestProcessingFlags manifestProcessingFlags,
            string moduleBase,
            string extension,
            bool verifyFilesExist,
            out List<string> list)
        {
            list = null;
            if (!GetListOfStringsFromData(data, moduleManifestPath, key, manifestProcessingFlags, out List<string> listOfStrings))
            {
                return false;
            }

            if (listOfStrings != null)
            {
                var psHome = Utils.DefaultPowerShellAppBase;
                string alternateDirToCheck = null;
                if (moduleBase.StartsWith(psHome, StringComparison.OrdinalIgnoreCase))
                {
                    // alternateDirToCheck is an ugly hack for how Microsoft.PowerShell.Diagnostics and
                    // Microsoft.WSMan.Management refer to the ps1xml that was in $PSHOME but removed.
                    alternateDirToCheck = moduleBase + "\\..\\..";
                }

                list = new List<string>();
                foreach (string s in listOfStrings)
                {
                    try
                    {
                        string fixedFileName = FixFileNameWithoutLoadingAssembly(moduleBase, s, extension);
                        var dir = Path.GetDirectoryName(fixedFileName);

                        if (string.Equals(psHome, dir, StringComparison.OrdinalIgnoreCase) ||
                            (alternateDirToCheck != null && string.Equals(alternateDirToCheck, dir, StringComparison.OrdinalIgnoreCase)))
                        {
                            // The ps1xml file no longer exists in $PSHOME.  Downstream, we expect a resolved path,
                            // which we can't really do b/c the file doesn't exist.
                            fixedFileName = psHome + "\\" + Path.GetFileName(s);
                        }
                        else if (verifyFilesExist && !File.Exists(fixedFileName))
                        {
                            string message = StringUtil.Format(SessionStateStrings.PathNotFound, fixedFileName);
                            throw new FileNotFoundException(message, fixedFileName);
                        }

                        list.Add(fixedFileName);
                    }
                    catch (Exception e)
                    {
                        if (manifestProcessingFlags.HasFlag(ManifestProcessingFlags.WriteErrors))
                        {
                            this.ThrowTerminatingError(GenerateInvalidModuleMemberErrorRecord(key, moduleManifestPath, e));
                        }

                        list = null;
                        WriteInvalidManifestMemberError(this, key, moduleManifestPath, e, manifestProcessingFlags);
                        return false;
                    }
                }
            }

            return true;
        }

        [Flags]
        internal enum ModuleLoggingGroupPolicyStatus
        {
            Undefined = 0x00,
            Enabled = 0x01,
            Disabled = 0x02,
        }

        /// <summary>
        /// Enable Module logging based on group policy.
        /// </summary>
        internal void SetModuleLoggingInformation(PSModuleInfo m)
        {
            IEnumerable<string> moduleNames;
            ModuleLoggingGroupPolicyStatus status = GetModuleLoggingInformation(out moduleNames);
            if (status != ModuleLoggingGroupPolicyStatus.Undefined)
            {
                SetModuleLoggingInformation(status, m, moduleNames);
            }
        }

        private static void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, PSModuleInfo m, IEnumerable<string> moduleNames)
        {
            // TODO, insivara : What happens when Enabled but none of the other options (DefaultSystemModules, NonDefaultSystemModule, NonSystemModule, SpecificModules) are set?
            // After input from GP team for this behavior, need to revisit the commented out part
            // if ((status & ModuleLoggingGroupPolicyStatus.Enabled) != 0)
            // {
            // }
            if (((status & ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleNames != null)
            {
                foreach (string currentGPModuleName in moduleNames)
                {
                    if (string.Equals(m.Name, currentGPModuleName, StringComparison.OrdinalIgnoreCase))
                    {
                        m.LogPipelineExecutionDetails = true;
                    }
                    else if (WildcardPattern.ContainsWildcardCharacters(currentGPModuleName))
                    {
                        WildcardPattern wildcard = WildcardPattern.Get(currentGPModuleName, WildcardOptions.IgnoreCase);
                        if (wildcard.IsMatch(m.Name))
                        {
                            m.LogPipelineExecutionDetails = true;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Get Module Logging information from the group policy.
        /// </summary>
        internal static ModuleLoggingGroupPolicyStatus GetModuleLoggingInformation(out IEnumerable<string> moduleNames)
        {
            moduleNames = null;
            ModuleLoggingGroupPolicyStatus status = ModuleLoggingGroupPolicyStatus.Undefined;

            var moduleLogging = Utils.GetPolicySetting<ModuleLogging>(Utils.SystemWideThenCurrentUserConfig);
            if (moduleLogging != null)
            {
                if (moduleLogging.EnableModuleLogging == false)
                {
                    status = ModuleLoggingGroupPolicyStatus.Disabled;
                }
                else if (moduleLogging.EnableModuleLogging == true)
                {
                    status = ModuleLoggingGroupPolicyStatus.Enabled;
                    moduleNames = moduleLogging.ModuleNames;
                }
            }

            return status;
        }

        /// <summary>
        /// Checks to see if the module manifest contains the specified key.
        /// If it does and it can be converted to the expected type, then it returns <see langword="true"/> and sets <paramref name="result"/> to the value.
        /// If the key is missing it returns <see langword="true"/> and sets <paramref name="result"/> to <c>default(<typeparamref name="T"/>)</c>.
        /// If the key is invalid then it returns <see langword="false"/>.
        /// </summary>
        /// <param name="data">The hashtable to look for the key in.</param>
        /// <param name="moduleManifestPath">The manifest that generated the hashtable.</param>
        /// <param name="key">The table key to use.</param>
        /// <param name="manifestProcessingFlags">Specifies how to treat errors and whether to load elements.</param>
        /// <param name="result">Value from the manifest converted to the right type.</param>
        /// <returns><see langword="true"/> if success; <see langword="false"/> if there were errors.</returns>
        internal bool GetScalarFromData<T>(
            Hashtable data,
            string moduleManifestPath,
            string key,
            ManifestProcessingFlags manifestProcessingFlags,
            out T result)
        {
            object value = data[key];
            if ((value == null) || (value is string && string.IsNullOrEmpty((string)value)))
            {
                result = default(T);
                return true;
            }

            try
            {
                result = (T)LanguagePrimitives.ConvertTo(value, typeof(T), CultureInfo.InvariantCulture);
                return true;
            }
            catch (PSInvalidCastException e)
            {
                result = default(T);
                if ((manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0)
                {
                    string message = StringUtil.Format(Modules.ModuleManifestInvalidValue, key, e.Message, moduleManifestPath);
                    ArgumentException newAe = new ArgumentException(message);
                    ErrorRecord er = new ErrorRecord(newAe, "Modules_InvalidManifest",
                        ErrorCategory.ResourceUnavailable, moduleManifestPath);
                    WriteError(er);
                }

                return false;
            }
        }

        private string FixFileNameWithoutLoadingAssembly(string moduleBase, string fileName, string extension)
        {
            return FixFileName(moduleName: null, moduleBase, fileName, extension, canLoadAssembly: false, pathIsResolved: out _);
        }

        private string FixFileNameWithoutLoadingAssembly(string moduleBase, string fileName, string extension, out bool pathIsResolved)
        {
            return FixFileName(moduleName: null, moduleBase, fileName, extension, canLoadAssembly: false, out pathIsResolved);
        }

        /// <summary>
        /// A utility routine to fix up a file name so it's rooted and has an extension.
        /// </summary>
        private string FixFileName(string moduleName, string moduleBase, string fileName, string extension, bool canLoadAssembly)
        {
            return FixFileName(moduleName, moduleBase, fileName, extension, canLoadAssembly, pathIsResolved: out _);
        }

        /// <summary>
        /// A utility routine to fix up a file name so it's rooted and has an extension.
        /// </summary>
        /// <remarks>
        /// When fixing up an assembly file, this method loads the resolved assembly if it's in the process of actually loading a module.
        /// Read the comments in the method for the detailed information.
        /// </remarks>
        /// <param name="moduleName">Name of the module that we are processing, used for caching purpose when we need to load an assembly.</param>
        /// <param name="moduleBase">The base path to use if the file is not rooted.</param>
        /// <param name="fileName">The file name to resolve.</param>
        /// <param name="extension">The extension to use for the look up.</param>
        /// <param name="canLoadAssembly">Indicate if we can load assembly for the resolution.</param>
        /// <param name="pathIsResolved">Indicate if the returned path is fully resolved.</param>
        /// <returns>
        /// The resolved file path. Or, the combined path of <paramref name="moduleBase"/> and <paramref name="fileName"/> when the file path cannot be resolved.
        /// </returns>
        private string FixFileName(string moduleName, string moduleBase, string fileName, string extension, bool canLoadAssembly, out bool pathIsResolved)
        {
            pathIsResolved = false;

            string originalName = fileName;
            string originalExt = Path.GetExtension(fileName);

            if (string.IsNullOrEmpty(extension))
            {
                // When 'extension' is not explicitly specified, we honor the original extension.
                extension = originalExt;
            }
            else if (!extension.Equals(originalExt, StringComparison.OrdinalIgnoreCase))
            {
                // When 'extension' is explicitly specified, append it if the original extension is different.
                // Note: the original extension could actually be part of the file name. For example, the name
                // is `Microsoft.PowerShell.Command.Utility`, in which case the extension is `.Utility`.
                fileName += extension;
            }

            // Try to get the resolved fully qualified path to the file.
            // Note that, the 'IsRooted' method also returns true for relative paths, in which case we need to check for 'combinedPath' as well.
            //  * For example, the 'Microsoft.WSMan.Management.psd1' in Windows PowerShell defines 'FormatsToProcess="..\..\WSMan.format.ps1xml"'.
            //  * For such a module, we will have the following input when reaching this method:
            //     - moduleBase = 'C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.WSMan.Management'
            //     - name = '..\..\WSMan.format.ps1xml'
            //    Check for combinedPath in this case will get us the normalized rooted path 'C:\Windows\System32\WindowsPowerShell\v1.0\WSMan.format.ps1xml'.
            // The 'Microsoft.WSMan.Management' module in PowerShell was updated to not use the relative path for 'FormatsToProcess' entry,
            // but it's safer to keep the original behavior to avoid unexpected breaking changes.
            string combinedPath = Path.Combine(moduleBase, fileName);
            string resolvedPath = IsRooted(fileName)
                ? ResolveRootedFilePath(fileName, Context) ?? ResolveRootedFilePath(combinedPath, Context)
                : ResolveRootedFilePath(combinedPath, Context);

            // Return the path if successfully resolved.
            if (resolvedPath is not null)
            {
                if (canLoadAssembly && resolvedPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    // If we are fixing up an assembly file path and we are actually loading the module, then we load the resolved assembly file here.
                    // This is because we process type/format ps1xml files before 'RootModule' during the module loading. A types.ps1xml file could
                    // refer to a type defined in the assembly that is specified in the 'RootModule', and in that case, processing the types.ps1xml file
                    // would fail because it happens before processing the 'RootModule', which loads the assembly.
                    // We cannot move the processing of types.ps1xml file after processing 'RootModule' either, because the 'RootModule' might refer to
                    // members defined in the types.ps1xml file. In order to make it work for this paradox, we have to load the resolved assembly when
                    // we are actually loading the module. However, when it's module analysis, there is no need to load the assembly.
                    Context.AddAssembly(source: moduleName, assemblyName: null, filePath: resolvedPath, error: out _);
                }

                pathIsResolved = true;
                return resolvedPath;
            }

            // Path resolution failed, use the combined path as default.
            string result = combinedPath;

            // For dlls, we cannot get the path from the provider.
            // We need to load the assembly and then get the path.
            // If the module is already loaded, this is not expensive since the assembly is already loaded in the AppDomain
            if (canLoadAssembly && !string.IsNullOrEmpty(extension) &&
                (extension.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                 extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)))
            {
                Assembly assembly = Context.AddAssembly(source: moduleName, assemblyName: originalName, filePath: null, error: out _);
                if (assembly is not null)
                {
                    pathIsResolved = true;
                    result = assembly.Location;
                }
            }

            return result;
        }

        /// <summary>
        /// A utility routine to fix up a file name, if it is relative path convert it to absolute path combining moduleBase, if it is not a relative path, leave as it is.
        /// </summary>
        /// <param name="moduleBase">The base path to use if the file is not rooted.</param>
        /// <param name="path">The file name to resolve.</param>
        /// <returns></returns>
        internal string GetAbsolutePath(string moduleBase, string path)
        {
            if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')))
            {
                return Path.Combine(moduleBase, path);
            }
            else
            {
                return path;
            }
        }

        /// <summary>
        /// Check if a path is rooted or "relative rooted".
        /// </summary>
        /// <param name="filePath">The file path to check.</param>
        /// <returns>True if the path is rooted, false otherwise.</returns>
        internal static bool IsRooted(string filePath)
        {
            return (Path.IsPathRooted(filePath) ||
                filePath.StartsWith(@".\", StringComparison.Ordinal) ||
                filePath.StartsWith(@"./", StringComparison.Ordinal) ||
                filePath.StartsWith(@"..\", StringComparison.Ordinal) ||
                filePath.StartsWith(@"../", StringComparison.Ordinal) ||
                filePath.StartsWith(@"~/", StringComparison.Ordinal) ||
                filePath.StartsWith(@"~\", StringComparison.Ordinal) ||
                filePath.Contains(':'));
        }

        /// <summary>
        /// This utility resolves a rooted file name using the provider
        /// routines. It will only work if the path exists.
        /// </summary>
        /// <param name="filePath">The filename to resolve.</param>
        /// <param name="context">Execution context.</param>
        /// <returns>The resolved filename.</returns>
        internal static string ResolveRootedFilePath(string filePath, ExecutionContext context)
        {
            // If the path is not fully qualified or relative rooted, then
            // we need to do path-based resolution...
            if (!IsRooted(filePath))
            {
                return null;
            }

            ProviderInfo provider = null;

            Collection<string> filePaths = null;

            if (context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem))
            {
                try
                {
                    filePaths =
                        context.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider);
                }
                catch (ItemNotFoundException)
                {
                    return null;
                }

                // Make sure that the path is in the file system - that's all we can handle currently...
                if (!provider.NameEquals(context.ProviderNames.FileSystem))
                {
                    // "The current provider ({0}) cannot open a file"
                    throw InterpreterError.NewInterpreterException(
                        filePath,
                        typeof(RuntimeException),
                        errorPosition: null,
                        "FileOpenError",
                        ParserStrings.FileOpenError,
                        provider.FullName);
                }
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                return null;
            }

            if (filePaths.Count > 1)
            {
                // "The path resolved to more than one file; can only process one file at a time."
                throw InterpreterError.NewInterpreterException(
                    filePaths,
                    typeof(RuntimeException),
                    errorPosition: null,
                    "AmbiguousPath",
                    ParserStrings.AmbiguousPath);
            }

            return filePaths[0];
        }

        internal static string GetResolvedPath(string filePath, ExecutionContext context)
        {
            ProviderInfo provider = null;

            Collection<string> filePaths;

            if (context != null && context.EngineSessionState != null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem))
            {
                try
                {
                    filePaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, true /* allowNonExistentPaths */, out provider);
                }
                catch (Exception)
                {
                    return null;
                }
                // Make sure that the path is in the file system - that's all we can handle currently...
                if ((provider == null) || !provider.NameEquals(context.ProviderNames.FileSystem))
                {
                    return null;
                }
            }
            else
            {
                filePaths = new Collection<string>();
                filePaths.Add(filePath);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1 || filePaths.Count > 1)
            {
                return null;
            }

            return filePaths[0];
        }

        internal static Collection<string> GetResolvedPathCollection(string filePath, ExecutionContext context)
        {
            ProviderInfo provider = null;

            Collection<string> filePaths;

            if (context != null && context.EngineSessionState != null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem))
            {
                try
                {
                    filePaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, true /* allowNonExistentPaths */, out provider);
                }
                catch (Exception)
                {
                    return null;
                }
                // Make sure that the path is in the file system - that's all we can handle currently...
                if ((provider == null) || !provider.NameEquals(context.ProviderNames.FileSystem))
                {
                    return null;
                }
            }
            else
            {
                filePaths = new Collection<string>();
                filePaths.Add(filePath);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                return null;
            }

            return filePaths;
        }

        internal static PSSession GetWindowsPowerShellCompatRemotingSession()
        {
            PSSession result = null;
            var commandInfo = new CmdletInfo("Get-PSSession", typeof(GetPSSessionCommand));
            using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
            ps.AddCommand(commandInfo);
            ps.AddParameter("Name", WindowsPowerShellCompatRemotingSessionName);
            ps.AddParameter("ErrorAction", ActionPreference.Ignore);
            var results = ps.Invoke<PSSession>();
            if (results.Count > 0)
            {
                result = results[0];
            }
            return result;
        }

        internal static PSSession CreateWindowsPowerShellCompatResources()
        {
            PSSession compatSession = null;
            lock (s_WindowsPowerShellCompatSyncObject)
            {
                compatSession = GetWindowsPowerShellCompatRemotingSession();
                if (compatSession == null)
                {
                    var commandInfo = new CmdletInfo("New-PSSession", typeof(NewPSSessionCommand));
                    using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                    ps.AddCommand(commandInfo);
                    ps.AddParameter("UseWindowsPowerShell", true);
                    ps.AddParameter("Name", WindowsPowerShellCompatRemotingSessionName);
                    var results = ps.Invoke<PSSession>();
                    if (results.Count > 0)
                    {
                        compatSession = results[0];
                        System.Threading.Interlocked.Exchange(ref s_WindowsPowerShellCompatUsageCounter, 0);
                    }
                }
            }

            return compatSession;
        }

        internal static void CleanupWindowsPowerShellCompatResources(SessionState sessionState)
        {
            lock (s_WindowsPowerShellCompatSyncObject)
            {
                var compatSession = GetWindowsPowerShellCompatRemotingSession();
                if (compatSession != null)
                {
                    if (sessionState?.InvokeCommand.LocationChangedAction != null)
                    {
                        sessionState.InvokeCommand.LocationChangedAction -= SyncCurrentLocationDelegate;
                    }

                    var commandInfo = new CmdletInfo("Remove-PSSession", typeof(RemovePSSessionCommand));
                    using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                    ps.AddCommand(commandInfo);
                    ps.AddParameter("Session", compatSession);
                    ps.Invoke();
                }
            }
        }

        internal static void SyncCurrentLocationHandler(object sender, LocationChangedEventArgs args)
        {
            PSSession compatSession = GetWindowsPowerShellCompatRemotingSession();
            if (compatSession?.Runspace.RunspaceStateInfo.State == RunspaceState.Opened)
            {
                using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                ps.AddCommand(new CmdletInfo("Invoke-Command", typeof(InvokeCommandCommand)));
                ps.AddParameter("Session", compatSession);
                ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Create(CultureInfo.InvariantCulture, $"Set-Location -Path '{args.NewPath.Path}'")));
                ps.Invoke();
            }
        }

        internal static EventHandler<LocationChangedEventArgs> SyncCurrentLocationDelegate;

        internal virtual IList<PSModuleInfo> ImportModulesUsingWinCompat(IEnumerable<string> moduleNames, IEnumerable<ModuleSpecification> moduleFullyQualifiedNames, ImportModuleOptions importModuleOptions) { throw new System.NotImplementedException(); }

        private void RemoveTypesAndFormatting(
            IList<string> formatFilesToRemove,
            IList<string> typeFilesToRemove)
        {
            try
            {
                if (((formatFilesToRemove != null) && formatFilesToRemove.Count > 0) ||
                    ((typeFilesToRemove != null) && typeFilesToRemove.Count > 0))
                {
                    bool oldRefreshTypeFormatSetting = this.Context.InitialSessionState.RefreshTypeAndFormatSetting;
                    try
                    {
                        this.Context.InitialSessionState.RefreshTypeAndFormatSetting = true;
                        InitialSessionState.RemoveTypesAndFormats(this.Context, formatFilesToRemove, typeFilesToRemove);
                    }
                    finally
                    {
                        this.Context.InitialSessionState.RefreshTypeAndFormatSetting = oldRefreshTypeFormatSetting;
                    }
                }
            }
            catch (RuntimeException rte)
            {
                string fullErrorId = rte.ErrorRecord.FullyQualifiedErrorId;
                if (fullErrorId.Equals("ErrorsUpdatingTypes", StringComparison.Ordinal) ||
                    fullErrorId.Equals("ErrorsUpdatingFormats", StringComparison.Ordinal))
                {
                    return;
                }

                throw;
            }
        }

        /// <summary>
        /// Removes a module from the session state.
        /// </summary>
        /// <param name="module">Module to remove.</param>
        internal void RemoveModule(PSModuleInfo module)
        {
            RemoveModule(module, null);
        }

        /// <summary>
        /// Removes a module from the session state.
        /// </summary>
        /// <param name="module">Module to remove.</param>
        /// <param name="moduleNameInRemoveModuleCmdlet">Module name specified in the cmdlet.</param>
        internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleCmdlet)
        {
            // if the module path is empty string, means it is a dynamically generated assembly.
            // We have set the module path to be module name as key to make it unique, we need update here as well in case the module can be removed.
            if (module.Path == string.Empty)
            {
                module.Path = module.Name;
            }

            bool shouldModuleBeRemoved = ShouldModuleBeRemoved(module, moduleNameInRemoveModuleCmdlet, out bool isTopLevelModule);

            if (shouldModuleBeRemoved)
            {
                // We don't check for dups in the remove list so it may already be removed
                if (Context.Modules.ModuleTable.ContainsKey(module.Path))
                {
                    // We should try to run OnRemove as the very first thing
                    module.OnRemove?.InvokeUsingCmdlet(
                        contextCmdlet: this,
                        useLocalScope: true,
                        errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                        dollarUnder: AutomationNull.Value,
                        input: AutomationNull.Value,
                        scriptThis: AutomationNull.Value,
                        args: new object[] { module });

                    if (module.ImplementingAssembly != null && !module.ImplementingAssembly.IsDynamic)
                    {
                        var exportedTypes = PSSnapInHelpers.GetAssemblyTypes(module.ImplementingAssembly, module.Name);
                        foreach (var type in exportedTypes)
                        {
                            if (typeof(IModuleAssemblyCleanup).IsAssignableFrom(type))
                            {
                                var moduleCleanup = (IModuleAssemblyCleanup)Activator.CreateInstance(type, true);
                                moduleCleanup.OnRemove(module);
                            }
                        }
                    }

                    if (module.IsWindowsPowerShellCompatModule && (System.Threading.Interlocked.Decrement(ref s_WindowsPowerShellCompatUsageCounter) == 0))
                    {
                        CleanupWindowsPowerShellCompatResources(this.SessionState);
                    }

                    // First remove cmdlets from the session state
                    // (can't just go through module.ExportedCmdlets
                    //  because the names of the cmdlets might have been changed by the -Prefix parameter of Import-Module)
                    List<string> keysToRemoveFromCmdletCache = new List<string>();
                    foreach (KeyValuePair<string, List<CmdletInfo>> cmdlet in Context.EngineSessionState.GetCmdletTable())
                    {
                        List<CmdletInfo> matches = cmdlet.Value;
                        // If the entry's module name matches, then remove it from the list...
                        for (int i = matches.Count - 1; i >= 0; i--)
                        {
                            if (matches[i].Module == null)
                            {
                                continue;
                            }

                            if (matches[i].Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                            {
                                string name = matches[i].Name;
                                matches.RemoveAt(i);
                                Context.EngineSessionState.RemoveCmdlet(name, i, true);
                            }
                        }
                        // And finally remove the name from the cache if the list is now empty...
                        if (matches.Count == 0)
                        {
                            keysToRemoveFromCmdletCache.Add(cmdlet.Key);
                        }
                    }

                    foreach (string keyToRemove in keysToRemoveFromCmdletCache)
                    {
                        Context.EngineSessionState.RemoveCmdletEntry(keyToRemove, true);
                    }

                    // Remove any providers imported by this module. Providers are always imported into
                    // the top level session state. Only binary modules can import providers.
                    if (module.ModuleType == ModuleType.Binary)
                    {
                        Dictionary<string, List<ProviderInfo>> providers = Context.TopLevelSessionState.Providers;
                        List<string> keysToRemoveFromProviderTable = new List<string>();

                        foreach (KeyValuePair<string, System.Collections.Generic.List<ProviderInfo>> pl in providers)
                        {
                            Dbg.Assert(pl.Value != null, "There should never be a null list of entries in the provider table");

                            // For each provider with this name, if it was imported from the module,
                            // remove it from the list.
                            for (int i = pl.Value.Count - 1; i >= 0; i--)
                            {
                                ProviderInfo pi = pl.Value[i];

                                // If it was implemented by this module, remove it
                                string implAssemblyLocation = pi.ImplementingType.Assembly.Location;
                                if (implAssemblyLocation.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                                {
                                    // Remove all drives from the top level session state
                                    InitialSessionState.RemoveAllDrivesForProvider(pi, Context.TopLevelSessionState);
                                    // Remove all drives from the current module context
                                    if (Context.EngineSessionState != Context.TopLevelSessionState)
                                        InitialSessionState.RemoveAllDrivesForProvider(pi, Context.EngineSessionState);
                                    // Remove drives from all other module contexts.
                                    foreach (PSModuleInfo psmi in Context.Modules.ModuleTable.Values)
                                    {
                                        if (psmi.SessionState != null)
                                        {
                                            SessionStateInternal mssi = psmi.SessionState.Internal;
                                            if (mssi != Context.TopLevelSessionState &&
                                                mssi != Context.EngineSessionState)
                                            {
                                                InitialSessionState.RemoveAllDrivesForProvider(pi, Context.EngineSessionState);
                                            }
                                        }
                                    }

                                    pl.Value.RemoveAt(i);
                                }
                            }

                            // If there are no providers left with this name, add this key to the list
                            // of entries to remove.
                            if (pl.Value.Count == 0)
                            {
                                keysToRemoveFromProviderTable.Add(pl.Key);
                            }
                        }

                        // Finally remove all of the empty table entries.
                        foreach (string keyToRemove in keysToRemoveFromProviderTable)
                        {
                            providers.Remove(keyToRemove);
                        }
                    }

                    SessionStateInternal ss = Context.EngineSessionState;

                    if (module.SessionState != null)
                    {
                        // Remove the imported functions from SessionState...
                        // (can't just go through module.SessionState.Internal.ExportedFunctions,
                        //  because the names of the functions might have been changed by the -Prefix parameter of Import-Module)
                        foreach ((var _, FunctionInfo functionInfo) in ss.GetFunctionTable())
                        {
                            if (functionInfo.Module == null)
                            {
                                continue;
                            }

                            if (functionInfo.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                            {
                                string functionName = functionInfo.Name;
                                try
                                {
                                    ss.RemoveFunction(functionName, true);

                                    string memberMessage = StringUtil.Format(Modules.RemovingImportedFunction, functionName);
                                    WriteVerbose(memberMessage);
                                }
                                catch (SessionStateUnauthorizedAccessException e)
                                {
                                    string message = StringUtil.Format(Modules.UnableToRemoveModuleMember, functionName, module.Name, e.Message);
                                    InvalidOperationException memberNotRemoved = new InvalidOperationException(message, e);
                                    ErrorRecord er = new ErrorRecord(memberNotRemoved, "Modules_MemberNotRemoved",
                                                                     ErrorCategory.PermissionDenied, functionName);
                                    WriteError(er);
                                }
                            }
                        }

                        // Remove the imported variables from SessionState...
                        foreach (PSVariable mv in module.SessionState.Internal.ExportedVariables)
                        {
                            PSVariable sv = ss.GetVariable(mv.Name);
                            if (sv != null && sv == mv)
                            {
                                ss.RemoveVariable(sv, BaseForce);
                                string memberMessage = StringUtil.Format(Modules.RemovingImportedVariable, sv.Name);
                                WriteVerbose(memberMessage);
                            }
                        }

                        // Remove the imported aliases from SessionState...
                        // (can't just go through module.SessionState.Internal.ExportedAliases,
                        //  because the names of the aliases might have been changed by the -Prefix parameter of Import-Module)
                        foreach (KeyValuePair<string, AliasInfo> entry in ss.GetAliasTable())
                        {
                            AliasInfo ai = entry.Value;
                            if (ai.Module == null)
                            {
                                continue;
                            }

                            if (ai.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                            {
                                // Remove the alias with force...
                                ss.RemoveAlias(ai.Name, true);
                                string memberMessage = StringUtil.Format(Modules.RemovingImportedAlias, ai.Name);
                                WriteVerbose(memberMessage);
                            }
                        }
                    }

                    this.RemoveTypesAndFormatting(module.ExportedFormatFiles, module.ExportedTypeFiles);
                    // resetting the help caches. This is needed as the help content cached is cached in process.
                    // When a module is removed there is no need to cache the help content for the commands in
                    // the module. The HelpSystem is not designed to track per module help content...so resetting
                    // all of the cache. HelpSystem knows how to build this cache back when needed.
                    Context.HelpSystem.ResetHelpProviders();

                    // Remove the module from all session state module tables...
                    foreach (KeyValuePair<string, PSModuleInfo> e in Context.Modules.ModuleTable)
                    {
                        PSModuleInfo m = e.Value;
                        if (m.SessionState != null)
                        {
                            if (m.SessionState.Internal.ModuleTable.ContainsKey(module.Path))
                            {
                                m.SessionState.Internal.ModuleTable.Remove(module.Path);
                                m.SessionState.Internal.ModuleTableKeys.Remove(module.Path);
                            }
                        }
                    }

                    if (isTopLevelModule)
                    {
                        // Remove it from the top level session state
                        Context.TopLevelSessionState.ModuleTable.Remove(module.Path);
                        Context.TopLevelSessionState.ModuleTableKeys.Remove(module.Path);
                    }
                    // And finally from the global module table...
                    Context.Modules.ModuleTable.Remove(module.Path);

                    // And the appdomain level module path cache.
                    PSModuleInfo.RemoveFromAppDomainLevelCache(module.Name);

                    // And remove the module assembly entries that may have been added from the assembly cache.
                    Context.RemoveFromAssemblyCache(source: module.Name);
                    if (module.ModuleType == ModuleType.Binary && !string.IsNullOrEmpty(module.RootModule))
                    {
                        // We also need to clean up the cache entries that are possibly referenced by the root module in this case.
                        string rootModuleName = ModuleIntrinsics.GetModuleName(module.RootModule);
                        Context.RemoveFromAssemblyCache(source: rootModuleName);
                    }
                }
            }
        }

        private bool ShouldModuleBeRemoved(PSModuleInfo module, string moduleNameInRemoveModuleCmdlet, out bool isTopLevelModule)
        {
            isTopLevelModule = false;

            if (Context.TopLevelSessionState.ModuleTable.ContainsKey(module.Path))
            {
                isTopLevelModule = true;
                // This check makes sure that this module is removed only when we do a Remove-Module <moduleName> of this module
                // If this module is a nested module of some other module but is also imported as a top level module, then we should not be removing it.
                if (moduleNameInRemoveModuleCmdlet == null || module.Name.Equals(moduleNameInRemoveModuleCmdlet, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            else
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Checks if an already loaded module meets the constraints passed to the module cmdlet by the user.
        /// </summary>
        /// <param name="alreadyLoadedModule">The already loaded module that matched the name of the module to load.</param>
        /// <returns>True if the pre-loaded module matches all GUID and version constraints provided, false otherwise.</returns>
        internal bool DoesAlreadyLoadedModuleSatisfyConstraints(PSModuleInfo alreadyLoadedModule)
        {
            return ModuleIntrinsics.IsModuleMatchingConstraints(
                alreadyLoadedModule,
                guid: BaseGuid,
                requiredVersion: BaseRequiredVersion,
                minimumVersion: BaseMinimumVersion,
                maximumVersion: BaseMaximumVersion);
        }

        /// <summary>
        /// </summary>
        /// <param name="modulePath"></param>
        /// <param name="prefix"></param>
        /// <param name="options"></param>
        /// <returns>
        /// Returns PSModuleInfo of an already loaded module if that module can be simply reimported and there is no need to proceed with a regular import.
        /// Returns <see langword="null"/> if the caller should proceed with a regular import (either because there is no previously loaded module, or because the -Force flag was specified and the previously loaded module has been removed by this method).
        /// </returns>
        internal PSModuleInfo IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(string modulePath, string prefix, ImportModuleOptions options)
        {
            if (TryGetFromModuleTable(modulePath, out PSModuleInfo alreadyLoadedModule))
            {
                if (this.DoesAlreadyLoadedModuleSatisfyConstraints(alreadyLoadedModule))
                {
                    if (this.BaseForce) // remove the previously imported module + return null (null = please proceed with regular import)
                    {
                        // remove the module
                        RemoveModule(alreadyLoadedModule);

                        // proceed with regular import
                        return null;
                    }
                    else // reimport the module + return alreadyLoadedModule (alreadyLoadedModule = no need to proceed with regular import)
                    {
                        // If the module has already been loaded, then while loading it the second time, we should load it with the DefaultCommandPrefix specified in the module manifest. (If there is no Prefix from command line)
                        if (string.IsNullOrEmpty(prefix) && File.Exists(alreadyLoadedModule.Path))
                        {
                            string defaultPrefix = GetDefaultPrefix(alreadyLoadedModule);
                            if (!string.IsNullOrEmpty(defaultPrefix))
                            {
                                prefix = defaultPrefix;
                            }
                        }

                        AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, alreadyLoadedModule);

                        // Even if the alreadyLoadedModule has been loaded, import the specified members...
                        ImportModuleMembers(alreadyLoadedModule, prefix, options);

                        if (BaseAsCustomObject)
                        {
                            if (alreadyLoadedModule.ModuleType != ModuleType.Script)
                            {
                                string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, alreadyLoadedModule.Path);
                                InvalidOperationException invalidOp = new InvalidOperationException(message);
                                ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
                                    ErrorCategory.PermissionDenied, null);
                                WriteError(er);
                            }
                            else
                            {
                                WriteObject(alreadyLoadedModule.AsCustomObject());
                            }
                        }
                        else if (BasePassThru)
                        {
                            WriteObject(alreadyLoadedModule);
                        }

                        // no need to proceed with regular import
                        return alreadyLoadedModule;
                    }
                }
            }

            // no previously imported module (or already loaded module has wrong version) - proceed with regular import
            return null;
        }

        /// <summary>
        /// Loads a module file after searching for it using the known extension list.
        /// </summary>
        /// <param name="parentModule">The parent module for which this module is a nested module.</param>
        /// <param name="moduleName">The name to use for the module.</param>
        /// <param name="fileBaseName">The file basename for this module.</param>
        /// <param name="extension">The module's extension.</param>
        /// <param name="moduleBase">The module base which comes from the module manifest.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="ss">
        /// The session state instance to use for this module - may be null
        /// in which case a session state will be allocated if necessary
        /// </param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The processing flags to use when processing the module.</param>
        /// <param name="found">True if a module was found.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule,
            string moduleName, string fileBaseName, string extension, string moduleBase,
            string prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out bool found)
        {
            return LoadUsingExtensions(parentModule, moduleName, fileBaseName, extension, moduleBase, prefix, ss,
                                       options, manifestProcessingFlags, out found, out _);
        }

        /// <summary>
        /// Loads a module file after searching for it using the known extension list.
        /// </summary>
        /// <param name="parentModule">The parent module for which this module is a nested module.</param>
        /// <param name="moduleName">The name to use for the module.</param>
        /// <param name="fileBaseName">The file basename for this module.</param>
        /// <param name="extension">The module's extension.</param>
        /// <param name="moduleBase">The module base which comes from the module manifest.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="ss">
        /// The session state instance to use for this module - may be null
        /// in which case a session state will be allocated if necessary
        /// </param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The processing flags to use when processing the module.</param>
        /// <param name="found">True if a module was found.</param>
        /// <param name="moduleFileFound">True if a module file was found.</param>
        /// <returns></returns>
        internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule,
            string moduleName, string fileBaseName, string extension, string moduleBase,
            string prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out bool found, out bool moduleFileFound)
        {
            string[] extensions;
            moduleFileFound = false;

            if (!string.IsNullOrEmpty(extension))
                extensions = new string[] { extension };
            else
                extensions = ModuleIntrinsics.PSModuleExtensions;

            var importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0;

            // "ni.dll" has a higher priority then ".dll" to be loaded.
            for (int i = 0; i < extensions.Length; i++)
            {
                string ext = extensions[i];
                string fileName = fileBaseName + ext;

                // Get the resolved file name
                fileName = GetResolvedPath(fileName, Context);

                if (fileName == null)
                    continue;

                // If we've found ourselves, then skip and move on to the next extension.
                // This will be the case where a scriptmodule foo.psm1 does an "Import-Module foo" intending to get foo.dll.
                if (!string.IsNullOrEmpty(Context.ModuleBeingProcessed) &&
                    Context.ModuleBeingProcessed.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // If the module has already been loaded, just emit it and continue...
                TryGetFromModuleTable(fileName, out PSModuleInfo module);
                if (!BaseForce && importingModule && DoesAlreadyLoadedModuleSatisfyConstraints(module))
                {
                    moduleFileFound = true;

                    // If the module has already been loaded, then while loading it the second time, we should load it with the DefaultCommandPrefix specified in the module manifest. (If there is no Prefix from command line)
                    if (string.IsNullOrEmpty(prefix))
                    {
                        string defaultPrefix = GetDefaultPrefix(module);
                        if (!string.IsNullOrEmpty(defaultPrefix))
                        {
                            prefix = defaultPrefix;
                        }
                    }

                    AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);

                    // Even if the module has been loaded, import the specified members...
                    ImportModuleMembers(module, prefix, options);

                    if (BaseAsCustomObject)
                    {
                        if (module.ModuleType != ModuleType.Script)
                        {
                            string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, module.Path);
                            InvalidOperationException invalidOp = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
                                ErrorCategory.PermissionDenied, null);
                            WriteError(er);
                        }
                        else
                        {
                            WriteObject(module.AsCustomObject());
                        }
                    }
                    else if (BasePassThru)
                    {
                        WriteObject(module);
                    }

                    found = true;
                    return module;
                }
                else if (File.Exists(fileName))
                {
                    // Win8: 325243 - Added the version check so that we do not unload modules with the same name but different version
                    if (BaseForce && DoesAlreadyLoadedModuleSatisfyConstraints(module))
                    {
                        RemoveModule(module);
                    }

                    module = LoadModule(parentModule, fileName, moduleBase, prefix, ss, null, ref options, manifestProcessingFlags, out found, out moduleFileFound);
                    if (found)
                    {
                        return module;
                    }
                }
            }

            found = false;
            return null;
        }

        internal string GetDefaultPrefix(PSModuleInfo module)
        {
            string prefix = string.Empty;
            string extension = Path.GetExtension(module.Path);
            if (!string.IsNullOrEmpty(extension) && extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                string throwAwayScriptName;
                ExternalScriptInfo scriptInfo = GetScriptInfoForFile(module.Path, out throwAwayScriptName, true);
                Dbg.Assert(scriptInfo != null, "scriptInfo for module (.psd1) can't be null");
                bool containedErrors = false;
                Hashtable data = null;
                Hashtable localizedData = null;

                if (LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.NullOnFirstError, out data, out localizedData, ref containedErrors))
                {
                    // Get Default prefix
                    if (data.Contains("DefaultCommandPrefix"))
                    {
                        if (localizedData != null && localizedData.Contains("DefaultCommandPrefix"))
                        {
                            prefix = (string)LanguagePrimitives.ConvertTo(localizedData["DefaultCommandPrefix"],
                                typeof(string), CultureInfo.InvariantCulture);
                        }

                        if (string.IsNullOrEmpty(prefix))
                        {
                            prefix = (string)LanguagePrimitives.ConvertTo(data["DefaultCommandPrefix"],
                                typeof(string), CultureInfo.InvariantCulture);
                        }
                    }
                }
            }

            return prefix;
        }

        /// <summary>
        /// Create an ExternalScriptInfo object from a file path.
        /// </summary>
        /// <param name="fileName">The path to the file.</param>
        /// <param name="scriptName">The base name of the script.</param>
        /// <param name="checkExecutionPolicy">Check the current execution policy.</param>
        /// <returns>The ExternalScriptInfo object.</returns>
        internal ExternalScriptInfo GetScriptInfoForFile(string fileName, out string scriptName, bool checkExecutionPolicy)
        {
            scriptName = Path.GetFileName(fileName);
            ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, fileName, Context);

            // Skip ShouldRun check for .psd1 files.
            // Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file.
            if (!scriptName.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
            {
                if (checkExecutionPolicy)
                {
                    Context.AuthorizationManager.ShouldRunInternal(scriptInfo, CommandOrigin.Runspace,
                        Context.EngineHostInterface);
                }
                else
                {
                    Context.AuthorizationManager.ShouldRunInternal(scriptInfo, CommandOrigin.Internal,
                        Context.EngineHostInterface);
                }

                if (!scriptName.EndsWith(".cdxml", StringComparison.OrdinalIgnoreCase))
                {
                    CommandDiscovery.VerifyScriptRequirements(scriptInfo, Context);
                }

                // If we got this far, the check succeeded and we don't need to check again.
                scriptInfo.SignatureChecked = true;
            }

            return scriptInfo;
        }

        /// <summary>
        /// Load a module from a file...
        /// </summary>
        /// <param name="fileName">The resolved path to load the module from.</param>
        /// <param name="moduleBase">The module base path to use for this module.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="ss">The session state instance to use for this module - may be null in which case a session state will be allocated if necessary.</param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The manifest processing flags to use when processing the module.</param>
        /// <param name="found">True if a module was found.</param>
        /// <returns>True if the module was successfully loaded.</returns>
        internal PSModuleInfo LoadModule(string fileName, string moduleBase, string prefix, SessionState ss, ref ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags, out bool found)
        {
            bool throwAwayModuleFileFound = false;
            return LoadModule(null, fileName, moduleBase, prefix, ss, null, ref options, manifestProcessingFlags, out found, out throwAwayModuleFileFound);
        }

        /// <summary>
        /// Load a module from a file...
        /// </summary>
        /// <param name="parentModule">The parent module, if any.</param>
        /// <param name="fileName">The resolved path to load the module from.</param>
        /// <param name="moduleBase">The module base path to use for this module.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="ss">The session state instance to use for this module - may be null in which case a session state will be allocated if necessary.</param>
        /// <param name="privateData">Private Data for the module.</param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The manifest processing flags to use when processing the module.</param>
        /// <param name="found">True if a module was found.</param>
        /// <param name="moduleFileFound">True if a module file was found.</param>
        /// <returns>True if the module was successfully loaded.</returns>
        internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, string moduleBase, string prefix,
            SessionState ss, object privateData, ref ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags, out bool found, out bool moduleFileFound)
        {
            Dbg.Assert(fileName != null, "Filename argument to LoadModule() shouldn't be null");

            if (!File.Exists(fileName))
            {
                found = false;
                moduleFileFound = false;
                return null;
            }

            var importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0;
            var writingErrors = (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors) != 0;

            // In case the file is a Ngen Assembly.
            string ext;
            if (fileName.EndsWith(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase))
            {
                ext = StringLiterals.PowerShellNgenAssemblyExtension;
            }
            else
            {
                ext = Path.GetExtension(fileName);
            }

            PSModuleInfo module = null;

            // Block ps1 files from being imported in constrained language.
            if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage &&
                ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)
                {
                    InvalidOperationException invalidOp = new InvalidOperationException(Modules.ImportPSFileNotAllowedInConstrainedLanguage);
                    ErrorRecord er = new ErrorRecord(invalidOp, "Modules_ImportPSFileNotAllowedInConstrainedLanguage",
                                                    ErrorCategory.PermissionDenied, null);
                    ThrowTerminatingError(er);
                }

                SystemPolicy.LogWDACAuditMessage(
                    context: Context,
                    title: Modules.WDACScriptFileImportLogTitle,
                    message: StringUtil.Format(Modules.WDACScriptFileImportLogMessage, fileName),
                    fqid: "ModuleImportScriptFilesNotAllowed",
                    dropIntoDebugger: true);
            }

            // If MinimumVersion/RequiredVersion/MaximumVersion has been specified, then only try to process manifest modules...
            if (BaseMinimumVersion != null || BaseMaximumVersion != null || BaseRequiredVersion != null || BaseGuid != null)
            {
                // If the -Version flag was specified, don't look for non-manifest modules
                if (string.IsNullOrEmpty(ext) || !ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    found = false;
                    moduleFileFound = false;
                    return null;
                }

                // If the module is in memory and the versions don't match don't return it.
                // This will allow the search to continue and load a different version of the module.
                if (TryGetFromModuleTable(fileName, out module))
                {
                    if (!ModuleIntrinsics.IsVersionMatchingConstraints(module.Version, minimumVersion: BaseMinimumVersion, maximumVersion: BaseMaximumVersion))
                    {
                        found = false;
                        moduleFileFound = false;
                        return null;
                    }
                }
            }

            found = false;
            string scriptName;

            //
            // !!NOTE!!
            // If a new module type to load is ever added and if that new module type is based on a script file,
            // such as the existing .psd1 and .psm1 files,
            // then be sure to include the script file LanguageMode in the moduleInfo type created for the loaded module.
            // The PSModuleInfo.LanguageMode property is used to check consistency between the manifest (.psd1) file
            // and all other script (.psm1) file based modules being loaded by that manifest.
            // Use the PSModuleInfo class constructor that takes the PSLanguageMode parameter argument.
            // Look at the LoadModuleNamedInManifest() method to see how the language mode check works.
            // !!NOTE!!
            //

            string _origModuleBeingProcessed = Context.ModuleBeingProcessed;
            try
            {
                // Set the name of the module currently being processed...
                Context.PreviousModuleProcessed = Context.ModuleBeingProcessed;
                Context.ModuleBeingProcessed = fileName;

                string message = StringUtil.Format(Modules.LoadingModule, fileName);
                WriteVerbose(message);

                moduleFileFound = true;

                if (ext.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    if (!importingModule)
                    {
                        bool shouldProcessModule = ShouldProcessScriptModule(parentModule, ref found);

                        if (shouldProcessModule)
                        {
                            bool force = (manifestProcessingFlags & ManifestProcessingFlags.Force) == ManifestProcessingFlags.Force;
                            module = AnalyzeScriptFile(fileName, force, Context);
                            found = true;
                        }
                    }
                    else
                    {
                        var psm1ScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true);
                        try
                        {
                            Context.Modules.IncrementModuleNestingDepth(this, psm1ScriptInfo.Path);

                            // Create the module object...
                            try
                            {
                                module = Context.Modules.CreateModule(fileName, psm1ScriptInfo, MyInvocation.ScriptPosition, ss, privateData, BaseArgumentList);
                                module.SetModuleBase(moduleBase);

                                SetModuleLoggingInformation(module);

                                // If the script didn't call Export-ModuleMember explicitly, then
                                // implicitly export functions and cmdlets.
                                var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy();
                                if (!module.SessionState.Internal.UseExportList)
                                {
                                    // For cross language boundaries don't implicitly export all functions, unless they are allowed nested modules.
                                    // Implicit function export is allowed when any of the following is true:
                                    //  - Nested modules are allowed by module manifest
                                    //  - The import context language mode is FullLanguage
                                    //  - This script module is not running as trusted (FullLanguage)
                                    module.ModuleAutoExportsAllFunctions = options.AllowNestedModuleFunctionsToExport ||
                                                                           Context.LanguageMode == PSLanguageMode.FullLanguage ||
                                                                           psm1ScriptInfo.DefiningLanguageMode != PSLanguageMode.FullLanguage;
                                    List<WildcardPattern> fnMatchPattern = module.ModuleAutoExportsAllFunctions ? MatchAll : null;

                                    // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied.
                                    if (fnMatchPattern == null && systemLockdownPolicy == SystemEnforcementMode.Audit)
                                    {
                                        SystemPolicy.LogWDACAuditMessage(
                                            context: Context,
                                            title: Modules.WDACImplicitFunctionExportLogTitle,
                                            message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, module.Name),
                                            fqid: "ModuleImplicitFunctionExportNotAllowed",
                                            dropIntoDebugger: true);
                                        fnMatchPattern = MatchAll;
                                    }

                                    ModuleIntrinsics.ExportModuleMembers(
                                        cmdlet: this,
                                        sessionState: module.SessionState.Internal,
                                        functionPatterns: fnMatchPattern,
                                        cmdletPatterns: MatchAll,
                                        aliasPatterns: MatchAll,
                                        variablePatterns: null,
                                        doNotExportCmdlets: null);
                                }
                                else if ((systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) &&
                                         module.LanguageMode == PSLanguageMode.FullLanguage &&
                                         module.SessionState.Internal.FunctionsExportedWithWildcard &&
                                         !module.SessionState.Internal.ManifestWithExplicitFunctionExport)
                                {
                                    // When in a constrained environment and functions are being exported from this module using wildcards, make sure
                                    // exported functions only come from this module and not from any imported nested modules.
                                    // Unless there is a parent manifest that explicitly filters all exported functions (no wildcards).
                                    // This prevents unintended public exposure of imported functions running in FullLanguage.
                                    RemoveNestedModuleFunctions(Context, module, systemLockdownPolicy);
                                }

                                CheckForDisallowedDotSourcing(module, psm1ScriptInfo, options);

                                // Add it to the all module tables
                                ImportModuleMembers(module, prefix, options);
                                AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);

                                found = true;
                                if (BaseAsCustomObject)
                                {
                                    WriteObject(module.AsCustomObject());
                                }
                                else
                                    // If -pass has been specified, emit a module info...
                                    if (BasePassThru)
                                {
                                    WriteObject(module);
                                }
                            }
                            catch (RuntimeException e)
                            {
                                if (writingErrors)
                                {
                                    e.ErrorRecord.PreserveInvocationInfoOnce = true;
                                }

                                if (e.WasThrownFromThrowStatement)
                                {
                                    ThrowTerminatingError(e.ErrorRecord);
                                }
                                else
                                {
                                    WriteError(e.ErrorRecord);
                                }
                            }
                        }
                        finally
                        {
                            Context.Modules.DecrementModuleNestingCount();
                        }
                    }
                }
                else if (ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    if (!importingModule)
                    {
                        bool shouldProcessModule = ShouldProcessScriptModule(parentModule, ref found);

                        if (shouldProcessModule)
                        {
                            bool force = (manifestProcessingFlags & ManifestProcessingFlags.Force) == ManifestProcessingFlags.Force;
                            module = AnalyzeScriptFile(fileName, force, Context);
                            found = true;
                        }
                    }
                    else
                    {
                        // Create a dummy module info
                        // The module info created for a .ps1 file will not have ExportedCommands populated.
                        // Removing the module will not remove the commands dot-sourced from the .ps1 file.
                        // This module info is created so that we can keep the behavior consistent between scripts imported as modules and other kind of modules(all of them should have a PSModuleInfo).
                        // Auto-loading expects we always have a PSModuleInfo object for any module. This is how this issue was found.
                        var ps1ScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true);
                        Dbg.Assert(ps1ScriptInfo != null, "Scriptinfo for dotted file can't be null");
                        module = new PSModuleInfo(ModuleIntrinsics.GetModuleName(fileName), fileName, Context, ss, ps1ScriptInfo.DefiningLanguageMode);

                        message = StringUtil.Format(Modules.DottingScriptFile, fileName);
                        WriteVerbose(message);

                        try
                        {
                            found = true;

                            InvocationInfo oldInvocationInfo = (InvocationInfo)Context.GetVariableValue(SpecialVariables.MyInvocationVarPath);
                            object oldPSScriptRoot = Context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
                            object oldPSCommandPath = Context.GetVariableValue(SpecialVariables.PSCommandPathVarPath);

                            try
                            {
                                InvocationInfo invocationInfo = new InvocationInfo(ps1ScriptInfo, ps1ScriptInfo.ScriptBlock.Ast.Extent, Context);
                                ps1ScriptInfo.ScriptBlock.InvokeWithPipe(
                                    useLocalScope: false,
                                    errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                                    dollarUnder: AutomationNull.Value,
                                    input: AutomationNull.Value,
                                    scriptThis: AutomationNull.Value,
                                    outputPipe: ((MshCommandRuntime)this.CommandRuntime).OutputPipe,
                                    invocationInfo: invocationInfo,
                                    args: this.BaseArgumentList ?? Array.Empty<object>());
                            }
                            finally
                            {
                                // since useLocalScope is set false while calling InvokeWithPipe, we need to
                                // revert the changes made to LocalsTuple
                                if (Context.EngineSessionState.CurrentScope.LocalsTuple != null)
                                {
                                    Context.EngineSessionState.CurrentScope.LocalsTuple.SetAutomaticVariable(
                                        AutomaticVariable.PSScriptRoot, oldPSScriptRoot, Context);
                                    Context.EngineSessionState.CurrentScope.LocalsTuple.SetAutomaticVariable(AutomaticVariable.PSCommandPath, oldPSCommandPath, Context);
                                    Context.EngineSessionState.CurrentScope.LocalsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, oldInvocationInfo, Context);
                                }
                            }

                            AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);

                            if (BaseAsCustomObject)
                            {
                                WriteObject(module.AsCustomObject());
                            }
                            else
                                // If -pass has been specified, emit a module info...
                                if (BasePassThru)
                            {
                                WriteObject(module);
                            }
                        }
                        catch (RuntimeException e)
                        {
                            if (writingErrors)
                            {
                                e.ErrorRecord.PreserveInvocationInfoOnce = true;
                            }

                            if (e.WasThrownFromThrowStatement)
                            {
                                ThrowTerminatingError(e.ErrorRecord);
                            }
                            else
                            {
                                WriteError(e.ErrorRecord);
                            }
                        }
                        catch (ExitException ee)
                        {
                            int exitCode = (int)ee.Argument;
                            Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);
                        }
                    }
                }
                else if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    var psd1ScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true);
                    found = true;
                    Dbg.Assert(psd1ScriptInfo != null, "Scriptinfo for module manifest (.psd1) can't be null");
                    module = LoadModuleManifest(
                        psd1ScriptInfo,
                        manifestProcessingFlags,
                        BaseMinimumVersion,
                        BaseMaximumVersion,
                        BaseRequiredVersion,
                        BaseGuid,
                        ref options);

                    if (module != null)
                    {
                        CheckForDisallowedDotSourcing(module, psd1ScriptInfo, options);

                        if (importingModule)
                        {
                            // Add it to all the module tables
                            AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
                        }

                        if (BasePassThru)
                        {
                            WriteObject(module);
                        }
                    }
                    else if (BaseMinimumVersion != null || BaseRequiredVersion != null || BaseGuid != null || BaseMaximumVersion != null)
                    {
                        found = false;
                    }
                }
                else if (ext.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                         ext.Equals(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
                         ext.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
                {
                    module = LoadBinaryModule(
                        parentModule,
                        ModuleIntrinsics.GetModuleName(fileName),
                        fileName,
                        assemblyToLoad: null,
                        moduleBase,
                        ss,
                        options,
                        manifestProcessingFlags,
                        prefix,
                        out found);

                    if (found && module != null)
                    {
                        // LanguageMode does not apply to binary modules
                        module.LanguageMode = (PSLanguageMode?)null;

                        if (importingModule)
                        {
                            // Add it to all the module tables
                            AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
                        }

                        if (BaseAsCustomObject)
                        {
                            message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, fileName);
                            InvalidOperationException invalidOp = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
                                ErrorCategory.PermissionDenied, null);
                            WriteError(er);
                        }
                        else if (BasePassThru)
                        {
                            WriteObject(module);
                        }
                    }
                }
                else if (ext.Equals(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
                {
                    found = true;

                    // Create the module object...
                    try
                    {
                        string moduleName = ModuleIntrinsics.GetModuleName(fileName);
                        var cdxmlScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true);

                        try
                        {
                            // generate cmdletization proxies
                            var cmdletizationXmlReader = new StringReader(cdxmlScriptInfo.ScriptContents);
                            var cmdletizationProxyModuleWriter = new StringWriter(CultureInfo.InvariantCulture);
                            var scriptWriter = new ScriptWriter(
                                cmdletizationXmlReader,
                                moduleName,
                                StringLiterals.DefaultCmdletAdapter,
                                this.MyInvocation,
                                ScriptWriter.GenerationOptions.HelpXml);

                            if (!importingModule)
                            {
                                module = new PSModuleInfo(null, fileName, null, null, cdxmlScriptInfo.DefiningLanguageMode);
                                scriptWriter.PopulatePSModuleInfo(module);
                                scriptWriter.ReportExportedCommands(module, prefix);
                            }
                            else
                            {
                                scriptWriter.WriteScriptModule(cmdletizationProxyModuleWriter);
                                ScriptBlock sb = ScriptBlock.Create(this.Context, cmdletizationProxyModuleWriter.ToString());

                                // CDXML doesn't allow script injection, so it is trusted.
                                sb.LanguageMode = PSLanguageMode.FullLanguage;

                                // proceed with regular module import
                                List<object> results;
                                module = Context.Modules.CreateModule(moduleName, fileName, sb, ss, out results, BaseArgumentList);
                                module.SetModuleBase(moduleBase);
                                scriptWriter.PopulatePSModuleInfo(module);
                                scriptWriter.ReportExportedCommands(module, prefix);

                                ImportModuleMembers(module, prefix, options);

                                AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
                            }
                        }
                        catch (Exception e)
                        {
                            string xmlErrorMessage = string.Format(
                                CultureInfo.InvariantCulture, // file name is culture agnostic, we want to copy exception message verbatim
                                CmdletizationCoreResources.ExportCimCommand_ErrorInCmdletizationXmlFile,
                                fileName,
                                e.Message);
                            throw new XmlException(xmlErrorMessage, e);
                        }

                        if (BaseAsCustomObject)
                        {
                            WriteObject(module.AsCustomObject());
                        }
                        else
                            // If -pass has been specified, emit a module info...
                            if (BasePassThru)
                        {
                            WriteObject(module);
                        }
                    }
                    catch (RuntimeException e)
                    {
                        if (writingErrors)
                        {
                            e.ErrorRecord.PreserveInvocationInfoOnce = true;
                            WriteError(e.ErrorRecord);
                        }
                    }
                }
                else
                {
                    found = true;
                    message = StringUtil.Format(Modules.InvalidModuleExtension, ext, fileName);
                    InvalidOperationException invalidOp = new InvalidOperationException(message);
                    ErrorRecord er = new ErrorRecord(invalidOp, "Modules_InvalidModuleExtension",
                        ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                }
            }
            finally
            {
                // Restore the name of the module being processed...
                Context.ModuleBeingProcessed = _origModuleBeingProcessed;
            }

            // If using AppDomain-level module path caching, add this module to the cache. This is only done for
            // the modules loaded with without version info or other qualifiers.
            if (PSModuleInfo.UseAppDomainLevelModuleCache && module != null && moduleBase == null && this.AddToAppDomainLevelCache)
            {
                // Cache using the actual name specified by the user rather than the module basename
                PSModuleInfo.AddToAppDomainLevelModuleCache(module.Name, fileName, this.BaseForce);
            }

            return module;
        }

        private void CheckForDisallowedDotSourcing(
            PSModuleInfo moduleInfo,
            ExternalScriptInfo scriptInfo,
            ImportModuleOptions options)
        {
            if (moduleInfo.SessionState == null || moduleInfo.SessionState.Internal == null)
            {
                return;
            }

            // A manifest with explicit function export is detected through a shared session state or the nested module options, because nested
            // module processing does not use a shared session state.
            var manifestWithExplicitFunctionExport = moduleInfo.SessionState.Internal.ManifestWithExplicitFunctionExport || options.AllowNestedModuleFunctionsToExport;

            // If system is in lock down mode, we disallow trusted modules that use the dotsource operator while simultaneously using
            // wild cards for exporting module functions, unless there is an overriding manifest that explicitly exports functions
            // without wild cards.
            // This is because dotsourcing brings functions into module scope and it is too easy to inadvertently or maliciously
            // expose harmful private functions that run in trusted (FullLanguage) mode.
            var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy();
            if (!manifestWithExplicitFunctionExport && moduleInfo.SessionState.Internal.FunctionsExportedWithWildcard &&
                (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) &&
                scriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage)
            {
                var dotSourceOperator = scriptInfo.GetScriptBlockAst().FindAll(ast =>
                {
                    var cmdAst = ast as CommandAst;
                    return (cmdAst?.InvocationOperator == TokenKind.Dot);
                },
                searchNestedScriptBlocks: true).FirstOrDefault();

                if (dotSourceOperator != null)
                {
                    if (systemLockdownPolicy != SystemEnforcementMode.Audit)
                    {
                        var errorRecord = new ErrorRecord(
                            new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport),
                            "Modules_SystemLockDown_CannotUseDotSourceWithWildCardFunctionExport",
                            ErrorCategory.SecurityError, null);
                        ThrowTerminatingError(errorRecord);
                    }

                    SystemPolicy.LogWDACAuditMessage(
                        context: Context,
                        title: Modules.WDACModuleDotSourceLogTitle,
                        message: StringUtil.Format(Modules.WDACModuleDotSourceLogMessage, moduleInfo.Name),
                        fqid: "ModuleImportDotSourceNotAllowed",
                        dropIntoDebugger: true);
                }
            }
        }

        private static void RemoveNestedModuleFunctions(
            ExecutionContext context,
            PSModuleInfo module,
            SystemEnforcementMode systemLockdownPolicy)
        {
            var input = module.SessionState?.Internal?.ExportedFunctions;
            if (input == null || input.Count == 0)
            {
                return;
            }

            if (systemLockdownPolicy != SystemEnforcementMode.Audit)
            {
                input.RemoveAll(fnInfo => !module.Name.Equals(fnInfo.ModuleName, StringComparison.OrdinalIgnoreCase));
                return;
            }

            SystemPolicy.LogWDACAuditMessage(
                context: context,
                title: Modules.WDACModuleFnExportWithNestedModulesLogTitle,
                message: StringUtil.Format(Modules.WDACModuleFnExportWithNestedModulesLogMessage, module.Name),
                fqid: "ModuleExportWithWildcardCharactersNotAllowed",
                dropIntoDebugger: true);
        }

        private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref bool found)
        {
            bool shouldProcessModule = true;

            // If we are in module analysis and the parent module declares non-wildcarded exports, then we don't need to
            // actually process the script module.
            if (parentModule != null)
            {
                if (shouldProcessModule && (parentModule.DeclaredFunctionExports != null) && (parentModule.DeclaredFunctionExports.Count > 0))
                {
                    shouldProcessModule = false;

                    foreach (string exportedFunction in parentModule.ExportedFunctions.Keys)
                    {
                        if (WildcardPattern.ContainsWildcardCharacters(exportedFunction))
                        {
                            shouldProcessModule = true;
                            break;
                        }
                    }

                    found = true;
                }
            }

            return shouldProcessModule;
        }

        private static readonly object s_lockObject = new object();

        private static void ClearAnalysisCaches()
        {
            lock (s_lockObject)
            {
                s_binaryAnalysisCache.Clear();
                s_scriptAnalysisCache.Clear();
            }
        }

        // Analyzes a binary module implementation for its cmdlets.
        private static readonly Dictionary<string, Tuple<BinaryAnalysisResult, Version>> s_binaryAnalysisCache =
            new Dictionary<string, Tuple<BinaryAnalysisResult, Version>>();

        /// <summary>
        /// Analyze the module assembly to find out all cmdlets and aliases defined in that assembly.
        /// </summary>
        /// <remarks>
        /// In CoreCLR, there is only one AppDomain, so we cannot spin up a new AppDomain to load the assembly and do analysis there.
        /// So we need to depend on System.Reflection.Metadata (Microsoft.Bcl.Metadata.dll) to analyze the metadata of the assembly.
        /// </remarks>
        private static BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(string path, ManifestProcessingFlags manifestProcessingFlags, out Version assemblyVersion)
        {
            Tuple<BinaryAnalysisResult, Version> tuple;

            lock (s_lockObject)
            {
                s_binaryAnalysisCache.TryGetValue(path, out tuple);
            }

            if (tuple != null)
            {
                assemblyVersion = tuple.Item2;
                return tuple.Item1;
            }

            BinaryAnalysisResult analysisResult = PowerShellModuleAssemblyAnalyzer.AnalyzeModuleAssembly(path, out assemblyVersion);
            if (analysisResult == null && Path.IsPathRooted(path))
            {
                // If we couldn't load it from a file, try finding it in our probing path
                string assemblyFilename = Path.GetFileName(path);
                analysisResult = PowerShellModuleAssemblyAnalyzer.AnalyzeModuleAssembly(assemblyFilename, out assemblyVersion);
            }

            var resultToReturn = analysisResult ?? new BinaryAnalysisResult();

            lock (s_lockObject)
            {
                s_binaryAnalysisCache[path] = Tuple.Create(resultToReturn, assemblyVersion);
            }

            return resultToReturn;
        }

        // Analyzes a script module implementation for its exports.
        private static readonly Dictionary<string, PSModuleInfo> s_scriptAnalysisCache = new Dictionary<string, PSModuleInfo>();

        private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionContext context)
        {
            // We need to return a cloned version here.
            // This is because the Get-Module -List -All modifies the returned module info and we do not want the original one changed.
            PSModuleInfo module = null;

            lock (s_lockObject)
            {
                s_scriptAnalysisCache.TryGetValue(filename, out module);
            }

            if (module != null)
                return module.Clone();

            // fake/empty manifestInfo for processing in (!loadElements) mode
            module = new PSModuleInfo(filename, null, null);

            if (!force)
            {
                var exportedCommands = AnalysisCache.GetExportedCommands(filename, true, context);

                // If we have this info cached, return from the cache.
                if (exportedCommands != null)
                {
                    foreach (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandType = pair.Value;

                        if ((commandType & CommandTypes.Alias) == CommandTypes.Alias)
                        {
                            module.AddDetectedAliasExport(commandName, null);
                        }

                        if ((commandType & CommandTypes.Function) == CommandTypes.Function)
                        {
                            module.AddDetectedFunctionExport(commandName);
                        }

                        if ((commandType & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                        {
                            module.AddDetectedCmdletExport(commandName);
                        }

                        if ((commandType & CommandTypes.Configuration) == CommandTypes.Configuration)
                        {
                            module.AddDetectedFunctionExport(commandName);
                        }
                    }

                    lock (s_lockObject)
                    {
                        s_scriptAnalysisCache[filename] = module;
                    }

                    return module;
                }
            }

            // We don't have this cached, analyze the file.
            var scriptAnalysis = ScriptAnalysis.Analyze(filename, context);

            if (scriptAnalysis == null)
            {
                return module;
            }

            List<WildcardPattern> scriptAnalysisPatterns = new List<WildcardPattern>();
            foreach (string discoveredCommandFilter in scriptAnalysis.DiscoveredCommandFilters)
            {
                scriptAnalysisPatterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase));
            }

            // Add any directly discovered exports
            foreach (var command in scriptAnalysis.DiscoveredExports)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true))
                {
                    if (!HasInvalidCharacters(command.Replace("-", string.Empty)))
                    {
                        module.AddDetectedFunctionExport(command);
                    }
                }
            }

            // Add the discovered aliases
            foreach (var pair in scriptAnalysis.DiscoveredAliases)
            {
                var commandName = pair.Key;
                // These are already filtered
                if (!HasInvalidCharacters(commandName.Replace("-", string.Empty)))
                {
                    module.AddDetectedAliasExport(commandName, pair.Value);
                }
            }

            // Add the discovered exported types
            module.AddDetectedTypeExports(scriptAnalysis.DiscoveredClasses);

            // Add any files in PsScriptRoot if it added itself to the path
            if (scriptAnalysis.AddsSelfToPath)
            {
                string baseDirectory = System.IO.Path.GetDirectoryName(filename);

                try
                {
                    foreach (string item in System.IO.Directory.EnumerateFiles(baseDirectory, "*.ps1"))
                    {
                        module.AddDetectedFunctionExport(Path.GetFileNameWithoutExtension(item));
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    // Consume this exception here
                }
            }

            // Process any referenced modules
            foreach (RequiredModuleInfo requiredModule in scriptAnalysis.DiscoveredModules)
            {
                string moduleToProcess = requiredModule.Name;
                List<PSModuleInfo> processedModules = new List<PSModuleInfo>();

                // If this has an extension, and it's a relative path,
                // then we need to ensure it's a fully-qualified path
                if ((!PathUtils.ContainsInvalidPathChars(moduleToProcess)) &&
                    Path.HasExtension(moduleToProcess) &&
                    (!Path.IsPathRooted(moduleToProcess)))
                {
                    string moduleDirectory = System.IO.Path.GetDirectoryName(filename);
                    moduleToProcess = Path.Combine(moduleDirectory, moduleToProcess);

                    PSModuleInfo fileBasedModule = CreateModuleInfoForGetModule(moduleToProcess, true);
                    if (fileBasedModule != null)
                    {
                        processedModules.Add(fileBasedModule);
                    }
                }
                else
                {
                    // This is a named module
                    processedModules.AddRange(GetModule(new string[] { moduleToProcess }, false, true));
                }

                if ((processedModules == null) || (processedModules.Count == 0))
                {
                    continue;
                }

                List<WildcardPattern> patterns = new List<WildcardPattern>();
                foreach (var discoveredCommandFilter in requiredModule.CommandsToPostFilter)
                {
                    patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase));
                }

                foreach (PSModuleInfo processedModule in processedModules)
                {
                    foreach (string commandName in processedModule.ExportedFunctions.Keys)
                    {
                        if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, patterns, true) &&
                            SessionStateUtilities.MatchesAnyWildcardPattern(commandName, scriptAnalysisPatterns, true))
                        {
                            if (!HasInvalidCharacters(commandName.Replace("-", string.Empty)))
                            {
                                module.AddDetectedFunctionExport(commandName);
                            }
                        }
                    }

                    foreach (string commandName in processedModule.ExportedCmdlets.Keys)
                    {
                        if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, patterns, true) &&
                            SessionStateUtilities.MatchesAnyWildcardPattern(commandName, scriptAnalysisPatterns, true))
                        {
                            if (!HasInvalidCharacters(commandName.Replace("-", string.Empty)))
                            {
                                module.AddDetectedCmdletExport(commandName);
                            }
                        }
                    }

                    foreach (var pair in processedModule.ExportedAliases)
                    {
                        string commandName = pair.Key;
                        if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, patterns, true) &&
                            SessionStateUtilities.MatchesAnyWildcardPattern(commandName, scriptAnalysisPatterns, true))
                        {
                            module.AddDetectedAliasExport(commandName, pair.Value.Definition);
                        }
                    }
                }
            }

            // Cache the module's exported commands
            if (!module.HadErrorsLoading)
            {
                AnalysisCache.CacheModuleExports(module, context);
            }
            else
            {
                ModuleIntrinsics.Tracer.WriteLine("Caching skipped for {0} because it had errors while loading.", module.Name);
            }

            lock (s_lockObject)
            {
                s_scriptAnalysisCache[filename] = module;
            }

            return module;
        }

        /// <summary>
        /// Load a binary module. A binary module is an assembly that should contain cmdlets.
        /// </summary>
        /// <param name="parentModule">The parent module for which this module is a nested module.</param>
        /// <param name="moduleName">The name of the snapin or assembly to load.</param>
        /// <param name="fileName">The path to the assembly to load.</param>
        /// <param name="assemblyToLoad">The assembly to load so no lookup need be done.</param>
        /// <param name="moduleBase">The module base to use for this module.</param>
        /// <param name="ss">
        /// The session state instance to use for this module. Normally binary modules don't have a session state
        /// instance, however when loaded through a module manifest with nested modules, it will have a session
        /// state instance to store the imported functions, aliases and variables.
        /// </param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The manifest processing flags to use when processing the module.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="found">Sets this to true if an assembly was found.</param>
        /// <returns>THe module info object that was created...</returns>
        internal PSModuleInfo LoadBinaryModule(
            PSModuleInfo parentModule,
            string moduleName,
            string fileName,
            Assembly assemblyToLoad,
            string moduleBase,
            SessionState ss,
            ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags,
            string prefix,
            out bool found)
        {
            return LoadBinaryModule(
                parentModule,
                moduleName,
                fileName,
                assemblyToLoad,
                moduleBase,
                ss,
                options,
                manifestProcessingFlags,
                prefix,
                out found,
                shortModuleName: null,
                disableFormatUpdates: false);
        }

        /// <summary>
        /// Load a binary module. A binary module is an assembly that should contain cmdlets.
        /// </summary>
        /// <param name="parentModule">The parent module for which this module is a nested module.</param>
        /// <param name="moduleName">The name of the snapin or assembly to load.</param>
        /// <param name="fileName">The path to the assembly to load.</param>
        /// <param name="assemblyToLoad">The assembly to load so no lookup need be done.</param>
        /// <param name="moduleBase">The module base to use for this module.</param>
        /// <param name="ss">
        ///   The session state instance to use for this module. Normally binary modules don't have a session state
        ///   instance, however when loaded through a module manifest with nested modules, it will have a session
        ///   state instance to store the imported functions, aliases and variables.
        /// </param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        /// <param name="manifestProcessingFlags">The manifest processing flags to use when processing the module.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="found">Sets this to true if an assembly was found.</param>
        /// <param name="shortModuleName">Short name for module.</param>
        /// <param name="disableFormatUpdates"></param>
        /// <returns>THe module info object that was created...</returns>
        internal PSModuleInfo LoadBinaryModule(
            PSModuleInfo parentModule,
            string moduleName,
            string fileName,
            Assembly assemblyToLoad,
            string moduleBase,
            SessionState ss,
            ImportModuleOptions options,
            ManifestProcessingFlags manifestProcessingFlags,
            string prefix,
            out bool found,
            string shortModuleName,
            bool disableFormatUpdates)
        {
            if (string.IsNullOrEmpty(moduleName) && string.IsNullOrEmpty(fileName) && assemblyToLoad == null)
            {
                throw PSTraceSource.NewArgumentNullException("moduleName,fileName,assemblyToLoad");
            }

            bool isParentEngineModule = parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name);

            // Load the dll and process any cmdlets it might contain...
            InitialSessionState iss = InitialSessionState.Create();
            List<string> detectedCmdlets = null;
            List<Tuple<string, string>> detectedAliases = null;
            Assembly assembly = null;
            string modulePath = string.Empty;
            Version assemblyVersion = new Version(0, 0, 0, 0);
            bool importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0;

            // See if we're loading a straight assembly...
            if (assemblyToLoad != null)
            {
                // Figure out what to use for a module path...
                modulePath = string.IsNullOrEmpty(fileName) ? assemblyToLoad.Location : fileName;

                // And what to use for a module name...
                if (string.IsNullOrEmpty(moduleName))
                {
                    moduleName = "dynamic_code_module_" + assemblyToLoad.FullName;
                }

                if (importingModule)
                {
                    // Passing module as a parameter here so that the providers can have the module property populated.
                    // For engine providers, the module should point to top-level module name
                    // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation
                    iss.ImportCmdletsFromAssembly(assemblyToLoad, isParentEngineModule ? parentModule : null);
                }

                assemblyVersion = GetAssemblyVersionNumber(assemblyToLoad);
                assembly = assemblyToLoad;

                // Use the parent module name for caching if there is one.
                string source = parentModule?.Name ?? moduleName;
                // Add it to the assembly cache if it isn't already there.
                Context.AddToAssemblyCache(source, assembly);
            }
            else if (importingModule)
            {
                // Use the parent module name for caching if there is one.
                string source = parentModule?.Name ?? moduleName;
                assembly = Context.AddAssembly(source, moduleName, fileName, out Exception error);

                if (assembly == null)
                {
                    if (error != null)
                    {
                        throw error;
                    }

                    found = false;
                    return null;
                }

                assemblyVersion = GetAssemblyVersionNumber(assembly);
                modulePath = string.IsNullOrEmpty(fileName) ? assembly.Location : fileName;

                // Passing module as a parameter here so that the providers can have the module property populated.
                // For engine providers, the module should point to top-level module name
                // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation
                iss.ImportCmdletsFromAssembly(assembly, isParentEngineModule ? parentModule : null);
            }
            else
            {
                string binaryPath = fileName;
                modulePath = fileName;
                binaryPath ??= System.IO.Path.Combine(moduleBase, moduleName);

                BinaryAnalysisResult analysisResult = GetCmdletsFromBinaryModuleImplementation(binaryPath, manifestProcessingFlags, out assemblyVersion);
                detectedCmdlets = analysisResult.DetectedCmdlets;
                detectedAliases = analysisResult.DetectedAliases;
            }

            found = true;
            string nameToUse = string.IsNullOrEmpty(shortModuleName) ? moduleName : shortModuleName;
            PSModuleInfo module = new PSModuleInfo(nameToUse, modulePath, Context, ss);

            module.SetModuleType(ModuleType.Binary);
            module.SetModuleBase(moduleBase);
            module.SetVersion(assemblyVersion);
            module.ImplementingAssembly = assembly;

            if (importingModule)
            {
                SetModuleLoggingInformation(module);
            }

            // Add the module info the providers...
            foreach (SessionStateProviderEntry sspe in iss.Providers)
            {
                // For engine providers, the module should point to top-level module name
                // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation
                sspe.SetModule(isParentEngineModule ? parentModule : module);
            }

            // Add all of the exported cmdlets to the module object...
            if (iss.Commands != null)
            {
                foreach (SessionStateCommandEntry commandEntry in iss.Commands)
                {
                    commandEntry.SetModule(module);

                    // A binary module can only directly export cmdlets, so cmdletEntry should never be null.
                    // With nested modules in a manifest, there may be a session state attached to
                    // this module in which case we add the exported cmdlets to the existing list.
                    SessionStateCmdletEntry cmdletEntry = commandEntry as SessionStateCmdletEntry;
                    SessionStateAliasEntry aliasEntry = null;
                    if (cmdletEntry == null)
                    {
                        aliasEntry = commandEntry as SessionStateAliasEntry;
                    }

                    Dbg.Assert((cmdletEntry != null || aliasEntry != null), "When importing a binary module, the commands entry should only have cmdlets/aliases in it");
                    if (ss != null)
                    {
                        if (cmdletEntry != null)
                        {
                            ss.Internal.ExportedCmdlets.Add(CommandDiscovery.NewCmdletInfo(cmdletEntry, this.Context));
                        }
                        else if (aliasEntry != null)
                        {
                            ss.Internal.ExportedAliases.Add(CommandDiscovery.NewAliasInfo(aliasEntry, this.Context));
                        }
                    }
                    else
                    {
                        // If there is no session state, we need to attach the entry to the module instead
                        // of the session state.
                        if (cmdletEntry != null)
                        {
                            module.AddExportedCmdlet(CommandDiscovery.NewCmdletInfo(cmdletEntry, this.Context));
                        }
                        else if (aliasEntry != null)
                        {
                            module.AddExportedAlias(CommandDiscovery.NewAliasInfo(aliasEntry, this.Context));
                        }
                    }
                }
            }

            // If there were any cmdlets that were detected, add those.
            if (detectedCmdlets != null)
            {
                foreach (string detectedCmdlet in detectedCmdlets)
                {
                    module.AddDetectedCmdletExport(detectedCmdlet);
                }
            }

            // If there were any aliases that were detected, add those.
            if (detectedAliases != null)
            {
                foreach (Tuple<string, string> detectedAlias in detectedAliases)
                {
                    module.AddDetectedAliasExport(detectedAlias.Item1, detectedAlias.Item2);
                }
            }

            // If any command patterns where specified, then only import the
            // commands matching the patterns...
            if (BaseCmdletPatterns != null)
            {
                InitialSessionStateEntryCollection<SessionStateCommandEntry> commands = iss.Commands;
                // Remove all of the command entries that aren't matched by a pattern
                // in the pattern list...
                for (int i = commands.Count - 1; i >= 0; i--)
                {
                    SessionStateCommandEntry e = commands[i];
                    if (e == null)
                        continue;
                    string name = e.Name;
                    if (string.IsNullOrEmpty(name))
                        continue;
                    if (!SessionStateUtilities.MatchesAnyWildcardPattern(name, BaseCmdletPatterns, false))
                    {
                        commands.RemoveItem(i);
                    }
                }
            }

            // use the -Prefix parameter to change the names of imported commands
            foreach (SessionStateCommandEntry commandEntry in iss.Commands)
            {
                commandEntry.Name = AddPrefixToCommandName(commandEntry.Name, prefix);
            }

            SessionStateInternal oldSessionState = Context.EngineSessionState;

            if (importingModule)
            {
                try
                {
                    // If we have a session state instance, set it to be the engine sessionstate
                    // for the duration of the bind.
                    if (ss != null)
                    {
                        Context.EngineSessionState = ss.Internal;
                    }

                    if (disableFormatUpdates)
                        iss.DisableFormatUpdates = true;

                    // Load the cmdlets and providers, bound to the new module...
                    iss.Bind(Context, updateOnly: true, module, options.NoClobber, options.Local, setLocation: false);

                    // Scan all of the types in the assembly to register JobSourceAdapters.
                    IEnumerable<Type> allTypes = assembly?.ExportedTypes ?? Array.Empty<Type>();
                    foreach (Type type in allTypes)
                    {
                        // If it derives from JobSourceAdapter and it's not already registered, register it...
                        // Add the second check since SMA could also be loaded via Import-Module
                        if (typeof(JobSourceAdapter).IsAssignableFrom(type) && typeof(JobSourceAdapter) != type)
                        {
                            if (!JobManager.IsRegistered(type.Name))
                            {
                                JobManager.RegisterJobSourceAdapter(type);
                            }
                        }
                    }
                }
                finally
                {
                    Context.EngineSessionState = oldSessionState;
                }
            }

            // WriteVerbose all of the imported cmdlets ...
            string snapInPrefix = module.Name + "\\";
            bool checkVerb = !BaseDisableNameChecking;
            bool checkNoun = !BaseDisableNameChecking;
            foreach (SessionStateCommandEntry ssce in iss.Commands)
            {
                if (ssce._isImported)
                {
                    try
                    {
                        if (ssce is SessionStateCmdletEntry || ssce is SessionStateFunctionEntry)
                        {
                            ValidateCommandName(this, ssce.Name, module.Name, ref checkVerb, ref checkNoun);
                        }

                        // Lookup using the module qualified name....
                        string name = snapInPrefix + ssce.Name;
                        CommandInvocationIntrinsics.GetCmdlet(name, Context);
                    }
                    catch (CommandNotFoundException cnfe)
                    {
                        // Handle the errors generated by duplicate commands...
                        WriteError(cnfe.ErrorRecord);
                    }

                    string message = StringUtil.Format(ssce.CommandType == CommandTypes.Alias ? Modules.ImportingAlias : Modules.ImportingCmdlet, ssce.Name);
                    WriteVerbose(message);
                }
                else
                {
                    // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                    string message = StringUtil.Format(Modules.ImportModuleNoClobberForCmdlet, ssce.Name);
                    WriteVerbose(message);
                }
            }

            // Add the module being imported to the list of child modules for the current module
            // if it hasn't already been added...
            if (importingModule)
            {
                AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
            }

            return module;
        }

        private static Version GetAssemblyVersionNumber(Assembly assemblyToLoad)
        {
            Version assemblyVersion;

            // Get the assembly version...
            try
            {
                AssemblyName asn = assemblyToLoad.GetName();
                assemblyVersion = asn.Version;
            }
            catch (Exception)
            {
                assemblyVersion = new Version(0, 0);
            }

            return assemblyVersion;
        }

        internal static string AddPrefixToCommandName(string commandName, string prefix)
        {
            Dbg.Assert(commandName != null, "Caller should verify that commandName argument != null");

            if (string.IsNullOrEmpty(prefix))
                return commandName;

            string verb;
            string noun;
            if (CmdletInfo.SplitCmdletName(commandName, out verb, out noun))
            {
                commandName = verb + "-" + prefix + noun;
            }
            else
            {
                commandName = prefix + commandName;
            }

            return commandName;
        }

        /// <summary>
        /// Removes prefix from a command name and returns the command name.
        /// </summary>
        /// <param name="commandName">The command name from which the prefix needs to be removed.</param>
        /// <param name="prefix">The string containing the prefix.</param>
        /// <returns>The command name without the prefix.</returns>
        internal static string RemovePrefixFromCommandName(string commandName, string prefix)
        {
            Dbg.Assert(commandName != null, "Caller should verify that commandName argument != null");
            Dbg.Assert(prefix != null, "Caller should verify that prefix argument != null");

            string result = commandName;

            if (string.IsNullOrEmpty(prefix))
                return result;

            string verb;
            string noun;
            if (CmdletInfo.SplitCmdletName(commandName, out verb, out noun))
            {
                if (noun.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                {
                    string originalNoun = noun.Substring(prefix.Length, noun.Length - prefix.Length);
                    result = verb + "-" + originalNoun;
                }
            }
            else
            {
                if (commandName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                {
                    result = commandName.Substring(prefix.Length, commandName.Length - prefix.Length);
                }
            }

            return result;
        }

        internal static bool IsPrefixedCommand(CommandInfo commandInfo)
        {
            Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo is not null");
            Dbg.Assert(!string.IsNullOrEmpty(commandInfo.Prefix), "Caller should verify that the commandInfo has prefix");

            string verb, noun;
            bool isPrefixed = CmdletInfo.SplitCmdletName(commandInfo.Name, out verb, out noun)
                             ? noun.StartsWith(commandInfo.Prefix, StringComparison.OrdinalIgnoreCase)
                             : commandInfo.Name.StartsWith(commandInfo.Prefix, StringComparison.OrdinalIgnoreCase);

            return isPrefixed;
        }

        internal static void AddModuleToModuleTables(ExecutionContext context, SessionStateInternal targetSessionState, PSModuleInfo module)
        {
            Dbg.Assert(context != null, "Caller should verify that context != null");
            Dbg.Assert(targetSessionState != null, "Caller should verify that targetSessionState != null");
            Dbg.Assert(module != null, "Caller should verify that module != null");

            // if the module path is empty (assembly module in memory), we add the modulename as key
            string moduleTableKey;
            if (module.Path != string.Empty)
            {
                moduleTableKey = module.Path;
            }
            else
            {
                moduleTableKey = module.Name;
            }

            if (!context.Modules.ModuleTable.ContainsKey(moduleTableKey))
            {
                context.Modules.ModuleTable.Add(moduleTableKey, module);
            }

            if (context.previousModuleImported.ContainsKey(module.Name))
            {
                context.previousModuleImported.Remove(module.Name);
            }

            context.previousModuleImported.Add(module.Name, module.Path);

            if (!targetSessionState.ModuleTable.ContainsKey(moduleTableKey))
            {
                targetSessionState.ModuleTable.Add(moduleTableKey, module);
                targetSessionState.ModuleTableKeys.Add(moduleTableKey);
            }

            targetSessionState.Module?.AddNestedModule(module);
        }

        /// <summary>
        /// Import the script-level functions from one session state to another, calling
        /// WriteVerbose for each imported member...
        /// </summary>
        /// <param name="sourceModule">The session state instance to use as the source of the functions.</param>
        /// <param name="prefix">Command name prefix.</param>
        protected internal void ImportModuleMembers(PSModuleInfo sourceModule, string prefix)
        {
            ImportModuleOptions importModuleOptions = new ImportModuleOptions();
            ImportModuleMembers(
                this,
                this.TargetSessionState.Internal,
                sourceModule,
                prefix,
                this.BaseFunctionPatterns,
                this.BaseCmdletPatterns,
                this.BaseVariablePatterns,
                this.BaseAliasPatterns,
                importModuleOptions);
        }

        /// <summary>
        /// Import the script-level functions from one session state to another, calling
        /// WriteVerbose for each imported member...
        /// </summary>
        /// <param name="sourceModule">The session state instance to use as the source of the functions.</param>
        /// <param name="prefix">Command name prefix.</param>
        /// <param name="options">The set of options that are used while importing a module.</param>
        protected internal void ImportModuleMembers(PSModuleInfo sourceModule, string prefix, ImportModuleOptions options)
        {
            ImportModuleMembers(
                this,
                this.TargetSessionState.Internal,
                sourceModule,
                prefix,
                this.BaseFunctionPatterns,
                this.BaseCmdletPatterns,
                this.BaseVariablePatterns,
                this.BaseAliasPatterns,
                options);
        }

        internal static void ImportModuleMembers(
            ModuleCmdletBase cmdlet,
            SessionStateInternal targetSessionState,
            PSModuleInfo sourceModule,
            string prefix,
            List<WildcardPattern> functionPatterns,
            List<WildcardPattern> cmdletPatterns,
            List<WildcardPattern> variablePatterns,
            List<WildcardPattern> aliasPatterns,
            ImportModuleOptions options)
        {
            if (sourceModule == null)
                throw PSTraceSource.NewArgumentNullException(nameof(sourceModule));

            bool isImportModulePrivate = cmdlet.CommandInfo.Visibility == SessionStateEntryVisibility.Private ||
                targetSessionState.DefaultCommandVisibility == SessionStateEntryVisibility.Private;
            bool usePrefix = !string.IsNullOrEmpty(prefix);

            bool checkVerb = !cmdlet.BaseDisableNameChecking;
            bool checkNoun = !cmdlet.BaseDisableNameChecking;

            // Add the module being imported to the list of child modules for the current module
            // if it hasn't already been added...
            // TODO/FIXME: we should be calling AddModuleToModuleTables here but we can't
            //             because of the inconsistency with which dynamic modules should
            //             or should not be included in the global modules table
            if (targetSessionState.Module != null)
            {
                bool present = false;
                foreach (PSModuleInfo m in targetSessionState.Module.NestedModules)
                {
                    if (m.Path.Equals(sourceModule.Path, StringComparison.OrdinalIgnoreCase))
                        present = true;
                }

                if (!present)
                {
                    targetSessionState.Module.AddNestedModule(sourceModule);
                }
            }

            SessionStateInternal source = null;
            if (sourceModule.SessionState != null)
            {
                source = sourceModule.SessionState.Internal;
            }

            // True if none of -function, -cmdlet, -variable or -alias are specified
            bool noPatternsSpecified = functionPatterns == null &&
                variablePatterns == null && aliasPatterns == null && cmdletPatterns == null;

            // mapping from original to prefixed names (prefixed using -Prefix parameter of the cmdlet)
            // used to modify AliasInfo.Definition if necessary
            Dictionary<string, string> original2prefixedName = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            // We always load the cmdlets even if there is no session state which is
            // the case with a binary module.
            string message = null;
            foreach (CmdletInfo cmdletToImport in sourceModule.CompiledExports)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(cmdletToImport.Name, cmdletPatterns, noPatternsSpecified))
                {
                    if (options.NoClobber && CommandFound(cmdletToImport.Name, targetSessionState))
                    {
                        // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                        message = StringUtil.Format(Modules.ImportModuleNoClobberForCmdlet, cmdletToImport.Name);
                        cmdlet.WriteVerbose(message);
                        continue;
                    }

                    CmdletInfo prefixedCmdlet = new CmdletInfo(
                        AddPrefixToCommandName(cmdletToImport.Name, prefix),
                        cmdletToImport.ImplementingType,
                        cmdletToImport.HelpFile,
                        cmdletToImport.PSSnapIn,
                        cmdlet.Context);
                    SetCommandVisibility(isImportModulePrivate, prefixedCmdlet);
                    prefixedCmdlet.Module = sourceModule;
                    if (usePrefix)
                    {
                        original2prefixedName.Add(cmdletToImport.Name, prefixedCmdlet.Name);
                        cmdletToImport.Prefix = prefix;
                        prefixedCmdlet.Prefix = prefix;
                    }

                    ValidateCommandName(cmdlet, prefixedCmdlet.Name, sourceModule.Name, ref checkVerb, ref checkNoun);

                    var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope;
                    scope.AddCmdletToCache(prefixedCmdlet.Name, prefixedCmdlet, CommandOrigin.Internal, targetSessionState.ExecutionContext);

                    cmdletToImport.IsImported = true;

                    // Write directly into the local cmdlet cache table...
                    message = StringUtil.Format(Modules.ImportingCmdlet, prefixedCmdlet.Name);
                    cmdlet.WriteVerbose(message);
                }
            }

            foreach (AliasInfo aliasToImport in sourceModule.CompiledAliasExports)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(aliasToImport.Name, aliasPatterns, noPatternsSpecified))
                {
                    string prefixedAliasName = AddPrefixToCommandName(aliasToImport.Name, prefix);
                    string prefixedAliasDefinition;
                    if (!usePrefix || !original2prefixedName.TryGetValue(aliasToImport.Definition, out prefixedAliasDefinition))
                    {
                        prefixedAliasDefinition = aliasToImport.Definition;
                    }

                    if (options.NoClobber && CommandFound(prefixedAliasName, targetSessionState))
                    {
                        // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                        message = StringUtil.Format(Modules.ImportModuleNoClobberForAlias, prefixedAliasName);
                        cmdlet.WriteVerbose(message);
                        continue;
                    }

                    var prefixedAlias = new AliasInfo(
                        prefixedAliasName,
                        prefixedAliasDefinition,
                        cmdlet.Context);
                    SetCommandVisibility(isImportModulePrivate, prefixedAlias);
                    prefixedAlias.Module = sourceModule;
                    if (usePrefix)
                    {
                        if (!original2prefixedName.ContainsKey(aliasToImport.Name))
                        {
                            original2prefixedName.Add(aliasToImport.Name, prefixedAlias.Name);
                        }

                        aliasToImport.Prefix = prefix;
                        prefixedAlias.Prefix = prefix;
                    }

                    var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope;
                    scope.SetAliasItem(prefixedAlias, false);

                    aliasToImport.IsImported = true;

                    message = StringUtil.Format(Modules.ImportingAlias, prefixedAlias.Name);
                    cmdlet.WriteVerbose(message);
                }
            }

            // Only process functions, variables and aliases if there is a session state
            // associated with the source module.
            if (source != null)
            {
                foreach (FunctionInfo func in sourceModule.ExportedFunctions.Values)
                {
                    ImportFunctions(func, targetSessionState, sourceModule, functionPatterns, noPatternsSpecified, prefix, options, usePrefix, ref checkVerb, ref checkNoun, original2prefixedName, cmdlet, isImportModulePrivate, isFunction: true);
                }

                // Import any exported variables...
                foreach (PSVariable v in sourceModule.ExportedVariables.Values)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(v.Name, variablePatterns, noPatternsSpecified))
                    {
                        if (options.NoClobber && (targetSessionState.ModuleScope.GetVariable(v.Name) != null))
                        {
                            // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                            message = StringUtil.Format(Modules.ImportModuleNoClobberForVariable, v.Name);
                            cmdlet.WriteVerbose(message);
                            continue;
                        }
                        // Set the module on the variable...
                        v.SetModule(sourceModule);

                        var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope;
                        PSVariable newVariable = scope.NewVariable(v, true, source);

                        if (isImportModulePrivate)
                        {
                            newVariable.Visibility = SessionStateEntryVisibility.Private;
                        }

                        message = StringUtil.Format(Modules.ImportingVariable, v.Name);
                        cmdlet.WriteVerbose(message);
                    }
                }

                // Import any exported aliases...
                foreach (AliasInfo ai in sourceModule.ExportedAliases.Values)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(ai.Name, aliasPatterns, noPatternsSpecified))
                    {
                        string prefixedAliasName = AddPrefixToCommandName(ai.Name, prefix);
                        string prefixedAliasDefinition;
                        if (!usePrefix || !original2prefixedName.TryGetValue(ai.Definition, out prefixedAliasDefinition))
                        {
                            prefixedAliasDefinition = ai.Definition;
                        }

                        if (options.NoClobber && CommandFound(prefixedAliasName, targetSessionState))
                        {
                            // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                            message = StringUtil.Format(Modules.ImportModuleNoClobberForAlias, prefixedAliasName);
                            cmdlet.WriteVerbose(message);
                            continue;
                        }

                        AliasInfo prefixedAlias = new AliasInfo(
                            prefixedAliasName,
                            prefixedAliasDefinition,
                            cmdlet.Context);
                        SetCommandVisibility(isImportModulePrivate, prefixedAlias);
                        prefixedAlias.Module = sourceModule;

                        if (usePrefix)
                        {
                            if (!original2prefixedName.ContainsKey(ai.Name))
                            {
                                original2prefixedName.Add(ai.Name, prefixedAlias.Name);
                            }

                            ai.Prefix = prefix;
                            prefixedAlias.Prefix = prefix;
                        }

                        var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope;
                        scope.SetAliasItem(prefixedAlias, false, CommandOrigin.Internal);

                        ai.IsImported = true;

                        message = StringUtil.Format(Modules.ImportingAlias, prefixedAlias.Name);
                        cmdlet.WriteVerbose(message);
                    }
                }
            }
        }

        private static void ImportFunctions(FunctionInfo func, SessionStateInternal targetSessionState, PSModuleInfo sourceModule, List<WildcardPattern> functionPatterns, bool noPatternsSpecified,
            string prefix, ImportModuleOptions options, bool usePrefix, ref bool checkVerb, ref bool checkNoun, Dictionary<string, string> original2prefixedName, ModuleCmdletBase cmdlet, bool isImportModulePrivate, bool isFunction)
        {
            string message = null;
            if (SessionStateUtilities.MatchesAnyWildcardPattern(func.Name, functionPatterns, noPatternsSpecified))
            {
                string prefixedName = AddPrefixToCommandName(func.Name, prefix);

                if (options.NoClobber && CommandFound(prefixedName, targetSessionState))
                {
                    // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment.
                    message = StringUtil.Format(Modules.ImportModuleNoClobberForFunction, func.Name);
                    cmdlet.WriteVerbose(message);
                    return;
                }

                var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope;
                // Write directly into the function table...
                FunctionInfo functionInfo = scope.SetFunction(
                    prefixedName,
                    func.ScriptBlock,
                    func,
                    false,
                    CommandOrigin.Internal,
                    targetSessionState.ExecutionContext);

                // Note that the module 'func' and the function table 'functionInfo' instances are now linked
                // together (see 'CopiedCommand' in CommandInfo class), so setting visibility on one also
                // sets it on the other.
                SetCommandVisibility(isImportModulePrivate, functionInfo);
                functionInfo.Module = sourceModule;

                func.IsImported = true;
                if (usePrefix)
                {
                    original2prefixedName.Add(func.Name, prefixedName);
                    func.Prefix = prefix;
                    functionInfo.Prefix = prefix;
                }

                ValidateCommandName(cmdlet, functionInfo.Name, sourceModule.Name, ref checkNoun, ref checkVerb);
                message = StringUtil.Format(Modules.ImportingFunction, prefixedName);
                cmdlet.WriteVerbose(message);
            }
        }

        private static void SetCommandVisibility(bool isImportModulePrivate, CommandInfo command)
        {
            if (isImportModulePrivate)
            {
                command.Visibility = SessionStateEntryVisibility.Private;
            }
        }

        internal static bool CommandFound(string commandName, SessionStateInternal sessionStateInternal)
        {
            EventHandler<CommandLookupEventArgs> oldCommandNotFoundAction =
                sessionStateInternal.ExecutionContext.EngineIntrinsics.InvokeCommand.CommandNotFoundAction;
            try
            {
                sessionStateInternal.ExecutionContext.EngineIntrinsics.InvokeCommand.CommandNotFoundAction = null;
                CommandSearcher searcher = new CommandSearcher(
                            commandName,
                            SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns,
                            CommandTypes.Alias | CommandTypes.Function | CommandTypes.Cmdlet | CommandTypes.Configuration,
                            sessionStateInternal.ExecutionContext);

                if (!searcher.MoveNext())
                {
                    return false;
                }

                return true;
            }
            finally
            {
                sessionStateInternal.ExecutionContext.EngineIntrinsics.InvokeCommand.CommandNotFoundAction = oldCommandNotFoundAction;
            }
        }

        private static bool HasInvalidCharacters(string commandName)
        {
            foreach (char c in commandName)
            {
                switch (c)
                {
                    case '#':
                    case ',':
                    case '(':
                    case ')':
                    case '{':
                    case '}':
                    case '[':
                    case ']':
                    case '&':
                    case '-':
                    case '/':
                    case '\\':
                    case '$':
                    case '^':
                    case ';':
                    case ':':
                    case '"':
                    case '\'':
                    case '<':
                    case '>':
                    case '|':
                    case '?':
                    case '@':
                    case '`':
                    case '*':
                    case '%':
                    case '+':
                    case '=':
                    case '~':
                        return true;
                }
            }

            return false;
        }

        private static void ValidateCommandName(ModuleCmdletBase cmdlet,
                                                string commandName,
                                                string moduleName,
                                                ref bool checkVerb,
                                                ref bool checkNoun)
        {
            string verb;
            string noun;
            string message;

            if (!CmdletInfo.SplitCmdletName(commandName, out verb, out noun))
                return;

            if (!Verbs.IsStandard(verb))
            {
                // A hack for Sort-Object and Tee-Object as they have non-standard verbs
                // With engine dlls being loaded as modules, introducing the additional check to avoid warning message
                if (!commandName.Equals("Sort-Object", StringComparison.OrdinalIgnoreCase) && !commandName.Equals("Tee-Object", StringComparison.OrdinalIgnoreCase))
                {
                    if (checkVerb)
                    {
                        checkVerb = false;
                        message = StringUtil.Format(Modules.ImportingNonStandardVerb, moduleName);
                        cmdlet.WriteWarning(message);
                    }

                    string[] alternates = Verbs.SuggestedAlternates(verb);
                    if (alternates == null)
                    {
                        message = StringUtil.Format(Modules.ImportingNonStandardVerbVerbose, commandName, moduleName);
                        cmdlet.WriteVerbose(message);
                    }
                    else
                    {
                        var suggestions = string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, alternates);
                        message = StringUtil.Format(Modules.ImportingNonStandardVerbVerboseSuggestion, commandName, suggestions, moduleName);
                        cmdlet.WriteVerbose(message);
                    }
                }
            }

            if (HasInvalidCharacters(noun))
            {
                if (checkNoun)
                {
                    message = Modules.ImportingNonStandardNoun;
                    cmdlet.WriteWarning(message);
                    checkNoun = false;
                }

                message = StringUtil.Format(Modules.ImportingNonStandardNounVerbose, commandName, moduleName);
                cmdlet.WriteVerbose(message);
                return;
            }
        }

        /// <summary>
        /// Returns the context cached ModuleTable module for import only if found and has safe language boundaries while
        /// exporting all functions by default.
        ///
        /// This protects cached trusted modules that exported all functions in a trusted context, from being re-used
        /// in an untrusted context and thus exposing functions that were meant to be private in that context.
        ///
        /// Returning false forces module import to re-import the module from file with the current context and prevent
        /// all module functions from being exported by default.
        ///
        /// Note that module loading order is important with this check when the system is *locked down with DeviceGuard*.
        /// If a submodule that does not explicitly export any functions is imported from the command line, its useless
        /// because no functions are exported (default fn export is explicitly disallowed on locked down systems).
        /// But if a parentmodule that imports the submodule is then imported, it will get the useless version of the
        /// module from the ModuleTable and the parent module will not work.
        ///   $mSub = import-module SubModule  # No functions exported, useless
        ///   $mParent = import-module ParentModule  # This internally imports SubModule
        ///   $mParent.DoSomething  # This will likely be broken because SubModule functions are not accessible
        /// But this is not a realistic scenario because SubModule is useless with DeviceGuard lock down and must explicitly
        /// export its functions to become useful, at which point this check is no longer in effect and there is no issue.
        ///   $mSub = import-module SubModule  # Explicitly exports functions, useful
        ///   $mParent = import-module ParentModule  # This internally imports SubModule
        ///   $mParent.DoSomething  # This works because SubModule functions are exported and accessible.
        /// </summary>
        /// <param name="key">Key.</param>
        /// <param name="moduleInfo">PSModuleInfo.</param>
        /// <param name="toRemove">True if module item is to be removed.</param>
        /// <returns>True if module found in table and is safe to use.</returns>
        internal bool TryGetFromModuleTable(string key, out PSModuleInfo moduleInfo, bool toRemove = false)
        {
            var foundModule = Context.Modules.ModuleTable.TryGetValue(key, out moduleInfo);

            // Check for unsafe language modes between module load context and current context.
            // But only for script modules that exported all functions in a trusted (FL) context.
            if (foundModule &&
                !toRemove &&
                moduleInfo.ModuleType == ModuleType.Script &&
                Context.LanguageMode == PSLanguageMode.ConstrainedLanguage &&
                moduleInfo.LanguageMode == PSLanguageMode.FullLanguage &&
                moduleInfo.ModuleAutoExportsAllFunctions)
            {
                moduleInfo = null;
                return false;
            }

            return foundModule;
        }
    }

    /// <summary>
    /// Holds the result of a binary module analysis.
    /// </summary>
    internal class BinaryAnalysisResult
    {
        /// <summary>
        /// The list of cmdlets detected from the binary.
        /// </summary>
        internal List<string> DetectedCmdlets { get; set; }

        // The list of aliases detected from the binary.
        internal List<Tuple<string, string>> DetectedAliases { get; set; }
    }

    #endregion ModuleCmdletBase
}