Merge pull request #1001 from PowerShell/andschwa/import-sd

Merge Source Depot changes
This commit is contained in:
Andy Schwartzmeyer committed 2016-05-18 18:04:05 -07:00
commit 8ae0d2fd53
38 files changed
+5974 -245

No files matched your search

+6
View File
@@ -7,6 +7,12 @@ temporarily from `Microsoft.PowerShell.Commands.Management` because we
cannot resolve `[Shell32.ShellFolderItem]` for FullCLR builds. This must be cannot resolve `[Shell32.ShellFolderItem]` for FullCLR builds. This must be
fixed ASAP. fixed ASAP.
## `GetComputerInfoCommand.cs`
The file
`src\Microsoft.PowerShell.Commands.Management\commands\management\GetComputerInfoCommand.cs`
is not currently compiled because it needs resources.
## xUnit ## xUnit
The xUnit tests can only be run on Linux. The xUnit tests can only be run on Linux.
+2
View File
@@ -110,6 +110,7 @@
"src/monad/monad/src/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs": "src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs", "src/monad/monad/src/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs": "src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs",
"src/monad/monad/src/cimSupport/cmdletization/SessionBasedWrapper.cs": "src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs", "src/monad/monad/src/cimSupport/cmdletization/SessionBasedWrapper.cs": "src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs",
"src/monad/monad/src/commands/management/AddContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs", "src/monad/monad/src/commands/management/AddContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs",
"src/monad/monad/src/commands/management/CIMHelper.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs",
"src/monad/monad/src/commands/management/ClearContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs", "src/monad/monad/src/commands/management/ClearContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs",
"src/monad/monad/src/commands/management/ClearPropertyCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs", "src/monad/monad/src/commands/management/ClearPropertyCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs",
"src/monad/monad/src/commands/management/ClearRecycleBinCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs", "src/monad/monad/src/commands/management/ClearRecycleBinCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs",
@@ -123,6 +124,7 @@
"src/monad/monad/src/commands/management/Eventlog.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs", "src/monad/monad/src/commands/management/Eventlog.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs",
"src/monad/monad/src/commands/management/GetChildrenCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs", "src/monad/monad/src/commands/management/GetChildrenCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs",
"src/monad/monad/src/commands/management/GetClipboardCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs", "src/monad/monad/src/commands/management/GetClipboardCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs",
"src/monad/monad/src/commands/management/GetComputerInfoCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs",
"src/monad/monad/src/commands/management/GetContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs", "src/monad/monad/src/commands/management/GetContentCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs",
"src/monad/monad/src/commands/management/GetPropertyCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs", "src/monad/monad/src/commands/management/GetPropertyCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs",
"src/monad/monad/src/commands/management/GetTransactionCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs", "src/monad/monad/src/commands/management/GetTransactionCommand.cs": "src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs",
@@ -0,0 +1,342 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Management.Infrastructure;
namespace Microsoft.PowerShell.Commands
{
using Extensions;
internal static class CIMHelper
{
internal static class ClassNames
{
internal const string OperatingSystem = "Win32_OperatingSystem";
internal const string PageFileUsage = "Win32_PageFileUsage";
internal const string Bios = "Win32_BIOS";
internal const string BaseBoard = "Win32_BaseBoard";
internal const string ComputerSystem = "Win32_ComputerSystem";
internal const string Keyboard = "Win32_Keyboard";
internal const string DeviceGuard = "Win32_DeviceGuard";
internal const string HotFix = "Win32_QuickFixEngineering";
internal const string MicrosoftNetworkAdapter = "MSFT_NetAdapter";
internal const string NetworkAdapter = "Win32_NetworkAdapter";
internal const string NetworkAdapterConfiguration = "Win32_NetworkAdapterConfiguration";
internal const string Processor = "Win32_Processor";
internal const string PhysicalMemory = "Win32_PhysicalMemory";
internal const string TimeZone = "Win32_TimeZone";
}
internal const string DefaultNamespace = @"root\cimv2";
internal const string DeviceGuardNamespace = @"root\Microsoft\Windows\DeviceGuard";
internal const string MicrosoftNetworkAdapterNamespace = "root/StandardCimv2";
internal const string DefaultQueryDialect = "WQL";
/// <summary>
/// Create a WQL query string to retrieve all properties from
/// the specified WMI class.
/// </summary>
/// <param name="from">A string containing the WMI class name.</param>
/// <returns>
/// A string containing the WQL query string
/// </returns>
internal static string WqlQueryAll(string from)
{
return "SELECT * from " + from;
}
/// <summary>
/// Retrieve a new object of type T, whose properties and fields are
/// populated from an instance of the named WMI class. If the CIM
/// query results in multiple instances, only the first instance is
/// returned.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="nameSpace">
/// A string containing the namespace to run the query against
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant object.
/// </param>
/// <returns>
/// A new object of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T GetFirst<T>(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
{
if (string.IsNullOrEmpty(wmiClassName))
throw new ArgumentException("String argument may not be null or empty", "wmiClassName");
try
{
var type = typeof(T);
var binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
T rv = new T();
using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName)))
{
SetObjectDataMembers(rv, binding, instance);
}
return rv;
}
catch (Exception /*ex*/)
{
// on any error fall through to the null return below
}
return null;
}
/// <summary>
/// Retrieve an array of new objects of type T, whose properties and fields are
/// populated from an instance of the specified WMI class on the specified CIM
/// session.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="nameSpace">
/// A string containing the namespace to run the query against
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant array elements.
/// </param>
/// <returns>
/// An array of new objects of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T[] GetAll<T>(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
{
if (string.IsNullOrEmpty(wmiClassName))
throw new ArgumentException("String argument may not be null or empty", "wmiClassName");
var rv = new List<T>();
try
{
var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName));
if (instances != null)
{
var type = typeof(T);
var binding = BindingFlags.Public | BindingFlags.Instance;
foreach (var instance in instances)
{
T objT = new T();
using (instance)
{
SetObjectDataMembers(objT, binding, instance);
}
rv.Add(objT);
}
}
}
catch (Exception /*ex*/)
{
// on any error we'll just fall through to the return below
}
return rv.ToArray();
}
/// <summary>
/// Retrieve an array of new objects of type T, whose properties and fields are
/// populated from an instance of the specified WMI class on the specified CIM
/// session.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be created. Must be a default-constructable
/// reference type.
/// </typeparam>
/// <param name="session">
/// The CIM session to be queried.
/// </param>
/// <param name="wmiClassName">
/// A string containing the name of the WMI class from which to populate
/// the resultant array elements.
/// </param>
/// <returns>
/// An array of new objects of type T if successful, null otherwise.
/// </returns>
/// <remarks>
/// This method matches property and field names of type T with identically
/// named properties in the WMI class instance. The WMI property is converted
/// to the type of T's property or field.
/// </remarks>
internal static T[] GetAll<T>(CimSession session, string wmiClassName) where T : class, new()
{
return GetAll<T>(session, DefaultNamespace, wmiClassName);
}
internal static void SetObjectDataMember(object obj, BindingFlags binding, CimProperty cimProperty)
{
var type = obj.GetType();
var pi = type.GetProperty(cimProperty.Name, binding);
if (pi != null && pi.CanWrite)
{
pi.SetValue(obj, cimProperty.Value, null);
}
else
{
var fi = type.GetField(cimProperty.Name, binding);
if (fi != null && !fi.IsInitOnly)
{
fi.SetValue(obj, cimProperty.Value);
}
}
}
internal static void SetObjectDataMembers(object obj, BindingFlags binding, CimInstance instance)
{
foreach (var wmiProp in instance.CimInstanceProperties)
SetObjectDataMember(obj, binding, wmiProp);
}
/// <summary>
/// Escape any backslash (\) characters in a path with an additional
/// backslash, allowing the path to be used within a WMI query.
/// </summary>
/// <param name="path">
/// A string that may contain backslash characters.
/// </param>
/// <returns>
/// A new string in which any backshlash characters have been "escaped"
/// by prefacing then with an additional backslash
/// </returns>
internal static string EscapePath(string path)
{
return string.Join(@"\\", path.Split('\\'));
}
}
}
namespace Extensions
{
using Microsoft.PowerShell.Commands;
internal static class CIMExtensions
{
/// <summary>
/// An "overload" of the
/// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
/// method that takes only the query string as a parameter
/// </summary>
/// <param name="session">The CimSession to be queried</param>
/// <param name="query">A string containing the query to be run</param>
/// <returns>
/// An IEnumerable interface that can be used to enumerate the instances
/// </returns>
internal static IEnumerable<CimInstance> QueryInstances(this CimSession session, string query)
{
return session.QueryInstances(CIMHelper.DefaultNamespace, CIMHelper.DefaultQueryDialect, query);
}
/// <summary>
/// An "overload" of the
/// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
/// method that takes only the namespace and query string as a parameters
/// </summary>
/// <param name="session">The CimSession to be queried</param>
/// <param name="nameSpace">A string containing the namespace to run the query against</param>
/// <param name="query">A string containing the query to be run</param>
/// <returns>
/// An IEnumerable interface that can be used to enumerate the instances
/// </returns>
internal static IEnumerable<CimInstance> QueryInstances(this CimSession session, string nameSpace, string query)
{
return session.QueryInstances(nameSpace, CIMHelper.DefaultQueryDialect, query);
}
/// <summary>
/// Execute a CIM query and return only the first intance in the result.
/// </summary>
/// <param name="session">The CimSesson to be queried</param>
/// <param name="nameSpace">A string containing the namespace to run the query against</param>
/// <param name="query">A string containing the query to be run</param>
/// <returns>
/// A <see cref="Microsoft.Management.Infrastructure.CimInstance"/> object
/// representing the first instance in a query result if successful, null
/// otherwise.
/// </returns>
internal static CimInstance QueryFirstInstance(this CimSession session, string nameSpace, string query)
{
try
{
var instances = session.QueryInstances(nameSpace, query);
var enumerator = instances.GetEnumerator();
if (enumerator.MoveNext())
return enumerator.Current;
}
catch (Exception /*ex*/)
{
// on any error, fall through to the null return below
}
return null;
}
/// <summary>
/// Execute a CIM query and return only the first intance in the result.
/// </summary>
/// <param name="session">The CimSesson to be queried</param>
/// <param name="query">A string containing the query to be run</param>
/// <returns>
/// A <see cref="Microsoft.Management.Infrastructure.CimInstance"/> object
/// representing the first instance in a query result if successful, null
/// otherwise.
/// </returns>
internal static CimInstance QueryFirstInstance(this CimSession session, string query)
{
return session.QueryFirstInstance(CIMHelper.DefaultNamespace, query);
}
internal static T GetFirst<T>(this CimSession session, string wmiClassName) where T : class, new()
{
return session.GetFirst<T>(CIMHelper.DefaultNamespace, wmiClassName);
}
internal static T GetFirst<T>(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
{
return CIMHelper.GetFirst<T>(session, wmiNamespace, wmiClassName);
}
internal static T[] GetAll<T>(this CimSession session, string wmiClassName) where T : class, new()
{
return Microsoft.PowerShell.Commands.CIMHelper.GetAll<T>(session, wmiClassName);
}
internal static T[] GetAll<T>(this CimSession session, string wmiNamespace, string wmiClassName) where T : class, new()
{
return Microsoft.PowerShell.Commands.CIMHelper.GetAll<T>(session, wmiNamespace, wmiClassName);
}
}
}
@@ -1364,7 +1364,12 @@ namespace Microsoft.PowerShell.Commands
/// </summary> /// </summary>
[Parameter(ParameterSetName = "FromSource")] [Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")] [Parameter(ParameterSetName = "FromMember")]
[Alias("Provider")] [Alias("Provider")]
// Disabling OACR warning 26506 and 26505, which complains that there could be null pointer.
// Since we are using [ValidateNotNullOrEmpty], PowerShell will throw an error if CodeDomProvider is null or empty.
[SuppressMessage("Microsoft.Usage", "#pw26506")]
[SuppressMessage("Microsoft.Usage", "#pw26505")]
[ValidateNotNullOrEmpty]
public CodeDomProvider CodeDomProvider public CodeDomProvider CodeDomProvider
{ {
get get
@@ -1930,9 +1930,9 @@ namespace Microsoft.PowerShell.Commands
private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath) private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath)
{ {
//if recurse is true, remove every cert in the store //if recurse is true, remove every cert in the store
string localName = Security.NativeMethods.CryptFindLocalizedName(storeName); IntPtr localName = Security.NativeMethods.CryptFindLocalizedName(storeName);
string[] pathElements = GetPathElements(sourcePath); string[] pathElements = GetPathElements(sourcePath);
if (null == localName)//not find, we can remove if (IntPtr.Zero == localName)//not find, we can remove
{ {
X509NativeStore store = null; X509NativeStore store = null;
@@ -8,7 +8,7 @@ PowerShellVersion="3.0"
CLRVersion="4.0" CLRVersion="4.0"
NestedModules="Microsoft.PowerShell.Commands.Management.dll" NestedModules="Microsoft.PowerShell.Commands.Management.dll"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390785' HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390785'
AliasesToExport = @("gcb", "scb") AliasesToExport = @("gcb", "scb","gin")
FunctionsToExport = @() FunctionsToExport = @()
CmdletsToExport=@("Add-Content", CmdletsToExport=@("Add-Content",
"Clear-Content", "Clear-Content",
@@ -95,5 +95,6 @@ CmdletsToExport=@("Add-Content",
"Show-ControlPanelItem", "Show-ControlPanelItem",
"Clear-Recyclebin", "Clear-Recyclebin",
"Get-Clipboard", "Get-Clipboard",
"Set-Clipboard") "Set-Clipboard",
"Get-ComputerInfo")
} }
Binary file not shown.
Binary file not shown.
+75 -9
View File
@@ -2001,6 +2001,11 @@ function Find-DscResource
[ValidateNotNull()] [ValidateNotNull()]
[Version] [Version]
$MinimumVersion, $MinimumVersion,
[Parameter()]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter()] [Parameter()]
[ValidateNotNull()] [ValidateNotNull()]
@@ -2104,6 +2109,11 @@ function Find-Command
[ValidateNotNull()] [ValidateNotNull()]
[Version] [Version]
$MinimumVersion, $MinimumVersion,
[Parameter()]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter()] [Parameter()]
[ValidateNotNull()] [ValidateNotNull()]
@@ -2210,6 +2220,11 @@ function Find-RoleCapability
[Version] [Version]
$MinimumVersion, $MinimumVersion,
[Parameter()]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter()] [Parameter()]
[ValidateNotNull()] [ValidateNotNull()]
[Version] [Version]
@@ -3729,6 +3744,11 @@ function Register-PSRepository
[Uri] [Uri]
$ScriptPublishLocation, $ScriptPublishLocation,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[PSCredential]
$Credential,
[Parameter(Mandatory=$true, [Parameter(Mandatory=$true,
ParameterSetName='PSGalleryParameterSet')] ParameterSetName='PSGalleryParameterSet')]
[Switch] [Switch]
@@ -3834,6 +3854,7 @@ function Register-PSRepository
# Ping and resolve the specified location # Ping and resolve the specified location
$SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) ` $SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) `
-LocationParameterName 'SourceLocation' ` -LocationParameterName 'SourceLocation' `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet -CallerPSCmdlet $PSCmdlet
@@ -3929,6 +3950,10 @@ function Set-PSRepository
[Uri] [Uri]
$ScriptPublishLocation, $ScriptPublishLocation,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[PSCredential]
$Credential,
[Parameter()] [Parameter()]
[ValidateSet('Trusted','Untrusted')] [ValidateSet('Trusted','Untrusted')]
[string] [string]
@@ -4015,6 +4040,7 @@ function Set-PSRepository
# Ping and resolve the specified location # Ping and resolve the specified location
$SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) ` $SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) `
-LocationParameterName 'SourceLocation' ` -LocationParameterName 'SourceLocation' `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet -CallerPSCmdlet $PSCmdlet
@@ -5746,13 +5772,14 @@ function Check-PSGalleryApiAvailability
# check internet availability first # check internet availability first
$connected = $false $connected = $false
$microsoftDomain = 'www.microsoft.com'
if(Get-Command Microsoft.PowerShell.Management\Test-Connection -ErrorAction SilentlyContinue) if(Get-Command Microsoft.PowerShell.Management\Test-Connection -ErrorAction SilentlyContinue)
{ {
$connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName "www.microsoft.com" -Count 1 -Quiet $connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName $microsoftDomain -Count 1 -Quiet
} }
else else
{ {
$connected = NetTCPIP\Test-NetConnection -ComputerName "www.microsoft.com" -InformationLevel Quiet $connected = NetTCPIP\Test-NetConnection -ComputerName $microsoftDomain -InformationLevel Quiet
} }
if ( -not $connected) if ( -not $connected)
{ {
@@ -5876,6 +5903,9 @@ function Ping-Endpoint
[string] [string]
$Endpoint, $Endpoint,
[Parameter()]
$Credential,
[Parameter()] [Parameter()]
$Proxy, $Proxy,
@@ -5907,7 +5937,15 @@ function Ping-Endpoint
try try
{ {
$handler = New-Object System.Net.Http.HttpClientHandler $handler = New-Object System.Net.Http.HttpClientHandler
$handler.UseDefaultCredentials = $true
if($Credential)
{
$handler.Credentials = $Credential.GetNetworkCredential()
}
else
{
$handler.UseDefaultCredentials = $true
}
if($WebProxy) if($WebProxy)
{ {
@@ -5935,14 +5973,22 @@ function Ping-Endpoint
$iss.LanguageMode = "FullLanguage" $iss.LanguageMode = "FullLanguage"
$WebRequestcmd = @' $WebRequestcmd = @'
param($WebProxy) param($Credential, $WebProxy)
try try
{{ {{
$request = [System.Net.WebRequest]::Create("{0}") $request = [System.Net.WebRequest]::Create("{0}")
$request.Method = 'GET' $request.Method = 'GET'
$request.Timeout = 30000 $request.Timeout = 30000
$request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials if($Credential)
{{
$request.Credentials = $Credential.GetNetworkCredential()
}}
else
{{
$request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}}
$request.AllowAutoRedirect = ${1} $request.AllowAutoRedirect = ${1}
if($WebProxy) if($WebProxy)
@@ -5971,7 +6017,12 @@ function Ping-Endpoint
if($WebProxy) if($WebProxy)
{ {
$ps.AddParameter($WebProxy) $null = $ps.AddParameter('WebProxy', $WebProxy)
}
if($Credential)
{
$null = $ps.AddParameter('Credential', $Credential)
} }
$response = $ps.Invoke() $response = $ps.Invoke()
@@ -8373,6 +8424,8 @@ function Add-PackageSource
{ {
return return
} }
$Credential = $request.Credential
$IsNewModuleSource = $false $IsNewModuleSource = $false
$Options = $request.Options $Options = $request.Options
@@ -8615,6 +8668,7 @@ function Add-PackageSource
# Ping and resolve the specified location # Ping and resolve the specified location
$Location = Resolve-Location -Location $Location ` $Location = Resolve-Location -Location $Location `
-LocationParameterName 'Location' ` -LocationParameterName 'Location' `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet -CallerPSCmdlet $PSCmdlet
@@ -8663,7 +8717,7 @@ function Add-PackageSource
-ExceptionObject $Name -ExceptionObject $Name
} }
$LocationString = Get-ValidModuleLocation -LocationString $Location -ParameterName "Location" -Proxy $Proxy -ProxyCredential $ProxyCredential $LocationString = Get-ValidModuleLocation -LocationString $Location -ParameterName "Location" -Proxy $Proxy -ProxyCredential $ProxyCredential -Credential $Credential
# Check if Location is already registered with another Name # Check if Location is already registered with another Name
$existingSourceName = Get-SourceName -Location $LocationString $existingSourceName = Get-SourceName -Location $LocationString
@@ -8866,7 +8920,7 @@ function Add-PackageSource
if(-not $ScriptSourceLocation) if(-not $ScriptSourceLocation)
{ {
$ScriptSourceLocation = Get-ScriptSourceLocation -Location $LocationString -Proxy $Proxy -ProxyCredential $ProxyCredential $ScriptSourceLocation = Get-ScriptSourceLocation -Location $LocationString -Proxy $Proxy -ProxyCredential $ProxyCredential -Credential $Credential
} }
elseif($Options.ContainsKey($script:ScriptSourceLocation)) elseif($Options.ContainsKey($script:ScriptSourceLocation))
{ {
@@ -11726,6 +11780,9 @@ function Get-ValidModuleLocation
[string] [string]
$ParameterName, $ParameterName,
[Parameter()]
$Credential,
[Parameter()] [Parameter()]
$Proxy, $Proxy,
@@ -11764,6 +11821,7 @@ function Get-ValidModuleLocation
# Ping and resolve the specified location # Ping and resolve the specified location
$tempLocation = Resolve-Location -Location $tempLocation ` $tempLocation = Resolve-Location -Location $tempLocation `
-LocationParameterName $ParameterName ` -LocationParameterName $ParameterName `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-ErrorAction SilentlyContinue ` -ErrorAction SilentlyContinue `
@@ -11779,6 +11837,7 @@ function Get-ValidModuleLocation
# Ping and resolve the specified location # Ping and resolve the specified location
$LocationString = Resolve-Location -Location $LocationString ` $LocationString = Resolve-Location -Location $LocationString `
-LocationParameterName $ParameterName ` -LocationParameterName $ParameterName `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-CallerPSCmdlet $PSCmdlet -CallerPSCmdlet $PSCmdlet
@@ -13306,6 +13365,9 @@ function Get-ScriptSourceLocation
[String] [String]
$Location, $Location,
[Parameter()]
$Credential,
[Parameter()] [Parameter()]
$Proxy, $Proxy,
@@ -13340,6 +13402,7 @@ function Get-ScriptSourceLocation
# Ping and resolve the specified location # Ping and resolve the specified location
$scriptLocation = Resolve-Location -Location $tempScriptLocation ` $scriptLocation = Resolve-Location -Location $tempScriptLocation `
-LocationParameterName 'ScriptSourceLocation' ` -LocationParameterName 'ScriptSourceLocation' `
-Credential $Credential `
-Proxy $Proxy ` -Proxy $Proxy `
-ProxyCredential $ProxyCredential ` -ProxyCredential $ProxyCredential `
-ErrorAction SilentlyContinue ` -ErrorAction SilentlyContinue `
@@ -13407,6 +13470,9 @@ function Resolve-Location
[string] [string]
$LocationParameterName, $LocationParameterName,
[Parameter()]
$Credential,
[Parameter()] [Parameter()]
$Proxy, $Proxy,
@@ -13438,7 +13504,7 @@ function Resolve-Location
} }
else else
{ {
$pingResult = Ping-Endpoint -Endpoint $Location -Proxy $Proxy -ProxyCredential $ProxyCredential $pingResult = Ping-Endpoint -Endpoint $Location -Credential $Credential -Proxy $Proxy -ProxyCredential $ProxyCredential
$statusCode = $null $statusCode = $null
$exception = $null $exception = $null
$resolvedLocation = $null $resolvedLocation = $null
@@ -1753,41 +1753,6 @@ namespace System.Management.Automation.Tracing
#endif #endif
namespace Microsoft.PowerShell.Commands
{
using System.Management.Automation;
/// <summary>
///
/// </summary>
public sealed class GetPSSnapinCommand : PSCmdlet
{
/// <summary>
/// Name(s) of PSSnapIn(s).
/// </summary>
[Parameter(Position = 0, Mandatory = false)]
public string[] Name
{
get
{
return _pssnapins;
}
set
{
_pssnapins = value;
}
}
private string[] _pssnapins;
/// <summary>
///
/// </summary>
protected override void EndProcessing()
{
}
}
}
namespace Microsoft.PowerShell namespace Microsoft.PowerShell
{ {
internal static class NativeCultureResolver internal static class NativeCultureResolver
@@ -6132,6 +6132,7 @@ if($paths) {
{"New-PSSession", new SessionStateCmdletEntry("New-PSSession", typeof(NewPSSessionCommand), helpFile) }, {"New-PSSession", new SessionStateCmdletEntry("New-PSSession", typeof(NewPSSessionCommand), helpFile) },
{"New-PSSessionConfigurationFile", new SessionStateCmdletEntry("New-PSSessionConfigurationFile", typeof(NewPSSessionConfigurationFileCommand), helpFile) }, {"New-PSSessionConfigurationFile", new SessionStateCmdletEntry("New-PSSessionConfigurationFile", typeof(NewPSSessionConfigurationFileCommand), helpFile) },
{"New-PSSessionOption", new SessionStateCmdletEntry("New-PSSessionOption", typeof(NewPSSessionOptionCommand), helpFile) }, {"New-PSSessionOption", new SessionStateCmdletEntry("New-PSSessionOption", typeof(NewPSSessionOptionCommand), helpFile) },
{"New-PSTransportOption", new SessionStateCmdletEntry("New-PSTransportOption", typeof(NewPSTransportOptionCommand), helpFile) },
{"Out-Default", new SessionStateCmdletEntry("Out-Default", typeof(OutDefaultCommand), helpFile) }, {"Out-Default", new SessionStateCmdletEntry("Out-Default", typeof(OutDefaultCommand), helpFile) },
{"Out-Host", new SessionStateCmdletEntry("Out-Host", typeof(OutHostCommand), helpFile) }, {"Out-Host", new SessionStateCmdletEntry("Out-Host", typeof(OutHostCommand), helpFile) },
{"Out-Null", new SessionStateCmdletEntry("Out-Null", typeof(OutNullCommand), helpFile) }, {"Out-Null", new SessionStateCmdletEntry("Out-Null", typeof(OutNullCommand), helpFile) },
@@ -6160,7 +6161,6 @@ if($paths) {
{"Enable-PSRemoting", new SessionStateCmdletEntry("Enable-PSRemoting", typeof(EnablePSRemotingCommand), helpFile) }, {"Enable-PSRemoting", new SessionStateCmdletEntry("Enable-PSRemoting", typeof(EnablePSRemotingCommand), helpFile) },
{"Export-Console", new SessionStateCmdletEntry("Export-Console", typeof(ExportConsoleCommand), helpFile) }, {"Export-Console", new SessionStateCmdletEntry("Export-Console", typeof(ExportConsoleCommand), helpFile) },
{"Get-PSSnapin", new SessionStateCmdletEntry("Get-PSSnapin", typeof(GetPSSnapinCommand), helpFile) }, {"Get-PSSnapin", new SessionStateCmdletEntry("Get-PSSnapin", typeof(GetPSSnapinCommand), helpFile) },
{"New-PSTransportOption", new SessionStateCmdletEntry("New-PSTransportOption", typeof(NewPSTransportOptionCommand), helpFile) },
{"Remove-PSSnapin", new SessionStateCmdletEntry("Remove-PSSnapin", typeof(RemovePSSnapinCommand), helpFile) }, {"Remove-PSSnapin", new SessionStateCmdletEntry("Remove-PSSnapin", typeof(RemovePSSnapinCommand), helpFile) },
{"Resume-Job", new SessionStateCmdletEntry("Resume-Job", typeof(ResumeJobCommand), helpFile) }, {"Resume-Job", new SessionStateCmdletEntry("Resume-Job", typeof(ResumeJobCommand), helpFile) },
{"Suspend-Job", new SessionStateCmdletEntry("Suspend-Job", typeof(SuspendJobCommand), helpFile) }, {"Suspend-Job", new SessionStateCmdletEntry("Suspend-Job", typeof(SuspendJobCommand), helpFile) },
@@ -482,7 +482,6 @@ namespace System.Management.Automation
} }
#if !CORECLR #if !CORECLR
// .NET Core does not have a full DataTable type
static IEnumerable DataTableEnumerable(object obj) static IEnumerable DataTableEnumerable(object obj)
{ {
return (((DataTable)obj).Rows); return (((DataTable)obj).Rows);
@@ -526,7 +525,6 @@ namespace System.Management.Automation
static GetEnumerableDelegate CalculateGetEnumerable(Type objectType) static GetEnumerableDelegate CalculateGetEnumerable(Type objectType)
{ {
#if !CORECLR #if !CORECLR
// .NET Core does not have a full DataTable type
if (typeof(DataTable).IsAssignableFrom(objectType)) if (typeof(DataTable).IsAssignableFrom(objectType))
{ {
return LanguagePrimitives.DataTableEnumerable; return LanguagePrimitives.DataTableEnumerable;
@@ -672,44 +672,19 @@ namespace Microsoft.PowerShell.Commands
// Check if module could be a snapin. This was the case for PowerShell version 2 engine modules. // Check if module could be a snapin. This was the case for PowerShell version 2 engine modules.
if (InitialSessionState.IsEngineModule(name)) if (InitialSessionState.IsEngineModule(name))
{ {
CmdletInfo cmdletInfo = Context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-PSSnapIn"); PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name);
if (cmdletInfo != null && cmdletInfo.Visibility == SessionStateEntryVisibility.Public)
// Return the command if we found a module
if (snapin != null)
{ {
CommandInfo commandInfo = new CmdletInfo("Get-PSSnapIn", // warn that this module already exists as a snapin
typeof(Microsoft.PowerShell.Commands.GetPSSnapinCommand), string warningMessage = string.Format(
null, null, Context); CultureInfo.InvariantCulture,
Command getPSSnapInCommand = new Command(commandInfo); Modules.ModuleLoadedAsASnapin,
snapin.Name);
Collection<PSSnapInInfo> matchingSnapins = null; WriteWarning(warningMessage);
found = true;
try return foundModule;
{
using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddCommand(getPSSnapInCommand)
.AddParameter("Name", name)
.AddParameter("ErrorAction", ActionPreference.Ignore);
matchingSnapins = powerShell.Invoke<PSSnapInInfo>();
}
}
catch (Exception e)
{
// Call-out to user code, catch-all OK
CommandProcessorBase.CheckForSevereException(e);
}
// Return the command if we found a module
if (matchingSnapins != null && matchingSnapins.Count == 1)
{
// warn that this module already exists as a snapin
string warningMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.ModuleLoadedAsASnapin,
matchingSnapins[0].Name);
WriteWarning(warningMessage);
found = true;
return foundModule;
}
} }
} }
@@ -4089,27 +4089,10 @@ namespace Microsoft.PowerShell.Commands
// If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using RunspaceConfiguration or InitialSessionState.CreateDefault()) // If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using RunspaceConfiguration or InitialSessionState.CreateDefault())
if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name)) if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name))
{ {
using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) result = ModuleCmdletBase.GetEngineSnapIn(context, requiredModule.Name);
if (result != null)
{ {
Collection<PSSnapInInfo> loadedSnapins = null; loaded = true;
powerShell.AddCommand("Get-PSSnapin");
powerShell.AddParameter("Name", requiredModule.Name);
try
{
loadedSnapins = powerShell.Invoke<PSSnapInInfo>();
}
catch (Exception e)
{
// Catch-all OK, third-party call-out.
CommandProcessorBase.CheckForSevereException(e);
}
if (loadedSnapins != null && loadedSnapins.Count > 0)
{
Dbg.Assert(loadedSnapins.Count == 1, " There should only be one snapin by name " + requiredModule.Name);
result = loadedSnapins[0];
loaded = true;
}
} }
} }
@@ -7814,6 +7797,30 @@ namespace Microsoft.PowerShell.Commands
return; return;
} }
} }
/// <summary>
/// Search a PSSnapin with the specified name
/// </summary>
internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string name)
{
HashSet<PSSnapInInfo> snapinSet = new HashSet<PSSnapInInfo>();
List<CmdletInfo> cmdlets = context.SessionState.InvokeCommand.GetCmdlets();
foreach (CmdletInfo cmdlet in cmdlets)
{
PSSnapInInfo snapin = cmdlet.PSSnapIn;
if (snapin != null && !snapinSet.Contains(snapin))
snapinSet.Add(snapin);
}
foreach (PSSnapInInfo snapin in snapinSet)
{
if (string.Equals(snapin.Name, name, StringComparison.OrdinalIgnoreCase))
return snapin;
}
return null;
}
} // end ModuleCmdletBase } // end ModuleCmdletBase
/// <summary> /// <summary>
@@ -5008,12 +5008,13 @@ namespace System.Management.Automation
null); null);
string providerPath = null; string providerPath = null;
bool pathNotFoundOnClient = false;
try try
{ {
Collection<string> providerPaths = Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath( Globber.GetGlobbedProviderPathsFromMonadPath(
path, path,
!RemoteCopyOperation(context), true,
newContext, newContext,
out provider, out provider,
out providerInstance); out providerInstance);
@@ -5021,13 +5022,26 @@ namespace System.Management.Automation
if (providerPaths.Count > 0) if (providerPaths.Count > 0)
providerPath = providerPaths[0]; providerPath = providerPaths[0];
} }
catch (DriveNotFoundException) catch (DriveNotFoundException)
{ {
// This exception is expected for remote sessions where drives exist in a remote session but not // This exception is expected for remote sessions where drives exist in a remote session but not
// on the client. But we don't know if this is a remote use of copy-item because the FromSession // on the client.
pathNotFoundOnClient = true;
}
catch (ItemNotFoundException)
{
// This exception is expected for remote sessions where item exist in a remote session but not
// on the client.
pathNotFoundOnClient = true;
}
if (pathNotFoundOnClient)
{
// At this point, we don't know if this is a remote use of copy-item because the FromSession
// and ToSession dynamic parameters have not been retrieved yet. // and ToSession dynamic parameters have not been retrieved yet.
// Ignore the exception and use the FileSystem provider as default. If this is a real drive issue // Ignore these exceptions and use the FileSystem provider as default. If this is a real drive
// it will be caught later when the drive path is used. // issue, or if the item does not exist, it will be caught later when the drive or item path is used.
var fileSystemProviders = Providers["FileSystem"]; var fileSystemProviders = Providers["FileSystem"];
if (fileSystemProviders.Count > 0) if (fileSystemProviders.Count > 0)
{ {
@@ -5283,17 +5297,6 @@ namespace System.Management.Automation
return true; return true;
} }
private bool RemoteCopyOperation(CmdletProviderContext context)
{
Microsoft.PowerShell.Commands.CopyItemDynamicParameters dynamicParams = context.DynamicParameters as Microsoft.PowerShell.Commands.CopyItemDynamicParameters;
if (dynamicParams != null)
{
return ((dynamicParams.FromSession != null) || (dynamicParams.ToSession != null));
}
return false;
}
#endregion CopyItem #endregion CopyItem
#endregion ContainerCmdletProvider accessors #endregion ContainerCmdletProvider accessors
@@ -53,7 +53,7 @@ namespace System.Management.Automation.Runspaces
[Microsoft.PowerShell.Commands.FileSystemProvider]) [Microsoft.PowerShell.Commands.FileSystemProvider])
{ {
$driveRoot = ([System.IO.DirectoryInfo] $this.Root).Name.Replace('\','') $driveRoot = ([System.IO.DirectoryInfo] $this.Root).Name.Replace('\','')
$drive = Get-WmiObject Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'"" $drive = Get-CimInstance Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
$drive.Size - $drive.FreeSpace $drive.Size - $drive.FreeSpace
}"), null)); }"), null));
td4.Members.Add("Free", td4.Members.Add("Free",
@@ -62,7 +62,7 @@ namespace System.Management.Automation.Runspaces
[Microsoft.PowerShell.Commands.FileSystemProvider]) [Microsoft.PowerShell.Commands.FileSystemProvider])
{ {
$driveRoot = ([System.IO.DirectoryInfo] $this.Root).Root.Name.Replace('\','') $driveRoot = ([System.IO.DirectoryInfo] $this.Root).Root.Name.Replace('\','')
$drive = Get-WmiObject Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'"" $drive = Get-CimInstance Win32_LogicalDisk -Filter ""DeviceId='$driveRoot'""
$drive.FreeSpace $drive.FreeSpace
}"), null)); }"), null));
yield return td4; yield return td4;
@@ -746,6 +746,8 @@ namespace System.Management.Automation.Runspaces
throw initError; throw initError;
} }
} }
TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData);
} }
/// <summary> /// <summary>
@@ -14,6 +14,7 @@ using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Host; using System.Management.Automation.Host;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Management.Automation.Remoting.Client; using System.Management.Automation.Remoting.Client;
using Microsoft.PowerShell.Telemetry.Internal;
namespace System.Management.Automation.Runspaces.Internal namespace System.Management.Automation.Runspaces.Internal
{ {
@@ -884,6 +885,8 @@ namespace System.Management.Automation.Runspaces.Internal
PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open, PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational); PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational);
TelemetryAPI.ReportRemoteSessionCreated(connectionInfo);
lock (syncObject) lock (syncObject)
{ {
AssertIfStateIsBeforeOpen(); AssertIfStateIsBeforeOpen();
@@ -248,7 +248,7 @@ function Register-PSSessionConfiguration
if ($?){{ if ($?){{
try{{ try{{
$s = New-PSSession -ComputerName localhost -ConfigurationName $pluginName -ErrorAction Stop $s = New-PSSession -ComputerName localhost -ConfigurationName $pluginName -ErrorAction Stop
# session is ok, no need to restart WinRM service # session is ok, no need to restart WinRM service
Remove-PSSession $s -Confirm:$false Remove-PSSession $s -Confirm:$false
}}catch{{ }}catch{{
# session is NOT ok, we need to restart winrm if -Force was specified, otherwise show a warning # session is NOT ok, we need to restart winrm if -Force was specified, otherwise show a warning
@@ -577,6 +577,15 @@ else
ArrayList errorList = (ArrayList)Context.DollarErrorVariable; ArrayList errorList = (ArrayList)Context.DollarErrorVariable;
int errorCountBefore = errorList.Count; int errorCountBefore = errorList.Count;
if (force &&
this.Context != null &&
this.Context.EngineHostInterface != null &&
this.Context.EngineHostInterface.ExternalHost != null &&
this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost)
{
WriteWarning(RemotingErrorIdStrings.WinRMForceRestartWarning);
}
newPluginSb.InvokeUsingCmdlet( newPluginSb.InvokeUsingCmdlet(
contextCmdlet: this, contextCmdlet: this,
useLocalScope: true, useLocalScope: true,
@@ -402,10 +402,8 @@ namespace Microsoft.PowerShell.Commands
/// <summary> /// <summary>
/// Command to create an object for WSManConfigurationOption /// Command to create an object for WSManConfigurationOption
/// </summary> /// </summary>
#if !CORECLR
[Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)] [Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(WSManConfigurationOption))] [OutputType(typeof(WSManConfigurationOption))]
#endif
public sealed class NewPSTransportOptionCommand : PSCmdlet public sealed class NewPSTransportOptionCommand : PSCmdlet
{ {
private WSManConfigurationOption option = new WSManConfigurationOption(); private WSManConfigurationOption option = new WSManConfigurationOption();
@@ -96,9 +96,11 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)] ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true, [Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)] ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true, [Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)] ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true, [Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)] ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[Credential()] [Credential()]
public override PSCredential Credential public override PSCredential Credential
@@ -156,7 +158,9 @@ namespace Microsoft.PowerShell.Commands
/// i.e., allows going off box. When this property is true and a PSSession is disconnected, /// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box. /// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
/// </summary> /// </summary>
[Parameter()] [Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.SessionParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)]
public SwitchParameter EnableNetworkAccess public SwitchParameter EnableNetworkAccess
{ {
get { return enableNetworkAccess; } get { return enableNetworkAccess; }
@@ -278,6 +278,18 @@ namespace System.Management.Automation.Remoting
_streamReader = new StreamReader(_networkStream); _streamReader = new StreamReader(_networkStream);
_streamWriter = new StreamWriter(_networkStream); _streamWriter = new StreamWriter(_networkStream);
_streamWriter.AutoFlush = true; _streamWriter.AutoFlush = true;
//
// listenSocket is not closed when it goes out of scope here. Sometimes it is
// closed later in this thread, while other times it is not closed at all. This will
// cause problem when we set up a second PowerShell Direct session. Let's
// explicitly close listenSocket here for safe.
//
if (listenSocket != null)
{
try { listenSocket.Dispose(); }
catch (ObjectDisposedException) { }
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -533,6 +545,15 @@ namespace System.Management.Automation.Remoting
bool isFirstConnection) bool isFirstConnection)
{ {
bool result = false; bool result = false;
//
// Check invalid input and throw exception before setting up socket connection.
//
if (String.IsNullOrEmpty(networkCredential.UserName))
{
throw new PSDirectException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername));
}
_socket.Connect(_endPoint); _socket.Connect(_endPoint);
@@ -550,16 +571,6 @@ namespace System.Management.Automation.Remoting
networkCredential.Domain = "localhost"; networkCredential.Domain = "localhost";
} }
if (String.IsNullOrEmpty(networkCredential.UserName))
{
throw new PSInvalidOperationException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername),
null,
PSRemotingErrorId.InvalidUsername.ToString(),
ErrorCategory.InvalidOperation,
null);
}
bool emptyPassword = String.IsNullOrEmpty(networkCredential.Password); bool emptyPassword = String.IsNullOrEmpty(networkCredential.Password);
bool emptyConfiguration = String.IsNullOrEmpty(configurationName); bool emptyConfiguration = String.IsNullOrEmpty(configurationName);
@@ -1217,25 +1217,20 @@ namespace System.Management.Automation.Remoting
#region Constructors #region Constructors
/// <summary> /// <summary>
/// Constructor. Creates Named Pipe based on process Id, app domain name and container id. /// Constructor. Creates Named Pipe based on process Id, app domain name and container Guid.
/// </summary> /// </summary>
/// <param name="procId">Target process Id for pipe.</param> /// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain</param> /// <param name="appDomainName">AppDomain name or null for default AppDomain</param>
/// <param name="containerId">Container Id.</param> /// <param name="containerGuid">Container Guid.</param>
public ContainerSessionNamedPipeClient( public ContainerSessionNamedPipeClient(
int procId, int procId,
string appDomainName, string appDomainName,
string containerId) Guid containerGuid)
{ {
if (String.IsNullOrEmpty(containerId))
{
throw new PSArgumentNullException("containerId");
}
// //
// Named pipe inside Windows Server container is under different name space. // Named pipe inside Windows Server container is under different name space.
// //
_pipeName = @"\\.\Containers\" + containerId + @"\Device\NamedPipe\" + _pipeName = @"\\.\Containers\" + containerGuid.ToString() + @"\Device\NamedPipe\" +
NamedPipeUtils.CreateProcessPipeName(procId, appDomainName); NamedPipeUtils.CreateProcessPipeName(procId, appDomainName);
} }
@@ -2240,7 +2240,7 @@ namespace System.Management.Automation.Runspaces
bool runAsAdmin, bool runAsAdmin,
string configurationName) string configurationName)
{ {
ContainerProcess containerProc = new ContainerProcess(containerId, null, 0, runAsAdmin, configurationName); ContainerProcess containerProc = new ContainerProcess(containerId, null, Guid.Empty, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc); return new ContainerConnectionInfo(containerProc);
} }
@@ -2253,7 +2253,7 @@ namespace System.Management.Automation.Runspaces
bool runAsAdmin, bool runAsAdmin,
string configurationName) string configurationName)
{ {
ContainerProcess containerProc = new ContainerProcess(null, containerName, 0, runAsAdmin, configurationName); ContainerProcess containerProc = new ContainerProcess(null, containerName, Guid.Empty, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc); return new ContainerConnectionInfo(containerProc);
} }
@@ -2288,8 +2288,9 @@ namespace System.Management.Automation.Runspaces
#region Private Data #region Private Data
private Guid runtimeId; private Guid runtimeId;
private Guid containerGuid = Guid.Empty;
private string containerId; private string containerId;
private string containerName; private string containerName;
private int processId; private int processId;
private bool runAsAdmin = false; private bool runAsAdmin = false;
private string configurationName; private string configurationName;
@@ -2318,6 +2319,15 @@ namespace System.Management.Automation.Runspaces
set { runtimeId = value; } set { runtimeId = value; }
} }
/// <summary>
/// Guid of the container.
/// </summary>
public Guid ContainerGuid
{
get { return containerGuid; }
set { containerGuid = value; }
}
/// <summary> /// <summary>
/// ID of the container. /// ID of the container.
/// </summary> /// </summary>
@@ -2413,10 +2423,11 @@ namespace System.Management.Automation.Runspaces
/// <summary> /// <summary>
/// Creates an instance used for PowerShell Direct for container. /// Creates an instance used for PowerShell Direct for container.
/// </summary> /// </summary>
public ContainerProcess(string containerId, string containerName, int processId, bool runAsAdmin, string configurationName) public ContainerProcess(string containerId, string containerName, Guid containerGuid, int processId, bool runAsAdmin, string configurationName)
{ {
this.ContainerId = containerId; this.ContainerId = containerId;
this.ContainerName = containerName; this.ContainerName = containerName;
this.ContainerGuid = containerGuid;
this.ProcessId = processId; this.ProcessId = processId;
this.RunAsAdmin = runAsAdmin; this.RunAsAdmin = runAsAdmin;
this.ConfigurationName = configurationName; this.ConfigurationName = configurationName;
@@ -2425,12 +2436,12 @@ namespace System.Management.Automation.Runspaces
{ {
if (String.IsNullOrEmpty(containerName)) if (String.IsNullOrEmpty(containerName))
{ {
GetContainerNameFromContainerId(); GetContainerPropertiesFromContainerId();
} }
} }
else if (!String.IsNullOrEmpty(containerName)) else if (!String.IsNullOrEmpty(containerName))
{ {
GetContainerIdFromContainerName(); GetContainerPropertiesFromContainerName();
} }
else else
{ {
@@ -2486,11 +2497,11 @@ namespace System.Management.Automation.Runspaces
} }
/// <summary> /// <summary>
/// Get container name based on given container id. /// Get container name and Guid based on given container id.
/// </summary> /// </summary>
public void GetContainerNameFromContainerId() public void GetContainerPropertiesFromContainerId()
{ {
RunOnMTAThread(GetContainerNameFromContainerIdInternal); RunOnMTAThread(GetContainerPropertiesFromContainerIdInternal);
// //
// Report error. // Report error.
@@ -2509,11 +2520,11 @@ namespace System.Management.Automation.Runspaces
} }
/// <summary> /// <summary>
/// Get container id based on given container name. /// Get container id and Guid based on given container name.
/// </summary> /// </summary>
public void GetContainerIdFromContainerName() public void GetContainerPropertiesFromContainerName()
{ {
RunOnMTAThread(GetContainerIdFromContainerNameInternal); RunOnMTAThread(GetContainerPropertiesFromContainerNameInternal);
// //
// Report error. // Report error.
@@ -2611,7 +2622,9 @@ namespace System.Management.Automation.Runspaces
} }
} }
catch (Exception e) catch (Exception e)
{ {
CommandProcessorBase.CheckForSevereException(e);
if (e is FileNotFoundException || e is FileLoadException) if (e is FileNotFoundException || e is FileLoadException)
{ {
// //
@@ -2646,9 +2659,9 @@ namespace System.Management.Automation.Runspaces
} }
/// <summary> /// <summary>
/// Get container name based on given container id. /// Get container name and Guid based on given container id.
/// </summary> /// </summary>
private void GetContainerNameFromContainerIdInternal() private void GetContainerPropertiesFromContainerIdInternal()
{ {
try try
{ {
@@ -2661,8 +2674,16 @@ namespace System.Management.Automation.Runspaces
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ContainerId }); var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ContainerId });
ContainerName = (string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle); ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle); RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container Guid for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerGuid = new Guid((string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle));
}
} }
catch (FileNotFoundException) catch (FileNotFoundException)
{ {
@@ -2674,6 +2695,8 @@ namespace System.Management.Automation.Runspaces
} }
catch (Exception e) catch (Exception e)
{ {
CommandProcessorBase.CheckForSevereException(e);
if (e.InnerException != null && if (e.InnerException != null &&
StringComparer.Ordinal.Equals( StringComparer.Ordinal.Equals(
e.InnerException.GetType().FullName, e.InnerException.GetType().FullName,
@@ -2690,9 +2713,9 @@ namespace System.Management.Automation.Runspaces
} }
/// <summary> /// <summary>
/// Get container id based on given container name. /// Get container id and Guid based on given container name.
/// </summary> /// </summary>
private void GetContainerIdFromContainerNameInternal() private void GetContainerPropertiesFromContainerNameInternal()
{ {
try try
{ {
@@ -2734,6 +2757,14 @@ namespace System.Management.Automation.Runspaces
ContainerId = (string)computeSystemPropertiesType.GetProperty("Id").GetValue(computeSystemPropertiesHandle); ContainerId = (string)computeSystemPropertiesType.GetProperty("Id").GetValue(computeSystemPropertiesHandle);
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle); ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle); RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container Guid for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerGuid = new Guid((string)computeSystemPropertiesType.GetProperty("SiloGuid").GetValue(computeSystemPropertiesHandle));
}
} }
catch (FileNotFoundException) catch (FileNotFoundException)
{ {
@@ -2745,6 +2776,8 @@ namespace System.Management.Automation.Runspaces
} }
catch (Exception e) catch (Exception e)
{ {
CommandProcessorBase.CheckForSevereException(e);
ErrorCode = OtherError; ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e); ErrorMessage = GetErrorMessageFromException(e);
} }
@@ -1636,7 +1636,7 @@ namespace System.Management.Automation.Remoting.Client
_clientPipe = new ContainerSessionNamedPipeClient( _clientPipe = new ContainerSessionNamedPipeClient(
_connectionInfo.ContainerProc.ProcessId, _connectionInfo.ContainerProc.ProcessId,
string.Empty, // AppDomainName string.Empty, // AppDomainName
_connectionInfo.ContainerProc.ContainerId); _connectionInfo.ContainerProc.ContainerGuid);
// Wait for named pipe to connect. // Wait for named pipe to connect.
_clientPipe.Connect(_connectionInfo.OpenTimeout); _clientPipe.Connect(_connectionInfo.OpenTimeout);
@@ -556,7 +556,7 @@ namespace System.Management.Automation.Language
} }
#if !CORECLR #if !CORECLR
// .NET Core does not have a full DataTable type // In CORECLR System.Data.DataTable does not have the DataRowCollection IEnumerable, so disabling code.
if (targetValue is DataTable) if (targetValue is DataTable)
{ {
// Generate: // Generate:
@@ -566,7 +566,7 @@ namespace System.Management.Automation
// This is the path to the help file. // This is the path to the help file.
string location = null; string location = null;
if (helpFile.EndsWith(".ni.dll-Help.xml")) if (helpFile.EndsWith(".ni.dll-Help.xml", StringComparison.OrdinalIgnoreCase))
{ {
// For PowerShell on OneCore, we ship Ngen binaries. As a result, the name of the assembly now contains '.ni' on it, // For PowerShell on OneCore, we ship Ngen binaries. As a result, the name of the assembly now contains '.ni' on it,
// e.g., <AssemblyName>.ni.dll as supposed to <AssemblyName>.dll. // e.g., <AssemblyName>.ni.dll as supposed to <AssemblyName>.dll.
@@ -1896,11 +1896,8 @@ namespace Microsoft.PowerShell.Commands
} }
// Verify that the target doesn't represent a device name // Verify that the target doesn't represent a device name
if (Utils.IsReservedDeviceName(newName)) if (PathIsReservedDeviceName(newName, "RenameError"))
{ {
String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, newName);
Exception e = new IOException(error);
WriteError(new ErrorRecord(e, "RenameError", ErrorCategory.WriteError, newName));
return; return;
} }
@@ -3787,11 +3784,8 @@ namespace Microsoft.PowerShell.Commands
} }
// Verify that the target doesn't represent a device name // Verify that the target doesn't represent a device name
if (Utils.IsReservedDeviceName(destinationPath)) if (PathIsReservedDeviceName(destinationPath, "CopyError"))
{ {
String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destinationPath);
Exception e = new IOException(error);
WriteError(new ErrorRecord(e, "CopyError", ErrorCategory.WriteError, destinationPath));
return; return;
} }
} }
@@ -4110,15 +4104,20 @@ namespace Microsoft.PowerShell.Commands
{ {
Dbg.Diagnostics.Assert(sourceFileFullName != null, "The caller should verify file."); Dbg.Diagnostics.Assert(sourceFileFullName != null, "The caller should verify file.");
// If the destination directory does not exist, error out. // If the destination is a container, add the file name
if(!Utils.NativeDirectoryExists(destinationPath)) // to the destination path.
if (IsItemContainer(destinationPath))
{
destinationPath = MakePath(destinationPath, sourceFileName);
}
// Verify that the target doesn't represent a device name
if (PathIsReservedDeviceName(destinationPath, "CopyError"))
{ {
Exception e = new IOException(String.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemDirectoryNotFound, destinationPath));
WriteError(new ErrorRecord(e, "DirectoryNotFound", ErrorCategory.WriteError, destinationPath));
return; return;
} }
FileInfo destinationFile = new FileInfo(Path.Combine(destinationPath, sourceFileName)); FileInfo destinationFile = new FileInfo(destinationPath);
string action = FileSystemProviderStrings.CopyItemActionFile; string action = FileSystemProviderStrings.CopyItemActionFile;
string resource = StringUtil.Format(FileSystemProviderStrings.CopyItemResourceFileTemplate, sourceFileFullName, destinationPath); string resource = StringUtil.Format(FileSystemProviderStrings.CopyItemResourceFileTemplate, sourceFileFullName, destinationPath);
@@ -4350,6 +4349,61 @@ namespace Microsoft.PowerShell.Commands
return supportsAlternateStreams; return supportsAlternateStreams;
} }
// Validate that the given remotePath exists, and do the following:
// 1) If the remotePath is a FileInfo, then just return the remotePath.
// 2) If the remotePath is a DirectoryInfo, then return the remotePath + the given filename.
// 3) If the remote path does not exist, but its parent does, and it is a DirectoryInfo, then return the remotePath.
// 4) If the remotePath or its parent do not exist, return null.
private string MakeRemotePath(System.Management.Automation.PowerShell ps, string remotePath, string filename)
{
bool isFileInfo = false;
bool isDirectoryInfo = false;
bool parentIsDirectoryInfo = false;
string path = null;
ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
ps.AddParameter("remotePath", remotePath);
Hashtable op = SafeInvokeCommand.Invoke(ps, this, null);
if (op != null)
{
if (op["IsDirectoryInfo"] != null)
{
isDirectoryInfo = (bool) op["IsDirectoryInfo"];
}
if (op["IsFileInfo"] != null)
{
isFileInfo = (bool) op["IsFileInfo"];
}
if (op["ParentIsDirectoryInfo"] != null)
{
parentIsDirectoryInfo = (bool)op["ParentIsDirectoryInfo"];
}
}
if (isFileInfo)
{
// The destination is a file, so we are going to overwrite it.
path = remotePath;
}
else if (isDirectoryInfo)
{
// The destination is a directory, so append the file name to the path.
path = Path.Combine(remotePath, filename);
}
else if (parentIsDirectoryInfo)
{
// At this point we know that the remotePath is neither a file or a directory on the remote target.
// However, if the parent of the remotePath exists, then we are doing a copy-item operation in which
// the destination file name is already being passed, e.g.,
// copy-item -path c:\localDir\foo.txt -destination d:\remoteDir\bar.txt -toSession $s
// Note that d:\remoteDir is a directory that exists on the remote target machine.
path = remotePath;
}
return path;
}
private bool RemoteDirectoryExist(System.Management.Automation.PowerShell ps, string path) private bool RemoteDirectoryExist(System.Management.Automation.PowerShell ps, string path)
{ {
bool pathExists = false; bool pathExists = false;
@@ -4378,9 +4432,6 @@ namespace Microsoft.PowerShell.Commands
"localhost", "localhost",
ps.Runspace.ConnectionInfo.ComputerName); ps.Runspace.ConnectionInfo.ComputerName);
// The destinationPath was verified by the caller so we can create the final filePath here.
var filePath = Path.Combine(destinationPath, file.Name);
ProgressRecord progress = new ProgressRecord(0, activity, statusDescription); ProgressRecord progress = new ProgressRecord(0, activity, statusDescription);
progress.PercentComplete = 0; progress.PercentComplete = 0;
progress.RecordType = ProgressRecordType.Processing; progress.RecordType = ProgressRecordType.Processing;
@@ -4441,14 +4492,31 @@ namespace Microsoft.PowerShell.Commands
if (!isAlternateStream) if (!isAlternateStream)
{ {
ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName); ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
ps.AddParameter("copyToFilePath", filePath); ps.AddParameter("copyToFilePath", destinationPath);
ps.AddParameter("b64Fragment", b64Fragment); ps.AddParameter("createFile", (iteration == 1));
ps.AddParameter("createFile", (iteration == 1) ? true : false);
if ((iteration == 1) && (b64Fragment.Length == 0))
{
// This fixes the case in which the user tries to copy an empty file between sessions.
// Scenario 1: The user creates an empty file using the Out-File cmdlet.
// In this case the file length is 6.
// "" | out-file test.txt
// Scenario 2: The user generates an empty file using the New-Item cmdlet.
// In this case the file length is 0.
// New-Item -Path test.txt -Type File
// Because of this, when we create the file on the remote session, we need to check
// the length of b64Fragment to figure out if we are creating an empty file.
ps.AddParameter("emptyFile", true);
}
else
{
ps.AddParameter("b64Fragment", b64Fragment);
}
} }
else else
{ {
ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName); ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName);
ps.AddParameter("copyToFilePath", filePath); ps.AddParameter("copyToFilePath", destinationPath);
ps.AddParameter("b64Fragment", b64Fragment); ps.AddParameter("b64Fragment", b64Fragment);
ps.AddParameter("streamName", streamName); ps.AddParameter("streamName", streamName);
} }
@@ -4540,17 +4608,19 @@ namespace Microsoft.PowerShell.Commands
private bool PerformCopyFileToRemoteSession(FileInfo file, string destinationPath, System.Management.Automation.PowerShell ps) private bool PerformCopyFileToRemoteSession(FileInfo file, string destinationPath, System.Management.Automation.PowerShell ps)
{ {
// Validate the the destination directory exist on the remote target. // Make the remote path
if (!RemoteDirectoryExist(ps, destinationPath)) var remoteFilePath = MakeRemotePath(ps, destinationPath, file.Name);
if (String.IsNullOrEmpty(remoteFilePath))
{ {
Exception e = new IOException(String.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemDirectoryNotFound, destinationPath)); Exception e = new ArgumentException(String.Format(CultureInfo.InvariantCulture, SessionStateStrings.PathNotFound, destinationPath));
WriteError(new ErrorRecord(e, "RemoteDirectoryNotFound", ErrorCategory.WriteError, destinationPath)); WriteError(new ErrorRecord(e, "RemotePathNotFound", ErrorCategory.WriteError, destinationPath));
return false; return false;
} }
bool result = CopyFileStreamToRemoteSession(file, destinationPath, ps, false, null); bool result = CopyFileStreamToRemoteSession(file, remoteFilePath, ps, false, null);
bool targetSupportsAlternateStreams = RemoteTargetSupportsAlternateStreams(ps, Path.Combine(destinationPath, file.Name)); bool targetSupportsAlternateStreams = RemoteTargetSupportsAlternateStreams(ps, remoteFilePath);
// Once the file is copied sucessfully, check if the file has any alternate data streams // Once the file is copied sucessfully, check if the file has any alternate data streams
if (result && targetSupportsAlternateStreams) if (result && targetSupportsAlternateStreams)
@@ -4559,7 +4629,7 @@ namespace Microsoft.PowerShell.Commands
{ {
if (!(String.Equals(":$DATA", stream.Stream, StringComparison.OrdinalIgnoreCase))) if (!(String.Equals(":$DATA", stream.Stream, StringComparison.OrdinalIgnoreCase)))
{ {
result = CopyFileStreamToRemoteSession(file, destinationPath, ps, true, stream.Stream); result = CopyFileStreamToRemoteSession(file, remoteFilePath, ps, true, stream.Stream);
if (!result) if (!result)
{ {
break; break;
@@ -4635,6 +4705,21 @@ namespace Microsoft.PowerShell.Commands
return path; return path;
} // CreateDirectoryOnRemoteSession } // CreateDirectoryOnRemoteSession
// Returns true if the destination path represents a device name, and write an error to the user.
private bool PathIsReservedDeviceName(string destinationPath, string errorId)
{
bool pathIsReservedDeviceName = false;
if (Utils.IsReservedDeviceName(destinationPath))
{
pathIsReservedDeviceName = true;
String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destinationPath);
Exception e = new IOException(error);
WriteError(new ErrorRecord(e, errorId, ErrorCategory.WriteError, destinationPath));
}
return pathIsReservedDeviceName;
}
#endregion CopyItem #endregion CopyItem
#endregion ContainerCmdletProvider members #endregion ContainerCmdletProvider members
@@ -5573,15 +5658,11 @@ namespace Microsoft.PowerShell.Commands
destination = NormalizePath(destination); destination = NormalizePath(destination);
// Verify that the target doesn't represent a device name // Verify that the target doesn't represent a device name
if (Utils.IsReservedDeviceName(destination)) if (PathIsReservedDeviceName(destination, "MoveError"))
{ {
String error = StringUtil.Format(FileSystemProviderStrings.TargetCannotContainDeviceName, destination);
Exception e = new IOException(error);
WriteError(new ErrorRecord(e, "MoveError", ErrorCategory.WriteError, destination));
return; return;
} }
try try
{ {
bool isContainer = IsItemContainer(path); bool isContainer = IsItemContainer(path);
@@ -8772,7 +8853,7 @@ namespace System.Management.Automation.Internal
{0} {0}
[string] $copyToFilePath, [string] $copyToFilePath,
[Parameter(ParameterSetName=""PSCopyFileToRemoteSession"", Mandatory=$true)] [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"", Mandatory=$false)]
[Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"")] [Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string] $b64Fragment, [string] $b64Fragment,
@@ -8780,6 +8861,9 @@ namespace System.Management.Automation.Internal
[Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")] [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")]
[switch] $createFile = $false, [switch] $createFile = $false,
[Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")]
[switch] $emptyFile = $false,
[Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"", Mandatory=$true)] [Parameter(ParameterSetName=""PSCopyAlternateStreamToRemoteSession"", Mandatory=$true)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string] $streamName, [string] $streamName,
@@ -8800,6 +8884,10 @@ namespace System.Management.Automation.Internal
{0} {0}
[string] $isFilePath, [string] $isFilePath,
[Parameter(ParameterSetName=""PSGetRemotePathInfo"", Mandatory=$true)]
{0}
[string] $remotePath,
[Parameter(ParameterSetName=""PSCreateDirectoryOnRemoteSession"", Mandatory=$true)] [Parameter(ParameterSetName=""PSCreateDirectoryOnRemoteSession"", Mandatory=$true)]
{0} {0}
[string] $createDirectoryPath, [string] $createDirectoryPath,
@@ -8840,9 +8928,10 @@ namespace System.Management.Automation.Internal
param( param(
[string] $copyToFilePath, [string] $copyToFilePath,
[string] $b64Fragment, [string] $b64Fragment,
[switch] $createFile = $false [switch] $createFile = $false,
[switch] $emptyFile = $false
) )
$op = @{{ $op = @{{
BytesWritten = $null BytesWritten = $null
}} }}
@@ -8851,9 +8940,6 @@ namespace System.Management.Automation.Internal
try try
{{ {{
# Decode
$fragment = [System.Convert]::FromBase64String($b64Fragment)
$filePathExists = Microsoft.PowerShell.Management\Test-Path -Path $copyToFilePath $filePathExists = Microsoft.PowerShell.Management\Test-Path -Path $copyToFilePath
if ($createFile -or (! $filePathExists)) if ($createFile -or (! $filePathExists))
@@ -8866,11 +8952,21 @@ namespace System.Management.Automation.Internal
# Create the new file. # Create the new file.
$fileInfo = Microsoft.PowerShell.Management\New-Item -Path $copyToFilePath -Type File -Force $fileInfo = Microsoft.PowerShell.Management\New-Item -Path $copyToFilePath -Type File -Force
if ($emptyFile)
{{
# Handle the empty file scenario.
$op['BytesWritten'] = 0
return $op
}}
}} }}
# Resolve path in case it is a PSDrive # Resolve path in case it is a PSDrive
$resolvedPath = Microsoft.PowerShell.Management\Resolve-Path -literal $copyToFilePath $resolvedPath = Microsoft.PowerShell.Management\Resolve-Path -literal $copyToFilePath
# Decode
$fragment = [System.Convert]::FromBase64String($b64Fragment)
# Check if drive specifies max size and if max size is exceeded # Check if drive specifies max size and if max size is exceeded
CheckPSDriveSize $resolvedPath $fragment.Length CheckPSDriveSize $resolvedPath $fragment.Length
@@ -9012,6 +9108,53 @@ namespace System.Management.Automation.Internal
}} }}
}} }}
# Returns a hashtable with the following member:
# IsFileInfo - boolean to keep track of whether the given path is a remote file.
# IsDirectoryInfo - boolean to keep track of whether the given path is a remote directory.
# ParentIsDirectoryInfo - boolean to keep track of whether the given parent path is a remote directory.
#
function PSGetRemotePathInfo
{{
param (
[string] $remotePath
)
try
{{
try
{{
$parentPath = Microsoft.PowerShell.Management\Split-Path $remotePath
}}
# catch everything and ignore the error.
catch {{}}
$result = @{{
IsFileInfo = (Microsoft.PowerShell.Management\Test-Path $remotePath -PathType Leaf)
IsDirectoryInfo = (Microsoft.PowerShell.Management\Test-Path $remotePath -PathType Container)
}}
if ($parentPath)
{{
$result['ParentIsDirectoryInfo'] = (Microsoft.PowerShell.Management\Test-Path $parentPath -PathType Container)
}}
}}
catch
{{
if ($_.Exception.InnerException)
{{
Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception.InnerException
}}
else
{{
Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception
}}
}}
return $result
}}
# Returns a hashtable with the following information: # Returns a hashtable with the following information:
# - IsFileInfotrue bool to keep track if the given destination is a FileInfo type. # - IsFileInfotrue bool to keep track if the given destination is a FileInfo type.
function PSRemoteDestinationPathIsFile function PSRemoteDestinationPathIsFile
@@ -9130,6 +9273,11 @@ namespace System.Management.Automation.Internal
return PSRemoteDestinationPathIsFile @params return PSRemoteDestinationPathIsFile @params
}} }}
""PSGetRemotePathInfo""
{{
return PSGetRemotePathInfo @params
}}
""PSCreateDirectoryOnRemoteSession"" ""PSCreateDirectoryOnRemoteSession""
{{ {{
return PSCreateDirectoryOnRemoteSession @params return PSCreateDirectoryOnRemoteSession @params
@@ -333,9 +333,6 @@
<data name="CopyItemRemotelyOperationNotSupported" xml:space="preserve"> <data name="CopyItemRemotelyOperationNotSupported" xml:space="preserve">
<value>Remote copy with {0} is not supported.</value> <value>Remote copy with {0} is not supported.</value>
</data> </data>
<data name="CopyItemDirectoryNotFound" xml:space="preserve">
<value>Destination folder '{0}' does not exist.</value>
</data>
<data name="CopyItemRemotelyFailedToCreateDirectory" xml:space="preserve"> <data name="CopyItemRemotelyFailedToCreateDirectory" xml:space="preserve">
<value>Failed to create directory '{0}' on remote destination.</value> <value>Failed to create directory '{0}' on remote destination.</value>
</data> </data>
@@ -935,6 +935,9 @@ Do you want to continue?</value>
<data name="WinRMRestartWarning" xml:space="preserve"> <data name="WinRMRestartWarning" xml:space="preserve">
<value>{0} may need to restart the WinRM service if a configuration using this name has recently been unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required. <value>{0} may need to restart the WinRM service if a configuration using this name has recently been unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required.
All WinRM sessions connected to Windows PowerShell session configurations, such as Microsoft.PowerShell and session configurations that are created with the Register-PSSessionConfiguration cmdlet, are disconnected.</value> All WinRM sessions connected to Windows PowerShell session configurations, such as Microsoft.PowerShell and session configurations that are created with the Register-PSSessionConfiguration cmdlet, are disconnected.</value>
</data>
<data name="WinRMForceRestartWarning" xml:space="preserve">
<value>You are running in a remote session and have selected the Force option which means the WinRM service may restart.If the WinRM service restarts then this remote session will be terminated and you will need to create a new session to continue</value>
</data> </data>
<data name="JobSourceAdapterCannotSaveNullJob" xml:space="preserve"> <data name="JobSourceAdapterCannotSaveNullJob" xml:space="preserve">
<value>The job was null when trying to save identifiers. Specify a job to save its identifiers.</value> <value>The job was null when trying to save identifiers. Specify a job to save its identifiers.</value>
@@ -463,7 +463,7 @@ namespace System.Management.Automation.Security
[DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern internal static extern
string CryptFindLocalizedName(string pwszCryptName); IntPtr CryptFindLocalizedName(string pwszCryptName);
[DllImport(PinvokeDllNames.CryptAcquireContextDllName, SetLastError = true, CharSet = CharSet.Unicode)] [DllImport(PinvokeDllNames.CryptAcquireContextDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern internal static extern
@@ -1408,13 +1408,12 @@ namespace System.Management.Automation
{ {
defaultMshSnapins = new List<DefaultPSSnapInInformation>() defaultMshSnapins = new List<DefaultPSSnapInInformation>()
{ {
#if !CORECLR //TODO:CORECLR - The 'Diagnostics' and 'Host' modules are not available on OneCore yet
new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null, new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null,
"GetEventResources,Description", "GetEventResources,Vendor"), "GetEventResources,Description", "GetEventResources,Vendor"),
new DefaultPSSnapInInformation("Microsoft.PowerShell.CoreConsoleHost", "Microsoft.PowerShell.ConsoleHost", null, new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null,
"HostMshSnapInResources,Description","HostMshSnapInResources,Vendor"), "HostMshSnapInResources,Description","HostMshSnapInResources,Vendor"),
#endif
CoreSnapin, CoreSnapin,
new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null, new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null,
@@ -1427,7 +1426,7 @@ namespace System.Management.Automation
"SecurityMshSnapInResources,Description","SecurityMshSnapInResources,Vendor") "SecurityMshSnapInResources,Description","SecurityMshSnapInResources,Vendor")
}; };
#if !CORECLR //TODO:CORECLR - The 'Microsoft.WSMan.Management' module will be available on OneCore soon #if !LINUX
if (!Utils.IsWinPEHost()) if (!Utils.IsWinPEHost())
{ {
defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null, defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null,
@@ -29,8 +29,8 @@ namespace System.Management.Automation
internal static class EnumerableExtensions internal static class EnumerableExtensions
{ {
// CORECLR has an implementation of Append built-in.
#if !CORECLR #if !CORECLR
// Porting note: .NET Core has this, but full .NET does not
internal static IEnumerable<T> Append<T>(this IEnumerable<T> collection, T element) internal static IEnumerable<T> Append<T>(this IEnumerable<T> collection, T element)
{ {
foreach (T t in collection) foreach (T t in collection)
@@ -38,7 +38,6 @@ namespace System.Management.Automation
yield return element; yield return element;
} }
#endif #endif
internal static IEnumerable<T> Prepend<T>(this IEnumerable<T> collection, T element) internal static IEnumerable<T> Prepend<T>(this IEnumerable<T> collection, T element)
{ {
yield return element; yield return element;
@@ -189,6 +189,127 @@ namespace Microsoft.PowerShell.Telemetry.Internal
} }
} }
/// <summary>
/// Report that a new local session (runspace) is created
/// </summary>
internal static void ReportLocalSessionCreated(
System.Management.Automation.Runspaces.InitialSessionState iss,
System.Management.Automation.Host.TranscriptionData transcriptionData)
{
bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage);
bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null);
TelemetryWrapper.TraceMessage("PSNewLocalSession", new
{
Constrained = isConstrained,
Transcripting = isTranscripting
});
}
enum RemoteSessionType
{
Unknown,
LocalProcess,
WinRMRemote,
HyperVRemote,
ContainerRemote
}
enum RemoteConfigurationType
{
Unknown,
PSDefault,
PSWorkflow,
ServerManagerWorkflow,
Custom
}
/// <summary>
/// Report that a new remote session (runspace) is created
/// </summary>
internal static void ReportRemoteSessionCreated(
System.Management.Automation.Runspaces.RunspaceConnectionInfo connectionInfo)
{
RemoteSessionType sessionType = RemoteSessionType.Unknown;
RemoteConfigurationType configurationType = RemoteConfigurationType.Unknown;
if (connectionInfo is System.Management.Automation.Runspaces.NewProcessConnectionInfo)
{
sessionType = RemoteSessionType.LocalProcess;
configurationType = RemoteConfigurationType.PSDefault;
}
else
{
System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo;
if (wsManConnectionInfo != null)
{
sessionType = RemoteSessionType.WinRMRemote;
// Parse configuration name from ShellUri:
// ShellUri = 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'
// ConfigName = 'Microsoft.PowerShell'
string configurationName = wsManConnectionInfo.ShellUri;
if (!string.IsNullOrEmpty(configurationName))
{
int index = configurationName.LastIndexOf('/');
if (index > -1)
{
configurationName = configurationName.Substring(index + 1);
}
}
configurationType = GetConfigurationTypefromName(configurationName);
}
else
{
System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo;
if (vmConnectionInfo != null)
{
sessionType = RemoteSessionType.HyperVRemote;
configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName);
}
else
{
System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo;
if (containerConnectionInfo != null)
{
sessionType = RemoteSessionType.ContainerRemote;
configurationType = GetConfigurationTypefromName(
(containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty);
}
}
}
}
TelemetryWrapper.TraceMessage("PSNewRemoteSession", new
{
Type = sessionType,
Configuration = configurationType
});
}
private static RemoteConfigurationType GetConfigurationTypefromName(string name)
{
string configName = (name != null) ? name.Trim() : string.Empty;
if (string.IsNullOrEmpty(configName) ||
configName.Equals("microsoft.powershell", StringComparison.OrdinalIgnoreCase) ||
configName.Equals("microsoft.powershell32", StringComparison.OrdinalIgnoreCase))
{
return RemoteConfigurationType.PSDefault;
}
else if (configName.Equals("microsoft.powershell.workflow", StringComparison.OrdinalIgnoreCase))
{
return RemoteConfigurationType.PSWorkflow;
}
else if (configName.Equals("microsoft.windows.servermanagerworkflows", StringComparison.OrdinalIgnoreCase))
{
return RemoteConfigurationType.ServerManagerWorkflow;
}
else
{
return RemoteConfigurationType.Custom;
}
}
enum ScriptFileType enum ScriptFileType
{ {
None = 0, None = 0,
@@ -676,9 +676,10 @@ namespace NativeMsh
L"Microsoft.Win32.Registry", L"Microsoft.Win32.Registry",
L"mscorlib", L"mscorlib",
L"System.AppContext", L"System.AppContext",
L"System.Buffers",
L"System.Collections.Concurrent", L"System.Collections.Concurrent",
L"System.Collections.Immutable",
L"System.Collections", L"System.Collections",
L"System.Collections.Immutable",
L"System.Collections.NonGeneric", L"System.Collections.NonGeneric",
L"System.Collections.Specialized", L"System.Collections.Specialized",
L"System.ComponentModel.Annotations", L"System.ComponentModel.Annotations",
@@ -690,7 +691,6 @@ namespace NativeMsh
L"System.Console", L"System.Console",
L"System.Core", L"System.Core",
L"System.Data.Common", L"System.Data.Common",
L"System.Data.SqlClient",
L"System.Diagnostics.Contracts", L"System.Diagnostics.Contracts",
L"System.Diagnostics.Debug", L"System.Diagnostics.Debug",
L"System.Diagnostics.DiagnosticSource", L"System.Diagnostics.DiagnosticSource",
@@ -701,6 +701,7 @@ namespace NativeMsh
L"System.Diagnostics.Tools", L"System.Diagnostics.Tools",
L"System.Diagnostics.TraceSource", L"System.Diagnostics.TraceSource",
L"System.Diagnostics.Tracing", L"System.Diagnostics.Tracing",
L"System",
L"System.Dynamic.Runtime", L"System.Dynamic.Runtime",
L"System.Globalization.Calendars", L"System.Globalization.Calendars",
L"System.Globalization", L"System.Globalization",
@@ -714,34 +715,30 @@ namespace NativeMsh
L"System.IO.FileSystem.Primitives", L"System.IO.FileSystem.Primitives",
L"System.IO.FileSystem.Watcher", L"System.IO.FileSystem.Watcher",
L"System.IO.MemoryMappedFiles", L"System.IO.MemoryMappedFiles",
L"System.IO.Packaging",
L"System.IO.Pipes", L"System.IO.Pipes",
L"System.IO.UnmanagedMemoryStream", L"System.IO.UnmanagedMemoryStream",
L"System.Linq", L"System.Linq",
L"System.Linq.Expressions", L"System.Linq.Expressions",
L"System.Linq.Parallel", L"System.Linq.Parallel",
L"System.Linq.Queryable", L"System.Linq.Queryable",
L"System", L"System.Net",
L"System.Net.Http", L"System.Net.Http",
L"System.Net.Http.WinHttpHandler", L"System.Net.Http.WinHttpHandler",
L"System.Net",
L"System.Net.NameResolution", L"System.Net.NameResolution",
L"System.Net.NetworkInformation", L"System.Net.NetworkInformation",
L"System.Net.Ping",
L"System.Net.Primitives", L"System.Net.Primitives",
L"System.Net.Requests", L"System.Net.Requests",
L"System.Net.Security", L"System.Net.Security",
L"System.Net.Sockets", L"System.Net.Sockets",
L"System.Net.Utilities",
L"System.Net.WebHeaderCollection", L"System.Net.WebHeaderCollection",
L"System.Net.WebSockets.Client", L"System.Net.WebSockets.Client",
L"System.Net.WebSockets", L"System.Net.WebSockets",
L"System.Numerics", L"System.Numerics",
L"System.Numerics.Vectors", L"System.Numerics.Vectors",
L"System.ObjectModel", L"System.ObjectModel",
L"System.Private.CompilerServices.ICastable",
L"System.Private.CoreLib.InteropServices",
L"System.Private.DataContractSerialization", L"System.Private.DataContractSerialization",
L"System.Private.Interop",
L"System.Private.Networking",
L"System.Private.ServiceModel", L"System.Private.ServiceModel",
L"System.Private.Uri", L"System.Private.Uri",
L"System.Reflection.DispatchProxy", L"System.Reflection.DispatchProxy",
@@ -760,11 +757,12 @@ namespace NativeMsh
L"System.Runtime.Extensions", L"System.Runtime.Extensions",
L"System.Runtime.Handles", L"System.Runtime.Handles",
L"System.Runtime.InteropServices", L"System.Runtime.InteropServices",
L"System.Runtime.InteropServices.PInvoke",
L"System.Runtime.InteropServices.RuntimeInformation", L"System.Runtime.InteropServices.RuntimeInformation",
L"System.Runtime.Loader", L"System.Runtime.Loader",
L"System.Runtime.Numerics", L"System.Runtime.Numerics",
L"System.Runtime.Serialization.Json",
L"System.Runtime.Serialization", L"System.Runtime.Serialization",
L"System.Runtime.Serialization.Json",
L"System.Runtime.Serialization.Primitives", L"System.Runtime.Serialization.Primitives",
L"System.Runtime.Serialization.Xml", L"System.Runtime.Serialization.Xml",
L"System.Security.AccessControl", L"System.Security.AccessControl",
@@ -772,45 +770,39 @@ namespace NativeMsh
L"System.Security.Cryptography.Algorithms", L"System.Security.Cryptography.Algorithms",
L"System.Security.Cryptography.Cng", L"System.Security.Cryptography.Cng",
L"System.Security.Cryptography.Csp", L"System.Security.Cryptography.Csp",
L"System.Security.Cryptography.DeriveBytes",
L"System.Security.Cryptography.Encoding", L"System.Security.Cryptography.Encoding",
L"System.Security.Cryptography.Encryption.Aes",
L"System.Security.Cryptography.Encryption",
L"System.Security.Cryptography.Hashing.Algorithms",
L"System.Security.Cryptography.Hashing",
L"System.Security.Cryptography.OpenSsl", L"System.Security.Cryptography.OpenSsl",
L"System.Security.Cryptography.Primitives", L"System.Security.Cryptography.Primitives",
L"System.Security.Cryptography.RandomNumberGenerator",
L"System.Security.Cryptography.RSA",
L"System.Security.Cryptography.X509Certificates", L"System.Security.Cryptography.X509Certificates",
L"System.Security.Principal", L"System.Security.Principal",
L"System.Security.Principal.Windows", L"System.Security.Principal.Windows",
L"System.Security.SecureString", L"System.Security.SecureString",
L"System.ServiceModel",
L"System.ServiceModel.Duplex", L"System.ServiceModel.Duplex",
L"System.ServiceModel.Http", L"System.ServiceModel.Http",
L"System.ServiceModel",
L"System.ServiceModel.NetTcp", L"System.ServiceModel.NetTcp",
L"System.ServiceModel.Primitives", L"System.ServiceModel.Primitives",
L"System.ServiceModel.Security", L"System.ServiceModel.Security",
L"System.ServiceModel.Web", L"System.ServiceModel.Web",
L"System.ServiceProcess.ServiceController", L"System.ServiceProcess.ServiceController",
L"System.Text.Encoding.CodePages", L"System.Text.Encoding.CodePages",
L"System.Text.Encoding.Extensions",
L"System.Text.Encoding", L"System.Text.Encoding",
L"System.Text.Encoding.Web", L"System.Text.Encoding.Extensions",
L"System.Text.Encodings.Web",
L"System.Text.RegularExpressions", L"System.Text.RegularExpressions",
L"System.Threading.AccessControl", L"System.Threading.AccessControl",
L"System.Threading", L"System.Threading",
L"System.Threading.Overlapped", L"System.Threading.Overlapped",
L"System.Threading.Tasks.Dataflow", L"System.Threading.Tasks.Dataflow",
L"System.Threading.Tasks", L"System.Threading.Tasks",
L"System.Threading.Tasks.Extensions",
L"System.Threading.Tasks.Parallel", L"System.Threading.Tasks.Parallel",
L"System.Threading.Thread", L"System.Threading.Thread",
L"System.Threading.ThreadPool", L"System.Threading.ThreadPool",
L"System.Threading.Timer", L"System.Threading.Timer",
L"System.Windows", L"System.Windows",
L"System.Xml.Linq",
L"System.Xml", L"System.Xml",
L"System.Xml.Linq",
L"System.Xml.ReaderWriter", L"System.Xml.ReaderWriter",
L"System.Xml.Serialization", L"System.Xml.Serialization",
L"System.Xml.XDocument", L"System.Xml.XDocument",
@@ -11,7 +11,7 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
"Get-EventSubscriber", "Unregister-Event", "New-Event", "Add-Member", "Add-Type", "Compare-Object", "Get-EventSubscriber", "Unregister-Event", "New-Event", "Add-Member", "Add-Type", "Compare-Object",
"ConvertFrom-StringData", "Export-Csv", "Import-Csv", "ConvertTo-Csv", "ConvertFrom-Csv", "Export-Alias", "ConvertFrom-StringData", "Export-Csv", "Import-Csv", "ConvertTo-Csv", "ConvertFrom-Csv", "Export-Alias",
"Invoke-Expression", "Get-Alias", "Get-Culture", "Get-Date", "Get-Host", "Get-Member", "Get-Random", "Invoke-Expression", "Get-Alias", "Get-Culture", "Get-Date", "Get-Host", "Get-Member", "Get-Random",
"Get-UICulture", "Get-FileHash", "Get-Unique", "Import-Alias", "Import-LocalizedData", "Get-UICulture", "Get-Unique", "Import-Alias", "Import-LocalizedData",
"Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date",
"Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData", "Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData",
"Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object",
@@ -20,8 +20,10 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
"Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint",
"Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", "Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack",
"Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", "Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug",
"Get-RunspaceDebug", "Wait-Debugger", "Convert-String", "New-TemporaryFile", "New-Guid", "Format-Hex", "Get-RunspaceDebug", "Wait-Debugger"
"Import-PowerShellDataFile", "ConvertFrom-SddlString" FunctionsToExport= "Get-FileHash", "New-TemporaryFile", "New-Guid", "Format-Hex", "Import-PowerShellDataFile",
"ConvertFrom-SddlString"
AliasesToExport= "fhx"
NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390787' HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390787'
} }