From 479814594ccea917f8fda215b4653db04275cb43 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 29 Sep 2017 16:57:11 -0700 Subject: [PATCH] [feature] fix CRLF to LF --- docker/release/nanoserver-insider/Dockerfile | 110 +- .../CommonUtils.cs | 312 +- .../en-US/PSReadline.md | 1026 ++-- .../resources/CertificateProviderStrings.resx | 384 +- .../Microsoft.PowerShell.Utility.psm1 | 348 +- .../Microsoft.PowerShell.Utility.psd1 | 60 +- .../CimCmdlets/CimCmdlets.psd1 | 36 +- .../WSMan.format.ps1xml | 472 +- .../PSDiagnostics/PSDiagnostics.psd1 | 26 +- .../PSDiagnostics/PSDiagnostics.psm1 | 892 ++-- .../Microsoft.PowerShell.Diagnostics.psd1 | 26 +- .../Microsoft.PowerShell.Utility.psd1 | 60 +- .../Diagnostics.format.ps1xml | 158 +- .../Event.format.ps1xml | 242 +- .../GetEvent.types.ps1xml | 278 +- .../Microsoft.PowerShell.LocalAccounts.psd1 | 64 +- .../Microsoft.PowerShell.ODataAdapter.ps1 | 4140 ++++++++--------- .../Microsoft.PowerShell.ODataUtils.psd1 | 480 +- .../Microsoft.PowerShell.ODataUtils.psm1 | 462 +- .../Microsoft.PowerShell.ODataUtilsHelper.ps1 | 1564 +++---- ...icrosoft.PowerShell.ODataUtilsStrings.psd1 | 108 +- .../Microsoft.PowerShell.Utility.psd1 | 64 +- .../PSScheduledJob.Format.ps1xml | 234 +- .../PSScheduledJob.types.ps1xml | 48 +- src/Schemas/PSMaml/Maml.tbr | 2853 ++++++------ src/Schemas/PSMaml/Maml_HTML.xsl | 14 +- .../displayResourceManagerCache.cs | 6 +- .../remoting/commands/PushRunspaceCommand.cs | 20 +- .../resources/CmdletizationCoreResources.resx | 406 +- .../CatalogTestData/CatalogTestFile1.mof | 84 +- 30 files changed, 7488 insertions(+), 7489 deletions(-) diff --git a/docker/release/nanoserver-insider/Dockerfile b/docker/release/nanoserver-insider/Dockerfile index e0ef088f68b..91b45e60b82 100755 --- a/docker/release/nanoserver-insider/Dockerfile +++ b/docker/release/nanoserver-insider/Dockerfile @@ -1,55 +1,55 @@ -# escape=` -# Args used by from statements must be defined here: -ARG NanoServerVersion=10.0.16257.1000 -ARG WindowsServerCoreVersion=10.0.16257.1000 -ARG WindowsServerCoreRepo=microsoft/windowsservercore-insider -ARG NanoServerRepo=microsoft/nanoserver-insider - -# Use server core as an installer container to extract PowerShell, -# As this is a multi-stage build, this stage will eventually be thrown away -FROM ${WindowsServerCoreRepo}:$WindowsServerCoreVersion AS installer-env - -# Arguments for installing powershell, must be defined in the container they are used -ARG PS_VERSION=6.0.0-beta.7 - -ENV PS_DOWNLOAD_URL https://github.com/PowerShell/PowerShell/releases/download/v$PS_VERSION/PowerShell-$PS_VERSION-win-x64.zip - -SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] -RUN Invoke-WebRequest $Env:PS_DOWNLOAD_URL -OutFile powershell.zip - -RUN Expand-Archive powershell.zip -DestinationPath \PowerShell - -# Install PowerShell into NanoServer -FROM ${NanoServerRepo}:$NanoServerVersion - -ARG VCS_REF="none" -ARG PS_VERSION=6.0.0-beta.7 -ARG IMAGE_NAME=microsoft/nanoserver-insider-powershell - -LABEL maintainer="PowerShell Team " ` - readme.md="https://github.com/PowerShell/PowerShell/blob/master/docker/README.md" ` - description="This Dockerfile will install the latest release of PS." ` - org.label-schema.usage="https://github.com/PowerShell/PowerShell/tree/master/docker#run-the-docker-image-you-built" ` - org.label-schema.url="https://github.com/PowerShell/PowerShell/blob/master/docker/README.md" ` - org.label-schema.vcs-url="https://github.com/PowerShell/PowerShell" ` - org.label-schema.name="powershell" ` - org.label-schema.vcs-ref=${VCS_REF} ` - org.label-schema.vendor="PowerShell" ` - org.label-schema.version=${PS_VERSION} ` - org.label-schema.schema-version="1.0" ` - org.label-schema.docker.cmd="docker run ${IMAGE_NAME} powershell -c '$psversiontable'" ` - org.label-schema.docker.cmd.devel="docker run ${IMAGE_NAME}" ` - org.label-schema.docker.cmd.test="docker run ${IMAGE_NAME} powershell -c Invoke-Pester" ` - org.label-schema.docker.cmd.help="docker run ${IMAGE_NAME} powershell -c Get-Help" - -# Copy Powershell from the installer containter -ENV ProgramFiles C:\Program Files -COPY --from=installer-env ["\\PowerShell\\", "$ProgramFiles\\PowerShell"] - -# Persist %PSCORE% ENV variable for user convenience -ENV PSCORE="$ProgramFiles\PowerShell\PowerShell.exe" - -# Set the path -RUN setx PATH "%PATH%;%ProgramFiles%\PowerShell" - -CMD ["PowerShell.exe"] +# escape=` +# Args used by from statements must be defined here: +ARG NanoServerVersion=10.0.16257.1000 +ARG WindowsServerCoreVersion=10.0.16257.1000 +ARG WindowsServerCoreRepo=microsoft/windowsservercore-insider +ARG NanoServerRepo=microsoft/nanoserver-insider + +# Use server core as an installer container to extract PowerShell, +# As this is a multi-stage build, this stage will eventually be thrown away +FROM ${WindowsServerCoreRepo}:$WindowsServerCoreVersion AS installer-env + +# Arguments for installing powershell, must be defined in the container they are used +ARG PS_VERSION=6.0.0-beta.7 + +ENV PS_DOWNLOAD_URL https://github.com/PowerShell/PowerShell/releases/download/v$PS_VERSION/PowerShell-$PS_VERSION-win-x64.zip + +SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] +RUN Invoke-WebRequest $Env:PS_DOWNLOAD_URL -OutFile powershell.zip + +RUN Expand-Archive powershell.zip -DestinationPath \PowerShell + +# Install PowerShell into NanoServer +FROM ${NanoServerRepo}:$NanoServerVersion + +ARG VCS_REF="none" +ARG PS_VERSION=6.0.0-beta.7 +ARG IMAGE_NAME=microsoft/nanoserver-insider-powershell + +LABEL maintainer="PowerShell Team " ` + readme.md="https://github.com/PowerShell/PowerShell/blob/master/docker/README.md" ` + description="This Dockerfile will install the latest release of PS." ` + org.label-schema.usage="https://github.com/PowerShell/PowerShell/tree/master/docker#run-the-docker-image-you-built" ` + org.label-schema.url="https://github.com/PowerShell/PowerShell/blob/master/docker/README.md" ` + org.label-schema.vcs-url="https://github.com/PowerShell/PowerShell" ` + org.label-schema.name="powershell" ` + org.label-schema.vcs-ref=${VCS_REF} ` + org.label-schema.vendor="PowerShell" ` + org.label-schema.version=${PS_VERSION} ` + org.label-schema.schema-version="1.0" ` + org.label-schema.docker.cmd="docker run ${IMAGE_NAME} powershell -c '$psversiontable'" ` + org.label-schema.docker.cmd.devel="docker run ${IMAGE_NAME}" ` + org.label-schema.docker.cmd.test="docker run ${IMAGE_NAME} powershell -c Invoke-Pester" ` + org.label-schema.docker.cmd.help="docker run ${IMAGE_NAME} powershell -c Get-Help" + +# Copy Powershell from the installer containter +ENV ProgramFiles C:\Program Files +COPY --from=installer-env ["\\PowerShell\\", "$ProgramFiles\\PowerShell"] + +# Persist %PSCORE% ENV variable for user convenience +ENV PSCORE="$ProgramFiles\PowerShell\PowerShell.exe" + +# Set the path +RUN setx PATH "%PATH%;%ProgramFiles%\PowerShell" + +CMD ["PowerShell.exe"] diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index 182cf59d994..8ee3e95903d 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -1,156 +1,156 @@ -using System; -using System.Collections; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; -using System.Resources; -using System.Reflection; - -#if CORECLR -using System.ComponentModel; -#else -using System.Threading; -#endif - -namespace Microsoft.PowerShell.Commands.Diagnostics.Common -{ - internal static class CommonUtilities - { - // - // StringArrayToString helper converts a string array into a comma-separated string. - // Note this has only limited use, individual strings cannot have commas. - // - public static string StringArrayToString(IEnumerable input) - { - string ret = ""; - foreach (string element in input) - { - ret += element + ", "; - } - - ret = ret.TrimEnd(); - ret = ret.TrimEnd(','); - - return ret; - } - -#if CORECLR - private const string LibraryLoadDllName = "api-ms-win-core-libraryloader-l1-2-0.dll"; - private const string LocalizationDllName = "api-ms-win-core-localization-l1-2-1.dll"; - private const string SysInfoDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct OSVERSIONINFOEX - { - public int OSVersionInfoSize; - public int MajorVersion; - public int MinorVersion; - public int BuildNumber; - public int PlatformId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string CSDVersion; - public ushort ServicePackMajor; - public ushort ServicePackMinor; - public short SuiteMask; - public byte ProductType; - public byte Reserved; - } - - [DllImport(SysInfoDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx); -#else - private const string LibraryLoadDllName = "kernel32.dll"; - private const string LocalizationDllName = "kernel32.dll"; -#endif - - private const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; - private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; - private const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; - - [DllImport(LocalizationDllName, SetLastError = true, CharSet = CharSet.Unicode)] - private static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, - uint dwMessageId, uint dwLanguageId, - [MarshalAs(UnmanagedType.LPWStr)] - StringBuilder lpBuffer, - uint nSize, IntPtr Arguments); - - [DllImport(LibraryLoadDllName, SetLastError = true, CharSet = CharSet.Unicode)] - private static extern IntPtr LoadLibraryEx( - [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - IntPtr hFile, - uint dwFlags - ); - - [DllImport(LibraryLoadDllName)] - private static extern bool FreeLibrary(IntPtr hModule); - - - [DllImport(LocalizationDllName, EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] - private static extern ushort GetUserDefaultLangID(); - - - public static uint FormatMessageFromModule(uint lastError, string moduleName, out String msg) - { - Debug.Assert(!string.IsNullOrEmpty(moduleName)); - - uint formatError = 0; - msg = String.Empty; - IntPtr moduleHandle = IntPtr.Zero; - - moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); - if (moduleHandle == IntPtr.Zero) - { - return (uint)Marshal.GetLastWin32Error(); - } - - try - { - uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; - uint LANGID = (uint)GetUserDefaultLangID(); - uint langError = (uint)Marshal.GetLastWin32Error(); - if (langError != 0) - { - LANGID = 0; // neutral - } - - StringBuilder outStringBuilder = new StringBuilder(1024); - uint nChars = FormatMessage(dwFormatFlags, - moduleHandle, - lastError, - LANGID, - outStringBuilder, - (uint)outStringBuilder.Capacity, - IntPtr.Zero); - - if (nChars == 0) - { - formatError = (uint)Marshal.GetLastWin32Error(); - //Console.WriteLine("Win32FormatMessage", String.Format(null, "Error formatting message: {0}", formatError)); - } - else - { - msg = outStringBuilder.ToString(); - if (msg.EndsWith(Environment.NewLine, StringComparison.Ordinal)) - { - msg = msg.Substring(0, msg.Length - 2); - } - } - } - finally - { - FreeLibrary(moduleHandle); - } - return formatError; - } - - public static ResourceManager GetResourceManager() - { - // this naming pattern is dictated by the dotnet cli - return new ResourceManager("Microsoft.PowerShell.Commands.Diagnostics.resources.GetEventResources", typeof(CommonUtilities).GetTypeInfo().Assembly); - } - } -} - +using System; +using System.Collections; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Resources; +using System.Reflection; + +#if CORECLR +using System.ComponentModel; +#else +using System.Threading; +#endif + +namespace Microsoft.PowerShell.Commands.Diagnostics.Common +{ + internal static class CommonUtilities + { + // + // StringArrayToString helper converts a string array into a comma-separated string. + // Note this has only limited use, individual strings cannot have commas. + // + public static string StringArrayToString(IEnumerable input) + { + string ret = ""; + foreach (string element in input) + { + ret += element + ", "; + } + + ret = ret.TrimEnd(); + ret = ret.TrimEnd(','); + + return ret; + } + +#if CORECLR + private const string LibraryLoadDllName = "api-ms-win-core-libraryloader-l1-2-0.dll"; + private const string LocalizationDllName = "api-ms-win-core-localization-l1-2-1.dll"; + private const string SysInfoDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct OSVERSIONINFOEX + { + public int OSVersionInfoSize; + public int MajorVersion; + public int MinorVersion; + public int BuildNumber; + public int PlatformId; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string CSDVersion; + public ushort ServicePackMajor; + public ushort ServicePackMinor; + public short SuiteMask; + public byte ProductType; + public byte Reserved; + } + + [DllImport(SysInfoDllName, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx); +#else + private const string LibraryLoadDllName = "kernel32.dll"; + private const string LocalizationDllName = "kernel32.dll"; +#endif + + private const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; + private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; + private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; + private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; + private const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; + + [DllImport(LocalizationDllName, SetLastError = true, CharSet = CharSet.Unicode)] + private static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, + uint dwMessageId, uint dwLanguageId, + [MarshalAs(UnmanagedType.LPWStr)] + StringBuilder lpBuffer, + uint nSize, IntPtr Arguments); + + [DllImport(LibraryLoadDllName, SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr LoadLibraryEx( + [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, + IntPtr hFile, + uint dwFlags + ); + + [DllImport(LibraryLoadDllName)] + private static extern bool FreeLibrary(IntPtr hModule); + + + [DllImport(LocalizationDllName, EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] + private static extern ushort GetUserDefaultLangID(); + + + public static uint FormatMessageFromModule(uint lastError, string moduleName, out String msg) + { + Debug.Assert(!string.IsNullOrEmpty(moduleName)); + + uint formatError = 0; + msg = String.Empty; + IntPtr moduleHandle = IntPtr.Zero; + + moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); + if (moduleHandle == IntPtr.Zero) + { + return (uint)Marshal.GetLastWin32Error(); + } + + try + { + uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; + uint LANGID = (uint)GetUserDefaultLangID(); + uint langError = (uint)Marshal.GetLastWin32Error(); + if (langError != 0) + { + LANGID = 0; // neutral + } + + StringBuilder outStringBuilder = new StringBuilder(1024); + uint nChars = FormatMessage(dwFormatFlags, + moduleHandle, + lastError, + LANGID, + outStringBuilder, + (uint)outStringBuilder.Capacity, + IntPtr.Zero); + + if (nChars == 0) + { + formatError = (uint)Marshal.GetLastWin32Error(); + //Console.WriteLine("Win32FormatMessage", String.Format(null, "Error formatting message: {0}", formatError)); + } + else + { + msg = outStringBuilder.ToString(); + if (msg.EndsWith(Environment.NewLine, StringComparison.Ordinal)) + { + msg = msg.Substring(0, msg.Length - 2); + } + } + } + finally + { + FreeLibrary(moduleHandle); + } + return formatError; + } + + public static ResourceManager GetResourceManager() + { + // this naming pattern is dictated by the dotnet cli + return new ResourceManager("Microsoft.PowerShell.Commands.Diagnostics.resources.GetEventResources", typeof(CommonUtilities).GetTypeInfo().Assembly); + } + } +} + diff --git a/src/Microsoft.PowerShell.PSReadLine/en-US/PSReadline.md b/src/Microsoft.PowerShell.PSReadLine/en-US/PSReadline.md index c92c4872641..2d433a94552 100644 --- a/src/Microsoft.PowerShell.PSReadLine/en-US/PSReadline.md +++ b/src/Microsoft.PowerShell.PSReadLine/en-US/PSReadline.md @@ -1,513 +1,513 @@ -# Get-PSReadlineKeyHandler - -## SYNOPSIS -Gets the key bindings for the PSReadline module. - -## DESCRIPTION -Gets the key bindings for the PSReadline module. - -If neither -Bound nor -Unbound is specified, returns all bound keys and unbound functions. - -If -Bound is specified and -Unbound is not specified, only bound keys are returned. - -If -Unbound is specified and -Bound is not specified, only unbound keys are returned. - -If both -Bound and -Unbound are specified, returns all bound keys and unbound functions. - -## PARAMETERS - -### Bound [switch] = True - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Include functions that are bound. - - -### Unbound [switch] = True - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Include functions that are unbound. - - - -## INPUTS -### None -You cannot pipe objects to Get-PSReadlineKeyHandler - -## OUTPUTS -### Microsoft.PowerShell.KeyHandler - -Returns one entry for each key binding (or chord) for bound functions and/or one entry for each unbound function - - - -## RELATED LINKS - -[about_PSReadline]() - -# Get-PSReadlineOption - -## SYNOPSIS -Returns the values for the options that can be configured. - -## DESCRIPTION -Get-PSReadlineOption returns the current state of the settings that can be configured by Set-PSReadlineOption. - -The object returned can be used to change PSReadline options. -This provides a slightly simpler way of setting syntax coloring options for multiple kinds of tokens. - -## PARAMETERS - - -## INPUTS -### None -You cannot pipe objects to Get-PSReadlineOption - -## OUTPUTS -### - - - - - -## RELATED LINKS - -[about_PSReadline]() - -# Set-PSReadlineKeyHandler - -## SYNOPSIS -Binds or rebinds keys to user defined or PSReadline provided key handlers. - -## DESCRIPTION -This cmdlet is used to customize what happens when a particular key or sequence of keys is pressed while PSReadline is reading input. - -With user defined key bindings, you can do nearly anything that is possible from a PowerShell script. -Typically you might just edit the command line in some novel way, but because the handlers are just PowerShell scripts, you can do interesting things like change directories, launch programs, etc. - -## PARAMETERS - -### Chord [String[]] - -```powershell -[Parameter( - Mandatory = $true, - Position = 0)] -``` - -The key or sequence of keys to be bound to a Function or ScriptBlock. -A single binding is specified with a single string. -If the binding is a sequence of keys, the keys are separated with a comma, e.g. "Ctrl+X,Ctrl+X". -Note that this parameter accepts multiple strings. -Each string is a separate binding, not a sequence of keys for a single binding. - - -### ScriptBlock [ScriptBlock] - -```powershell -[Parameter( - Mandatory = $true, - Position = 1, - ParameterSetName = 'Set 1')] -``` - -The ScriptBlock is called when the Chord is entered. -The ScriptBlock is passed one or sometimes two arguments. -The first argument is the key pressed (a ConsoleKeyInfo.) The second argument could be any object depending on the context. - - -### BriefDescription [String] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -A brief description of the key binding. -Used in the output of cmdlet Get-PSReadlineKeyHandler. - - -### Description [String] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -A more verbose description of the key binding. -Used in the output of the cmdlet Get-PSReadlineKeyHandler. - - -### Function [String] - -```powershell -[Parameter( - Mandatory = $true, - Position = 1, - ParameterSetName = 'Set 2')] -``` - -The name of an existing key handler provided by PSReadline. -This parameter allows one to rebind existing key bindings or to bind a handler provided by PSReadline that is currently unbound. - -Using the ScriptBlock parameter, one can achieve equivalent functionality by calling the method directly from the ScriptBlock. -This parameter is preferred though - it makes it easier to determine which functions are bound and unbound. - - - -## INPUTS -### None -You cannot pipe objects to Set-PSReadlineKeyHandler - -## OUTPUTS -### - - - - -## EXAMPLES -### -------------- Example 1 -------------- - -```powershell -PS C:\> Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward -``` -This command binds the up arrow key to the function HistorySearchBackward which will use the currently entered command line as the beginning of the search string when searching through history. -### -------------- Example 2 -------------- - -```powershell -PS C:\> Set-PSReadlineKeyHandler -Chord Shift+Ctrl+B -ScriptBlock { - [PSConsoleUtilities.PSConsoleReadLine]::RevertLine() - [PSConsoleUtilities.PSConsoleReadLine]::Insert('build') ->>> [PSConsoleUtilities.PSConsoleReadLine]::AcceptLine() -} -``` -This example binds the key Ctrl+Shift+B to a script block that clears the line, inserts build, then accepts the line. -This example shows how a single key can be used to execute a command. - -## RELATED LINKS - -[about_PSReadline]() - -# Set-PSReadlineOption - -## SYNOPSIS -Customizes the behavior of command line editing in PSReadline. - -## DESCRIPTION -The Set-PSReadlineOption cmdlet is used to customize the behavior of the PSReadline module when editing the command line. - -## PARAMETERS - -### EditMode [EditMode] = Windows - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the command line editing mode. -This will reset any key bindings set by Set-PSReadlineKeyHandler. - -Valid values are: - --- Windows: Key bindings emulate PowerShell/cmd with some bindings emulating Visual Studio. - --- Emacs: Key bindings emulate Bash or Emacs. - - -### ContinuationPrompt [String] = >>> - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the string displayed at the beginning of the second and subsequent lines when multi-line input is being entered. -Defaults to '\>\>\> '. -The empty string is valid. - - -### ContinuationPromptForegroundColor [ConsoleColor] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the foreground color of the continuation prompt. - - -### ContinuationPromptBackgroundColor [ConsoleColor] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the background color of the continuation prompt. - - -### EmphasisForegroundColor [ConsoleColor] = Cyan - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the foreground color used for emphasis, e.g. -to highlight search text. - - -### EmphasisBackgroundColor [ConsoleColor] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the background color used for emphasis, e.g. -to highlight search text. - - -### ErrorForegroundColor [ConsoleColor] = Red - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the foreground color used for errors. - - -### ErrorBackgroundColor [ConsoleColor] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the background color used for errors. - - -### HistoryNoDuplicates [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies that duplicate commands should not be added to PSReadline history. - - -### AddToHistoryHandler [Func[String, Boolean]] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies a ScriptBlock that can be used to control which commands get added to PSReadline history. - - -### ValidationHandler [Func[String, Object]] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies a ScriptBlock that is called from ValidateAndAcceptLine. -If a non-null object is returned or an exception is thrown, validation fails and the error is reported. -If the object returned/thrown has a Message property, it's value is used in the error message, and if there is an Offset property, the cursor is moved to that offset after reporting the error. -If there is no Message property, the ToString method is called to report the error. - - -### HistorySearchCursorMovesToEnd [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - - - - -### MaximumHistoryCount [Int32] = 1024 - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the maximum number of commands to save in PSReadline history. -Note that PSReadline history is separate from PowerShell history. - - -### MaximumKillRingCount [Int32] = 10 - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the maximum number of items stored in the kill ring. - - -### ResetTokenColors [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Restore the token colors to the default settings. - - -### ShowToolTips [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -When displaying possible completions, show tooltips in the list of completions. - - -### ExtraPromptLineCount [Int32] = 0 - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Use this option if your prompt spans more than one line and you want the extra lines to appear when PSReadline displays the prompt after showing some output, e.g. -when showing a list of completions. - - -### DingTone [Int32] = 1221 - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -When BellStyle is set to Audible, specifies the tone of the beep. - - -### DingDuration [Int32] = 50ms - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -When BellStyle is set to Audible, specifies the duration of the beep. - - -### BellStyle [BellStyle] = Audible - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies how PSReadline should respond to various error and ambiguous conditions. - -Valid values are: - --- Audible: a short beep - --- Visible: a brief flash is performed - --- None: no feedback - - -### CompletionQueryItems [Int32] = 100 - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the maximum number of completion items that will be shown without prompting. -If the number of items to show is greater than this value, PSReadline will prompt y/n before displaying the completion items. - - -### WordDelimiters [string] = ;:,.[]{}()/\|^&*-=+ - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the characters that delimit words for functions like ForwardWord or KillWord. - - -### HistorySearchCaseSensitive [switch] - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the searching history is case sensitive in functions like ReverseSearchHistory or HistorySearchBackward. - - -### HistorySaveStyle [HistorySaveStyle] = SaveIncrementally - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies how PSReadline should save history. - -Valid values are: - --- SaveIncrementally: save history after each command is executed - and share across multiple instances of PowerShell - --- SaveAtExit: append history file when PowerShell exits - --- SaveNothing: don't use a history file - - -### HistorySavePath [String] = ~\AppData\Roaming\PSReadline\$($host.Name)_history.txt - -```powershell -[Parameter(ParameterSetName = 'Set 1')] -``` - -Specifies the path to the history file. - - -### TokenKind [TokenClassification] - -```powershell -[Parameter( - Mandatory = $true, - Position = 0, - ParameterSetName = 'Set 2')] -``` - -Specifies the kind of token when setting token coloring options with the -ForegroundColor and -BackgroundColor parameters. - - -### ForegroundColor [ConsoleColor] - -```powershell -[Parameter( - Position = 1, - ParameterSetName = 'Set 2')] -``` - -Specifies the foreground color for the token kind specified by the parameter -TokenKind. - - -### BackgroundColor [ConsoleColor] - -```powershell -[Parameter( - Position = 2, - ParameterSetName = 'Set 2')] -``` - -Specifies the background color for the token kind specified by the parameter -TokenKind. - - - -## INPUTS -### None -You cannot pipe objects to Set-PSReadlineOption - - -## OUTPUTS -### None -This cmdlet does not generate any output. - - - - -## RELATED LINKS - -[about_PSReadline]() - - +# Get-PSReadlineKeyHandler + +## SYNOPSIS +Gets the key bindings for the PSReadline module. + +## DESCRIPTION +Gets the key bindings for the PSReadline module. + +If neither -Bound nor -Unbound is specified, returns all bound keys and unbound functions. + +If -Bound is specified and -Unbound is not specified, only bound keys are returned. + +If -Unbound is specified and -Bound is not specified, only unbound keys are returned. + +If both -Bound and -Unbound are specified, returns all bound keys and unbound functions. + +## PARAMETERS + +### Bound [switch] = True + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Include functions that are bound. + + +### Unbound [switch] = True + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Include functions that are unbound. + + + +## INPUTS +### None +You cannot pipe objects to Get-PSReadlineKeyHandler + +## OUTPUTS +### Microsoft.PowerShell.KeyHandler + +Returns one entry for each key binding (or chord) for bound functions and/or one entry for each unbound function + + + +## RELATED LINKS + +[about_PSReadline]() + +# Get-PSReadlineOption + +## SYNOPSIS +Returns the values for the options that can be configured. + +## DESCRIPTION +Get-PSReadlineOption returns the current state of the settings that can be configured by Set-PSReadlineOption. + +The object returned can be used to change PSReadline options. +This provides a slightly simpler way of setting syntax coloring options for multiple kinds of tokens. + +## PARAMETERS + + +## INPUTS +### None +You cannot pipe objects to Get-PSReadlineOption + +## OUTPUTS +### + + + + + +## RELATED LINKS + +[about_PSReadline]() + +# Set-PSReadlineKeyHandler + +## SYNOPSIS +Binds or rebinds keys to user defined or PSReadline provided key handlers. + +## DESCRIPTION +This cmdlet is used to customize what happens when a particular key or sequence of keys is pressed while PSReadline is reading input. + +With user defined key bindings, you can do nearly anything that is possible from a PowerShell script. +Typically you might just edit the command line in some novel way, but because the handlers are just PowerShell scripts, you can do interesting things like change directories, launch programs, etc. + +## PARAMETERS + +### Chord [String[]] + +```powershell +[Parameter( + Mandatory = $true, + Position = 0)] +``` + +The key or sequence of keys to be bound to a Function or ScriptBlock. +A single binding is specified with a single string. +If the binding is a sequence of keys, the keys are separated with a comma, e.g. "Ctrl+X,Ctrl+X". +Note that this parameter accepts multiple strings. +Each string is a separate binding, not a sequence of keys for a single binding. + + +### ScriptBlock [ScriptBlock] + +```powershell +[Parameter( + Mandatory = $true, + Position = 1, + ParameterSetName = 'Set 1')] +``` + +The ScriptBlock is called when the Chord is entered. +The ScriptBlock is passed one or sometimes two arguments. +The first argument is the key pressed (a ConsoleKeyInfo.) The second argument could be any object depending on the context. + + +### BriefDescription [String] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +A brief description of the key binding. +Used in the output of cmdlet Get-PSReadlineKeyHandler. + + +### Description [String] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +A more verbose description of the key binding. +Used in the output of the cmdlet Get-PSReadlineKeyHandler. + + +### Function [String] + +```powershell +[Parameter( + Mandatory = $true, + Position = 1, + ParameterSetName = 'Set 2')] +``` + +The name of an existing key handler provided by PSReadline. +This parameter allows one to rebind existing key bindings or to bind a handler provided by PSReadline that is currently unbound. + +Using the ScriptBlock parameter, one can achieve equivalent functionality by calling the method directly from the ScriptBlock. +This parameter is preferred though - it makes it easier to determine which functions are bound and unbound. + + + +## INPUTS +### None +You cannot pipe objects to Set-PSReadlineKeyHandler + +## OUTPUTS +### + + + + +## EXAMPLES +### -------------- Example 1 -------------- + +```powershell +PS C:\> Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward +``` +This command binds the up arrow key to the function HistorySearchBackward which will use the currently entered command line as the beginning of the search string when searching through history. +### -------------- Example 2 -------------- + +```powershell +PS C:\> Set-PSReadlineKeyHandler -Chord Shift+Ctrl+B -ScriptBlock { + [PSConsoleUtilities.PSConsoleReadLine]::RevertLine() + [PSConsoleUtilities.PSConsoleReadLine]::Insert('build') +>>> [PSConsoleUtilities.PSConsoleReadLine]::AcceptLine() +} +``` +This example binds the key Ctrl+Shift+B to a script block that clears the line, inserts build, then accepts the line. +This example shows how a single key can be used to execute a command. + +## RELATED LINKS + +[about_PSReadline]() + +# Set-PSReadlineOption + +## SYNOPSIS +Customizes the behavior of command line editing in PSReadline. + +## DESCRIPTION +The Set-PSReadlineOption cmdlet is used to customize the behavior of the PSReadline module when editing the command line. + +## PARAMETERS + +### EditMode [EditMode] = Windows + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the command line editing mode. +This will reset any key bindings set by Set-PSReadlineKeyHandler. + +Valid values are: + +-- Windows: Key bindings emulate PowerShell/cmd with some bindings emulating Visual Studio. + +-- Emacs: Key bindings emulate Bash or Emacs. + + +### ContinuationPrompt [String] = >>> + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the string displayed at the beginning of the second and subsequent lines when multi-line input is being entered. +Defaults to '\>\>\> '. +The empty string is valid. + + +### ContinuationPromptForegroundColor [ConsoleColor] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the foreground color of the continuation prompt. + + +### ContinuationPromptBackgroundColor [ConsoleColor] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the background color of the continuation prompt. + + +### EmphasisForegroundColor [ConsoleColor] = Cyan + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the foreground color used for emphasis, e.g. +to highlight search text. + + +### EmphasisBackgroundColor [ConsoleColor] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the background color used for emphasis, e.g. +to highlight search text. + + +### ErrorForegroundColor [ConsoleColor] = Red + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the foreground color used for errors. + + +### ErrorBackgroundColor [ConsoleColor] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the background color used for errors. + + +### HistoryNoDuplicates [switch] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies that duplicate commands should not be added to PSReadline history. + + +### AddToHistoryHandler [Func[String, Boolean]] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies a ScriptBlock that can be used to control which commands get added to PSReadline history. + + +### ValidationHandler [Func[String, Object]] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies a ScriptBlock that is called from ValidateAndAcceptLine. +If a non-null object is returned or an exception is thrown, validation fails and the error is reported. +If the object returned/thrown has a Message property, it's value is used in the error message, and if there is an Offset property, the cursor is moved to that offset after reporting the error. +If there is no Message property, the ToString method is called to report the error. + + +### HistorySearchCursorMovesToEnd [switch] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + + + + +### MaximumHistoryCount [Int32] = 1024 + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the maximum number of commands to save in PSReadline history. +Note that PSReadline history is separate from PowerShell history. + + +### MaximumKillRingCount [Int32] = 10 + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the maximum number of items stored in the kill ring. + + +### ResetTokenColors [switch] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Restore the token colors to the default settings. + + +### ShowToolTips [switch] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +When displaying possible completions, show tooltips in the list of completions. + + +### ExtraPromptLineCount [Int32] = 0 + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Use this option if your prompt spans more than one line and you want the extra lines to appear when PSReadline displays the prompt after showing some output, e.g. +when showing a list of completions. + + +### DingTone [Int32] = 1221 + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +When BellStyle is set to Audible, specifies the tone of the beep. + + +### DingDuration [Int32] = 50ms + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +When BellStyle is set to Audible, specifies the duration of the beep. + + +### BellStyle [BellStyle] = Audible + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies how PSReadline should respond to various error and ambiguous conditions. + +Valid values are: + +-- Audible: a short beep + +-- Visible: a brief flash is performed + +-- None: no feedback + + +### CompletionQueryItems [Int32] = 100 + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the maximum number of completion items that will be shown without prompting. +If the number of items to show is greater than this value, PSReadline will prompt y/n before displaying the completion items. + + +### WordDelimiters [string] = ;:,.[]{}()/\|^&*-=+ + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the characters that delimit words for functions like ForwardWord or KillWord. + + +### HistorySearchCaseSensitive [switch] + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the searching history is case sensitive in functions like ReverseSearchHistory or HistorySearchBackward. + + +### HistorySaveStyle [HistorySaveStyle] = SaveIncrementally + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies how PSReadline should save history. + +Valid values are: + +-- SaveIncrementally: save history after each command is executed - and share across multiple instances of PowerShell + +-- SaveAtExit: append history file when PowerShell exits + +-- SaveNothing: don't use a history file + + +### HistorySavePath [String] = ~\AppData\Roaming\PSReadline\$($host.Name)_history.txt + +```powershell +[Parameter(ParameterSetName = 'Set 1')] +``` + +Specifies the path to the history file. + + +### TokenKind [TokenClassification] + +```powershell +[Parameter( + Mandatory = $true, + Position = 0, + ParameterSetName = 'Set 2')] +``` + +Specifies the kind of token when setting token coloring options with the -ForegroundColor and -BackgroundColor parameters. + + +### ForegroundColor [ConsoleColor] + +```powershell +[Parameter( + Position = 1, + ParameterSetName = 'Set 2')] +``` + +Specifies the foreground color for the token kind specified by the parameter -TokenKind. + + +### BackgroundColor [ConsoleColor] + +```powershell +[Parameter( + Position = 2, + ParameterSetName = 'Set 2')] +``` + +Specifies the background color for the token kind specified by the parameter -TokenKind. + + + +## INPUTS +### None +You cannot pipe objects to Set-PSReadlineOption + + +## OUTPUTS +### None +This cmdlet does not generate any output. + + + + +## RELATED LINKS + +[about_PSReadline]() + + diff --git a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx index 7884140dd38..ded11aab0a2 100644 --- a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx +++ b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx @@ -1,192 +1,192 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - X509 Certificate Provider - - - Cannot find the X509 certificate at path {0}. - - - Cannot find the X509 certificate store at path {0}. - - - Cannot find the certificate store because the specified X509 store location {0} is not valid. - - - Cannot process the path because path {0} is not a valid certificate provider path. - - - Move certificate - - - Remove certificate - - - Remove certificate and its private key. - - - Invoke Certificate Manager - - - {0} is not supported in the current operating system. - - - Item: {0} Destination: {1} - - - You cannot move a certificate container. - - - You cannot move a certificate from user store to or from machine. - - - You cannot move a certificate to the same store. - - - You cannot create an item other than certificate store. - - - Creating certificate stores under CurrentUser is not supported. - - - Deleting certificate stores under CurrentUser is not supported. - - - The destination is not a valid store. - - - Item: {0} - - - The store {0} is a built-in system store and cannot be deleted. - - - You cannot remove a certificate container. - - - Private key skipped. The certificate has no private key association. - - - The operation is on user root store and UI is not allowed. - - - . The following error may be a result of user credentials required on the remote machine. See Enable-WSManCredSSP Cmdlet help on how to enable and use CredSSP for delegation with PowerShell remoting. - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + X509 Certificate Provider + + + Cannot find the X509 certificate at path {0}. + + + Cannot find the X509 certificate store at path {0}. + + + Cannot find the certificate store because the specified X509 store location {0} is not valid. + + + Cannot process the path because path {0} is not a valid certificate provider path. + + + Move certificate + + + Remove certificate + + + Remove certificate and its private key. + + + Invoke Certificate Manager + + + {0} is not supported in the current operating system. + + + Item: {0} Destination: {1} + + + You cannot move a certificate container. + + + You cannot move a certificate from user store to or from machine. + + + You cannot move a certificate to the same store. + + + You cannot create an item other than certificate store. + + + Creating certificate stores under CurrentUser is not supported. + + + Deleting certificate stores under CurrentUser is not supported. + + + The destination is not a valid store. + + + Item: {0} + + + The store {0} is a built-in system store and cannot be deleted. + + + You cannot remove a certificate container. + + + Private key skipped. The certificate has no private key association. + + + The operation is on user root store and UI is not allowed. + + + . The following error may be a result of user credentials required on the remote machine. See Enable-WSManCredSSP Cmdlet help on how to enable and use CredSSP for delegation with PowerShell remoting. + + diff --git a/src/Modules/Shared/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psm1 b/src/Modules/Shared/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psm1 index 322c671fcb0..cd915abe7ae 100644 --- a/src/Modules/Shared/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psm1 +++ b/src/Modules/Shared/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psm1 @@ -1,174 +1,174 @@ - -## Converts a SDDL string into an object-based representation of a security -## descriptor -function ConvertFrom-SddlString -{ - [CmdletBinding(HelpUri = "https://go.microsoft.com/fwlink/?LinkId=623636")] - param( - ## The string representing the security descriptor in SDDL syntax - [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] - [String] $Sddl, - - ## The type of rights that this SDDL string represents, if any. - [Parameter()] - [ValidateSet( - "FileSystemRights", "RegistryRights", "ActiveDirectoryRights", - "MutexRights", "SemaphoreRights", "CryptoKeyRights", - "EventWaitHandleRights")] - $Type - ) - - Begin - { - # On CoreCLR CryptoKeyRights and ActiveDirectoryRights are not supported. - if ($PSEdition -eq "Core" -and ($Type -eq "CryptoKeyRights" -or $Type -eq "ActiveDirectoryRights")) - { - $errorId = "TypeNotSupported" - $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument - $errorMessage = [Microsoft.PowerShell.Commands.UtilityResources]::TypeNotSupported -f $Type - $exception = [System.ArgumentException]::New($errorMessage) - $errorRecord = [System.Management.Automation.ErrorRecord]::New($exception, $errorId, $errorCategory, $null) - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - ## Translates a SID into a NT Account - function ConvertTo-NtAccount - { - param($Sid) - - if($Sid) - { - $securityIdentifier = [System.Security.Principal.SecurityIdentifier] $Sid - - try - { - $ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount]).ToString() - } - catch{} - - $ntAccount - } - } - - ## Gets the access rights that apply to an access mask, preferring right types - ## of 'Type' if specified. - function Get-AccessRights - { - param($AccessMask, $Type) - - if ($PSEdition -eq "Core") - { - ## All the types of access rights understood by .NET Core - $rightTypes = [Ordered] @{ - "FileSystemRights" = [System.Security.AccessControl.FileSystemRights] - "RegistryRights" = [System.Security.AccessControl.RegistryRights] - "MutexRights" = [System.Security.AccessControl.MutexRights] - "SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights] - "EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights] - } - } - else - { - ## All the types of access rights understood by .NET - $rightTypes = [Ordered] @{ - "FileSystemRights" = [System.Security.AccessControl.FileSystemRights] - "RegistryRights" = [System.Security.AccessControl.RegistryRights] - "ActiveDirectoryRights" = [System.DirectoryServices.ActiveDirectoryRights] - "MutexRights" = [System.Security.AccessControl.MutexRights] - "SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights] - "CryptoKeyRights" = [System.Security.AccessControl.CryptoKeyRights] - "EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights] - } - } - $typesToExamine = $rightTypes.Values - - ## If they know the access mask represents a certain type, prefer its names - ## (i.e.: CreateLink for the registry over CreateDirectories for the filesystem) - if($Type) - { - $typesToExamine = @($rightTypes[$Type]) + $typesToExamine - } - - - ## Stores the access types we've found that apply - $foundAccess = @() - - ## Store the access types we've already seen, so that we don't report access - ## flags that are essentially duplicate. Many of the access values in the different - ## enumerations have the same value but with different names. - $foundValues = @{} - - ## Go through the entries in the different right types, and see if they apply to the - ## provided access mask. If they do, then add that to the result. - foreach($rightType in $typesToExamine) - { - foreach($accessFlag in [Enum]::GetNames($rightType)) - { - $longKeyValue = [long] $rightType::$accessFlag - if(-not $foundValues.ContainsKey($longKeyValue)) - { - $foundValues[$longKeyValue] = $true - if(($AccessMask -band $longKeyValue) -eq ($longKeyValue)) - { - $foundAccess += $accessFlag - } - } - } - } - - $foundAccess | Sort-Object - } - - ## Converts an ACE into a string representation - function ConvertTo-AceString - { - param( - [Parameter(ValueFromPipeline)] - $Ace, - $Type - ) - - process - { - foreach($aceEntry in $Ace) - { - $AceString = (ConvertTo-NtAccount $aceEntry.SecurityIdentifier) + ": " + $aceEntry.AceQualifier - if($aceEntry.AceFlags -ne "None") - { - $AceString += " " + $aceEntry.AceFlags - } - - if($aceEntry.AccessMask) - { - $foundAccess = Get-AccessRights $aceEntry.AccessMask $Type - - if($foundAccess) - { - $AceString += " ({0})" -f ($foundAccess -join ", ") - } - } - - $AceString - } - } - } - } - - Process - { - $rawSecurityDescriptor = [Security.AccessControl.CommonSecurityDescriptor]::new($false,$false,$Sddl) - - $owner = ConvertTo-NtAccount $rawSecurityDescriptor.Owner - $group = ConvertTo-NtAccount $rawSecurityDescriptor.Group - $discretionaryAcl = ConvertTo-AceString $rawSecurityDescriptor.DiscretionaryAcl $Type - $systemAcl = ConvertTo-AceString $rawSecurityDescriptor.SystemAcl $Type - - [PSCustomObject] @{ - Owner = $owner - Group = $group - DiscretionaryAcl = @($discretionaryAcl) - SystemAcl = @($systemAcl) - RawDescriptor = $rawSecurityDescriptor - } - } -} + +## Converts a SDDL string into an object-based representation of a security +## descriptor +function ConvertFrom-SddlString +{ + [CmdletBinding(HelpUri = "https://go.microsoft.com/fwlink/?LinkId=623636")] + param( + ## The string representing the security descriptor in SDDL syntax + [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] + [String] $Sddl, + + ## The type of rights that this SDDL string represents, if any. + [Parameter()] + [ValidateSet( + "FileSystemRights", "RegistryRights", "ActiveDirectoryRights", + "MutexRights", "SemaphoreRights", "CryptoKeyRights", + "EventWaitHandleRights")] + $Type + ) + + Begin + { + # On CoreCLR CryptoKeyRights and ActiveDirectoryRights are not supported. + if ($PSEdition -eq "Core" -and ($Type -eq "CryptoKeyRights" -or $Type -eq "ActiveDirectoryRights")) + { + $errorId = "TypeNotSupported" + $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument + $errorMessage = [Microsoft.PowerShell.Commands.UtilityResources]::TypeNotSupported -f $Type + $exception = [System.ArgumentException]::New($errorMessage) + $errorRecord = [System.Management.Automation.ErrorRecord]::New($exception, $errorId, $errorCategory, $null) + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + ## Translates a SID into a NT Account + function ConvertTo-NtAccount + { + param($Sid) + + if($Sid) + { + $securityIdentifier = [System.Security.Principal.SecurityIdentifier] $Sid + + try + { + $ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount]).ToString() + } + catch{} + + $ntAccount + } + } + + ## Gets the access rights that apply to an access mask, preferring right types + ## of 'Type' if specified. + function Get-AccessRights + { + param($AccessMask, $Type) + + if ($PSEdition -eq "Core") + { + ## All the types of access rights understood by .NET Core + $rightTypes = [Ordered] @{ + "FileSystemRights" = [System.Security.AccessControl.FileSystemRights] + "RegistryRights" = [System.Security.AccessControl.RegistryRights] + "MutexRights" = [System.Security.AccessControl.MutexRights] + "SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights] + "EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights] + } + } + else + { + ## All the types of access rights understood by .NET + $rightTypes = [Ordered] @{ + "FileSystemRights" = [System.Security.AccessControl.FileSystemRights] + "RegistryRights" = [System.Security.AccessControl.RegistryRights] + "ActiveDirectoryRights" = [System.DirectoryServices.ActiveDirectoryRights] + "MutexRights" = [System.Security.AccessControl.MutexRights] + "SemaphoreRights" = [System.Security.AccessControl.SemaphoreRights] + "CryptoKeyRights" = [System.Security.AccessControl.CryptoKeyRights] + "EventWaitHandleRights" = [System.Security.AccessControl.EventWaitHandleRights] + } + } + $typesToExamine = $rightTypes.Values + + ## If they know the access mask represents a certain type, prefer its names + ## (i.e.: CreateLink for the registry over CreateDirectories for the filesystem) + if($Type) + { + $typesToExamine = @($rightTypes[$Type]) + $typesToExamine + } + + + ## Stores the access types we've found that apply + $foundAccess = @() + + ## Store the access types we've already seen, so that we don't report access + ## flags that are essentially duplicate. Many of the access values in the different + ## enumerations have the same value but with different names. + $foundValues = @{} + + ## Go through the entries in the different right types, and see if they apply to the + ## provided access mask. If they do, then add that to the result. + foreach($rightType in $typesToExamine) + { + foreach($accessFlag in [Enum]::GetNames($rightType)) + { + $longKeyValue = [long] $rightType::$accessFlag + if(-not $foundValues.ContainsKey($longKeyValue)) + { + $foundValues[$longKeyValue] = $true + if(($AccessMask -band $longKeyValue) -eq ($longKeyValue)) + { + $foundAccess += $accessFlag + } + } + } + } + + $foundAccess | Sort-Object + } + + ## Converts an ACE into a string representation + function ConvertTo-AceString + { + param( + [Parameter(ValueFromPipeline)] + $Ace, + $Type + ) + + process + { + foreach($aceEntry in $Ace) + { + $AceString = (ConvertTo-NtAccount $aceEntry.SecurityIdentifier) + ": " + $aceEntry.AceQualifier + if($aceEntry.AceFlags -ne "None") + { + $AceString += " " + $aceEntry.AceFlags + } + + if($aceEntry.AccessMask) + { + $foundAccess = Get-AccessRights $aceEntry.AccessMask $Type + + if($foundAccess) + { + $AceString += " ({0})" -f ($foundAccess -join ", ") + } + } + + $AceString + } + } + } + } + + Process + { + $rawSecurityDescriptor = [Security.AccessControl.CommonSecurityDescriptor]::new($false,$false,$Sddl) + + $owner = ConvertTo-NtAccount $rawSecurityDescriptor.Owner + $group = ConvertTo-NtAccount $rawSecurityDescriptor.Group + $discretionaryAcl = ConvertTo-AceString $rawSecurityDescriptor.DiscretionaryAcl $Type + $systemAcl = ConvertTo-AceString $rawSecurityDescriptor.SystemAcl $Type + + [PSCustomObject] @{ + Owner = $owner + Group = $group + DiscretionaryAcl = @($discretionaryAcl) + SystemAcl = @($systemAcl) + RawDescriptor = $rawSecurityDescriptor + } + } +} diff --git a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 1add1c7038d..fdc7173d35b 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -1,30 +1,30 @@ -@{ -GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" -Author="Microsoft Corporation" -CompanyName="Microsoft Corporation" -Copyright="© Microsoft Corporation. All rights reserved." -ModuleVersion="3.1.0.0" -PowerShellVersion="3.0" -CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", - "Out-File", "Out-String", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", - "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", - "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", - "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", - "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", - "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", - "Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData", - "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", - "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", - "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug", - "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", - "Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", - "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash", - "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", - "Get-RunspaceDebug", "Wait-Debugger" , "Get-Uptime", "New-TemporaryFile", "Get-Verb", "Format-Hex" -FunctionsToExport= "Import-PowerShellDataFile" -AliasesToExport= "fhx" -NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' -} +@{ +GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" +Author="Microsoft Corporation" +CompanyName="Microsoft Corporation" +Copyright="© Microsoft Corporation. All rights reserved." +ModuleVersion="3.1.0.0" +PowerShellVersion="3.0" +CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", + "Out-File", "Out-String", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", + "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", + "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", + "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", + "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", + "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", + "Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData", + "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", + "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", + "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug", + "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", + "Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", + "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash", + "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", + "Get-RunspaceDebug", "Wait-Debugger" , "Get-Uptime", "New-TemporaryFile", "Get-Verb", "Format-Hex" +FunctionsToExport= "Import-PowerShellDataFile" +AliasesToExport= "fhx" +NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" +HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' +} diff --git a/src/Modules/Windows-Core+Full/CimCmdlets/CimCmdlets.psd1 b/src/Modules/Windows-Core+Full/CimCmdlets/CimCmdlets.psd1 index 294de972f5c..16c79204763 100644 --- a/src/Modules/Windows-Core+Full/CimCmdlets/CimCmdlets.psd1 +++ b/src/Modules/Windows-Core+Full/CimCmdlets/CimCmdlets.psd1 @@ -1,18 +1,18 @@ -@{ -GUID="{Fb6cc51d-c096-4b38-b78d-0fed6277096a}" -Author="Microsoft Corporation" -CompanyName="Microsoft Corporation" -Copyright="© Microsoft Corporation. All rights reserved." -ModuleVersion="1.0.0.0" -PowerShellVersion="3.0" -CLRVersion="4.0" -RootModule="Microsoft.Management.Infrastructure.CimCmdlets" -RequiredAssemblies="Microsoft.Management.Infrastructure.CimCmdlets.dll","Microsoft.Management.Infrastructure.Dll" -CmdletsToExport= "Get-CimAssociatedInstance", "Get-CimClass", "Get-CimInstance", "Get-CimSession", "Invoke-CimMethod", - "New-CimInstance","New-CimSession","New-CimSessionOption","Register-CimIndicationEvent","Remove-CimInstance", - "Remove-CimSession","Set-CimInstance", - "Export-BinaryMiLog","Import-BinaryMiLog" -AliasesToExport = "gcim","scim","ncim", "rcim","icim","gcai","rcie","ncms","rcms","gcms","ncso","gcls" -FunctionsToExport = @() -HelpInfoUri="https://go.microsoft.com/fwlink/?linkid=390758" -} +@{ +GUID="{Fb6cc51d-c096-4b38-b78d-0fed6277096a}" +Author="Microsoft Corporation" +CompanyName="Microsoft Corporation" +Copyright="© Microsoft Corporation. All rights reserved." +ModuleVersion="1.0.0.0" +PowerShellVersion="3.0" +CLRVersion="4.0" +RootModule="Microsoft.Management.Infrastructure.CimCmdlets" +RequiredAssemblies="Microsoft.Management.Infrastructure.CimCmdlets.dll","Microsoft.Management.Infrastructure.Dll" +CmdletsToExport= "Get-CimAssociatedInstance", "Get-CimClass", "Get-CimInstance", "Get-CimSession", "Invoke-CimMethod", + "New-CimInstance","New-CimSession","New-CimSessionOption","Register-CimIndicationEvent","Remove-CimInstance", + "Remove-CimSession","Set-CimInstance", + "Export-BinaryMiLog","Import-BinaryMiLog" +AliasesToExport = "gcim","scim","ncim", "rcim","icim","gcai","rcie","ncms","rcms","gcms","ncso","gcls" +FunctionsToExport = @() +HelpInfoUri="https://go.microsoft.com/fwlink/?linkid=390758" +} diff --git a/src/Modules/Windows-Core+Full/Microsoft.WSMan.Management/WSMan.format.ps1xml b/src/Modules/Windows-Core+Full/Microsoft.WSMan.Management/WSMan.format.ps1xml index a7bdea98469..c770f0e9769 100644 --- a/src/Modules/Windows-Core+Full/Microsoft.WSMan.Management/WSMan.format.ps1xml +++ b/src/Modules/Windows-Core+Full/Microsoft.WSMan.Management/WSMan.format.ps1xml @@ -1,236 +1,236 @@ - - - - - - - System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse - - System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse - - - - - - - wsmid - - - ProtocolVersion - - - ProductVendor - - - ProductVersion - - - - - - - - Microsoft.WSMan.Management.WSManConfigElement - - Microsoft.WSMan.Management.WSManConfigElement - - - PSParentPath - - - - - - - 15 - - - - 30 - - - - - - - TypeNameOfElement - - - Name - - - - - - - - Microsoft.WSMan.Management.WSManConfigContainerElement - - Microsoft.WSMan.Management.WSManConfigContainerElement - - - PSParentPath - - - - - - - 15 - - - - 35 - - - - - - - - - - TypeNameOfElement - - - Keys - - - Name - - - - - - - - Microsoft.WSMan.Management.WSManConfigLeafElement - - Microsoft.WSMan.Management.WSManConfigLeafElement - - - PSParentPath - - - - - - - 15 - - - - 30 - - - - 15 - - - - - - - - - - TypeNameOfElement - - - Name - - - SourceOfValue - - - Value - - - - - - - - Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams - - Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams - - - PSParentPath - - - - - - - 30 - - - - 20 - - - - - - - Name - - - Value - - - - - - - - Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel - - Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel - - - PSParentPath - - - - - - - 45 - - - - 20 - - - - - - - Name - - - TypeNameOfElement - - - - - - - - + + + + + + + System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse + + System.Xml.XmlElement#http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd#IdentifyResponse + + + + + + + wsmid + + + ProtocolVersion + + + ProductVendor + + + ProductVersion + + + + + + + + Microsoft.WSMan.Management.WSManConfigElement + + Microsoft.WSMan.Management.WSManConfigElement + + + PSParentPath + + + + + + + 15 + + + + 30 + + + + + + + TypeNameOfElement + + + Name + + + + + + + + Microsoft.WSMan.Management.WSManConfigContainerElement + + Microsoft.WSMan.Management.WSManConfigContainerElement + + + PSParentPath + + + + + + + 15 + + + + 35 + + + + + + + + + + TypeNameOfElement + + + Keys + + + Name + + + + + + + + Microsoft.WSMan.Management.WSManConfigLeafElement + + Microsoft.WSMan.Management.WSManConfigLeafElement + + + PSParentPath + + + + + + + 15 + + + + 30 + + + + 15 + + + + + + + + + + TypeNameOfElement + + + Name + + + SourceOfValue + + + Value + + + + + + + + Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams + + Microsoft.WSMan.Management.WSManConfigLeafElement#InitParams + + + PSParentPath + + + + + + + 30 + + + + 20 + + + + + + + Name + + + Value + + + + + + + + Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel + + Microsoft.WSMan.Management.WSManConfigContainerElement#ComputerLevel + + + PSParentPath + + + + + + + 45 + + + + 20 + + + + + + + Name + + + TypeNameOfElement + + + + + + + + diff --git a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psd1 b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psd1 index 4533f0991b2..44b9e292940 100644 --- a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psd1 +++ b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psd1 @@ -1,13 +1,13 @@ -@{ - GUID="c61d6278-02a3-4618-ae37-a524d40a7f44 " - Author="Microsoft Corporation" - CompanyName="Microsoft Corporation" - Copyright="© Microsoft Corporation. All rights reserved." - ModuleVersion="1.0.0.0" - PowerShellVersion="2.0" - CLRVersion="2.0.50727" - ModuleToProcess="PSDiagnostics.psm1" - AliasesToExport = @() - CmdletsToExport = @() - FunctionsToExport="Disable-PSTrace","Disable-PSWSManCombinedTrace","Disable-WSManTrace","Enable-PSTrace","Enable-PSWSManCombinedTrace","Enable-WSManTrace","Get-LogProperties","Set-LogProperties","Start-Trace","Stop-Trace" -} +@{ + GUID="c61d6278-02a3-4618-ae37-a524d40a7f44 " + Author="Microsoft Corporation" + CompanyName="Microsoft Corporation" + Copyright="© Microsoft Corporation. All rights reserved." + ModuleVersion="1.0.0.0" + PowerShellVersion="2.0" + CLRVersion="2.0.50727" + ModuleToProcess="PSDiagnostics.psm1" + AliasesToExport = @() + CmdletsToExport = @() + FunctionsToExport="Disable-PSTrace","Disable-PSWSManCombinedTrace","Disable-WSManTrace","Enable-PSTrace","Enable-PSWSManCombinedTrace","Enable-WSManTrace","Get-LogProperties","Set-LogProperties","Start-Trace","Stop-Trace" +} diff --git a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 index f662c25179a..524f2ccb73e 100644 --- a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 +++ b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 @@ -1,446 +1,446 @@ -<# - Windows PowerShell Diagnostics Module - This module contains a set of wrapper scripts that - enable a user to use ETW tracing in Windows - PowerShell. - #> - -$script:Logman="$env:windir\system32\logman.exe" -$script:wsmanlogfile = "$env:windir\system32\wsmtraces.log" -$script:wsmprovfile = "$env:windir\system32\wsmtraceproviders.txt" -$script:wsmsession = "wsmlog" -$script:pssession = "PSTrace" -$script:psprovidername="Microsoft-Windows-PowerShell" -$script:wsmprovidername = "Microsoft-Windows-WinRM" -$script:oplog = "/Operational" -$script:analyticlog="/Analytic" -$script:debuglog="/Debug" -$script:wevtutil="$env:windir\system32\wevtutil.exe" -$script:slparam = "sl" -$script:glparam = "gl" - -function Start-Trace -{ - Param( - [Parameter(Mandatory=$true, - Position=0)] - [string] - $SessionName, - [Parameter(Position=1)] - [ValidateNotNullOrEmpty()] - [string] - $OutputFilePath, - [Parameter(Position=2)] - [ValidateNotNullOrEmpty()] - [string] - $ProviderFilePath, - [Parameter()] - [Switch] - $ETS, - [Parameter()] - [ValidateSet("bin", "bincirc", "csv", "tsv", "sql")] - $Format, - [Parameter()] - [int] - $MinBuffers=0, - [Parameter()] - [int] - $MaxBuffers=256, - [Parameter()] - [int] - $BufferSizeInKB = 0, - [Parameter()] - [int] - $MaxLogFileSizeInMB=0 - ) - - Process - { - $executestring = " start $SessionName" - - if ($ETS) - { - $executestring += " -ets" - } - - if ($null -ne $OutputFilePath) - { - $executestring += " -o ""$OutputFilePath""" - } - - if ($null -ne $ProviderFilePath) - { - $executestring += " -pf ""$ProviderFilePath""" - } - - if ($null -ne $Format) - { - $executestring += " -f $Format" - } - - if ($MinBuffers -ne 0 -or $MaxBuffers -ne 256) - { - $executestring += " -nb $MinBuffers $MaxBuffers" - } - - if ($BufferSizeInKB -ne 0) - { - $executestring += " -bs $BufferSizeInKB" - } - - if ($MaxLogFileSizeInMB -ne 0) - { - $executestring += " -max $MaxLogFileSizeInMB" - } - - & $script:Logman $executestring.Split(" ") - } -} - -function Stop-Trace -{ - param( - [Parameter(Mandatory=$true, - Position=0)] - $SessionName, - [Parameter()] - [switch] - $ETS - ) - - Process - { - if ($ETS) - { - & $script:Logman update $SessionName -ets - & $script:Logman stop $SessionName -ets - } - else - { - & $script:Logman update $SessionName - & $script:Logman stop $SessionName - } - } -} - -function Enable-WSManTrace -{ - - # winrm - "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii - - # winrsmgr - "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - # WinrsExe - "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - # WinrsCmd - "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - # IPMIPrv - "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - #IpmiDrv - "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - # WSManProvHost - "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - # Event Forwarding - "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append - - Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKb 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile -} - -function Disable-WSManTrace -{ - Stop-Trace $script:wsmsession -ets -} - -function Enable-PSWSManCombinedTrace -{ - param ( - [switch] $DoNotOverwriteExistingTrace - ) - - $provfile = [io.path]::GetTempFilename() - - $traceFileName = [string][Guid]::NewGuid() - if ($DoNotOverwriteExistingTrace) { - $fileName = [string][guid]::newguid() - $logfile = $pshome + "\\Traces\\PSTrace_$fileName.etl" - } else { - $logfile = $pshome + "\\Traces\\PSTrace.etl" - } - - "Microsoft-Windows-PowerShell 0 5" | out-file $provfile -encoding ascii - "Microsoft-Windows-WinRM 0 5" | out-file $provfile -encoding ascii -append - - if (!(Test-Path $pshome\Traces)) - { - mkdir -Force $pshome\Traces | out-null - } - - if (Test-Path $logfile) - { - Remove-Item -Force $logfile | out-null - } - - Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ets - - remove-item $provfile -Force -ea 0 -} - -function Disable-PSWSManCombinedTrace -{ - Stop-Trace -SessionName $script:pssession -ets -} - -function Set-LogProperties -{ - param( - [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] - [Microsoft.PowerShell.Diagnostics.LogDetails] - $LogDetails, - [switch] $Force - ) - - Process - { - if ($LogDetails.AutoBackup -and !$LogDetails.Retention) - { - throw (New-Object System.InvalidOperationException) - } - - $enabled = $LogDetails.Enabled.ToString() - $retention = $LogDetails.Retention.ToString() - $autobackup = $LogDetails.AutoBackup.ToString() - $maxLogSize = $LogDetails.MaxLogSize.ToString() - $osVersion = [Version] (Get-Ciminstance Win32_OperatingSystem).Version - - if (($LogDetails.Type -eq "Analytic") -or ($LogDetails.Type -eq "Debug")) - { - if ($LogDetails.Enabled) - { - if($osVersion -lt 6.3.7600) - { - & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled - } - else - { - & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled - } - } - else - { - if($osVersion -lt 6.3.7600) - { - & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize - } - else - { - & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize - } - } - } - else - { - if($osVersion -lt 6.3.7600) - { - & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize - } - else - { - & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize - } - } - } -} - -function ConvertTo-Bool([string]$value) -{ - if ($value -ieq "true") - { - return $true - } - else - { - return $false - } -} - -function Get-LogProperties -{ - param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] $Name - ) - - Process - { - $details = & $script:wevtutil $script:glparam $Name - $indexes = @(1,2,8,9,10) - $value = @() - foreach($index in $indexes) - { - $value += @(($details[$index].SubString($details[$index].IndexOf(":")+1)).Trim()) - } - - $enabled = ConvertTo-Bool $value[0] - $retention = ConvertTo-Bool $value[2] - $autobackup = ConvertTo-Bool $value[3] - - New-Object Microsoft.PowerShell.Diagnostics.LogDetails $Name, $enabled, $value[1], $retention, $autobackup, $value[4] - } -} - -function Enable-PSTrace -{ - param( - [switch] $Force, - [switch] $AnalyticOnly - ) - - $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) - - if (!$Properties.Enabled) { - $Properties.Enabled = $true - if ($Force) { - Set-LogProperties $Properties -Force - } else { - Set-LogProperties $Properties - } - } - - if (!$AnalyticOnly) { - $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) - if (!$Properties.Enabled) { - $Properties.Enabled = $true - if ($Force) { - Set-LogProperties $Properties -Force - } else { - Set-LogProperties $Properties - } - } - } -} - -function Disable-PSTrace -{ - param( - [switch] $AnalyticOnly - ) - $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) - if ($Properties.Enabled) { - $Properties.Enabled = $false - Set-LogProperties $Properties - } - - if (!$AnalyticOnly) { - $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) - if ($Properties.Enabled) { - $Properties.Enabled = $false - Set-LogProperties $Properties - } - } -} -add-type @" -using System; - -namespace Microsoft.PowerShell.Diagnostics -{ - public class LogDetails - { - public string Name - { - get - { - return name; - } - } - private string name; - - public bool Enabled - { - get - { - return enabled; - } - set - { - enabled = value; - } - } - private bool enabled; - - public string Type - { - get - { - return type; - } - } - private string type; - - public bool Retention - { - get - { - return retention; - } - set - { - retention = value; - } - } - private bool retention; - - public bool AutoBackup - { - get - { - return autoBackup; - } - set - { - autoBackup = value; - } - } - private bool autoBackup; - - public int MaxLogSize - { - get - { - return maxLogSize; - } - set - { - maxLogSize = value; - } - } - private int maxLogSize; - - public LogDetails(string name, bool enabled, string type, bool retention, bool autoBackup, int maxLogSize) - { - this.name = name; - this.enabled = enabled; - this.type = type; - this.retention = retention; - this.autoBackup = autoBackup; - this.maxLogSize = maxLogSize; - } - } -} -"@ - - -if ($psedition -eq 'Core') - { - # Currently we only support these cmdlets as logman.exe is not working on Nano/Lot system. - Export-ModuleMember Enable-PSTrace, Disable-PSTrace, Get-LogProperties, Set-LogProperties - } - else - { - Export-ModuleMember Start-Trace, Stop-Trace, Enable-WSManTrace, Disable-WSManTrace, Enable-PSTrace, Disable-PSTrace, Enable-PSWSManCombinedTrace, Disable-PSWSManCombinedTrace, Get-LogProperties, Set-LogProperties - } +<# + Windows PowerShell Diagnostics Module + This module contains a set of wrapper scripts that + enable a user to use ETW tracing in Windows + PowerShell. + #> + +$script:Logman="$env:windir\system32\logman.exe" +$script:wsmanlogfile = "$env:windir\system32\wsmtraces.log" +$script:wsmprovfile = "$env:windir\system32\wsmtraceproviders.txt" +$script:wsmsession = "wsmlog" +$script:pssession = "PSTrace" +$script:psprovidername="Microsoft-Windows-PowerShell" +$script:wsmprovidername = "Microsoft-Windows-WinRM" +$script:oplog = "/Operational" +$script:analyticlog="/Analytic" +$script:debuglog="/Debug" +$script:wevtutil="$env:windir\system32\wevtutil.exe" +$script:slparam = "sl" +$script:glparam = "gl" + +function Start-Trace +{ + Param( + [Parameter(Mandatory=$true, + Position=0)] + [string] + $SessionName, + [Parameter(Position=1)] + [ValidateNotNullOrEmpty()] + [string] + $OutputFilePath, + [Parameter(Position=2)] + [ValidateNotNullOrEmpty()] + [string] + $ProviderFilePath, + [Parameter()] + [Switch] + $ETS, + [Parameter()] + [ValidateSet("bin", "bincirc", "csv", "tsv", "sql")] + $Format, + [Parameter()] + [int] + $MinBuffers=0, + [Parameter()] + [int] + $MaxBuffers=256, + [Parameter()] + [int] + $BufferSizeInKB = 0, + [Parameter()] + [int] + $MaxLogFileSizeInMB=0 + ) + + Process + { + $executestring = " start $SessionName" + + if ($ETS) + { + $executestring += " -ets" + } + + if ($null -ne $OutputFilePath) + { + $executestring += " -o ""$OutputFilePath""" + } + + if ($null -ne $ProviderFilePath) + { + $executestring += " -pf ""$ProviderFilePath""" + } + + if ($null -ne $Format) + { + $executestring += " -f $Format" + } + + if ($MinBuffers -ne 0 -or $MaxBuffers -ne 256) + { + $executestring += " -nb $MinBuffers $MaxBuffers" + } + + if ($BufferSizeInKB -ne 0) + { + $executestring += " -bs $BufferSizeInKB" + } + + if ($MaxLogFileSizeInMB -ne 0) + { + $executestring += " -max $MaxLogFileSizeInMB" + } + + & $script:Logman $executestring.Split(" ") + } +} + +function Stop-Trace +{ + param( + [Parameter(Mandatory=$true, + Position=0)] + $SessionName, + [Parameter()] + [switch] + $ETS + ) + + Process + { + if ($ETS) + { + & $script:Logman update $SessionName -ets + & $script:Logman stop $SessionName -ets + } + else + { + & $script:Logman update $SessionName + & $script:Logman stop $SessionName + } + } +} + +function Enable-WSManTrace +{ + + # winrm + "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii + + # winrsmgr + "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + # WinrsExe + "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + # WinrsCmd + "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + # IPMIPrv + "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + #IpmiDrv + "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + # WSManProvHost + "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + # Event Forwarding + "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + + Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKb 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile +} + +function Disable-WSManTrace +{ + Stop-Trace $script:wsmsession -ets +} + +function Enable-PSWSManCombinedTrace +{ + param ( + [switch] $DoNotOverwriteExistingTrace + ) + + $provfile = [io.path]::GetTempFilename() + + $traceFileName = [string][Guid]::NewGuid() + if ($DoNotOverwriteExistingTrace) { + $fileName = [string][guid]::newguid() + $logfile = $pshome + "\\Traces\\PSTrace_$fileName.etl" + } else { + $logfile = $pshome + "\\Traces\\PSTrace.etl" + } + + "Microsoft-Windows-PowerShell 0 5" | out-file $provfile -encoding ascii + "Microsoft-Windows-WinRM 0 5" | out-file $provfile -encoding ascii -append + + if (!(Test-Path $pshome\Traces)) + { + mkdir -Force $pshome\Traces | out-null + } + + if (Test-Path $logfile) + { + Remove-Item -Force $logfile | out-null + } + + Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ets + + remove-item $provfile -Force -ea 0 +} + +function Disable-PSWSManCombinedTrace +{ + Stop-Trace -SessionName $script:pssession -ets +} + +function Set-LogProperties +{ + param( + [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] + [Microsoft.PowerShell.Diagnostics.LogDetails] + $LogDetails, + [switch] $Force + ) + + Process + { + if ($LogDetails.AutoBackup -and !$LogDetails.Retention) + { + throw (New-Object System.InvalidOperationException) + } + + $enabled = $LogDetails.Enabled.ToString() + $retention = $LogDetails.Retention.ToString() + $autobackup = $LogDetails.AutoBackup.ToString() + $maxLogSize = $LogDetails.MaxLogSize.ToString() + $osVersion = [Version] (Get-Ciminstance Win32_OperatingSystem).Version + + if (($LogDetails.Type -eq "Analytic") -or ($LogDetails.Type -eq "Debug")) + { + if ($LogDetails.Enabled) + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled + } + } + else + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize + } + } + } + else + { + if($osVersion -lt 6.3.7600) + { + & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize + } + else + { + & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize + } + } + } +} + +function ConvertTo-Bool([string]$value) +{ + if ($value -ieq "true") + { + return $true + } + else + { + return $false + } +} + +function Get-LogProperties +{ + param( + [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] $Name + ) + + Process + { + $details = & $script:wevtutil $script:glparam $Name + $indexes = @(1,2,8,9,10) + $value = @() + foreach($index in $indexes) + { + $value += @(($details[$index].SubString($details[$index].IndexOf(":")+1)).Trim()) + } + + $enabled = ConvertTo-Bool $value[0] + $retention = ConvertTo-Bool $value[2] + $autobackup = ConvertTo-Bool $value[3] + + New-Object Microsoft.PowerShell.Diagnostics.LogDetails $Name, $enabled, $value[1], $retention, $autobackup, $value[4] + } +} + +function Enable-PSTrace +{ + param( + [switch] $Force, + [switch] $AnalyticOnly + ) + + $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) + + if (!$Properties.Enabled) { + $Properties.Enabled = $true + if ($Force) { + Set-LogProperties $Properties -Force + } else { + Set-LogProperties $Properties + } + } + + if (!$AnalyticOnly) { + $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) + if (!$Properties.Enabled) { + $Properties.Enabled = $true + if ($Force) { + Set-LogProperties $Properties -Force + } else { + Set-LogProperties $Properties + } + } + } +} + +function Disable-PSTrace +{ + param( + [switch] $AnalyticOnly + ) + $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog) + if ($Properties.Enabled) { + $Properties.Enabled = $false + Set-LogProperties $Properties + } + + if (!$AnalyticOnly) { + $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog) + if ($Properties.Enabled) { + $Properties.Enabled = $false + Set-LogProperties $Properties + } + } +} +add-type @" +using System; + +namespace Microsoft.PowerShell.Diagnostics +{ + public class LogDetails + { + public string Name + { + get + { + return name; + } + } + private string name; + + public bool Enabled + { + get + { + return enabled; + } + set + { + enabled = value; + } + } + private bool enabled; + + public string Type + { + get + { + return type; + } + } + private string type; + + public bool Retention + { + get + { + return retention; + } + set + { + retention = value; + } + } + private bool retention; + + public bool AutoBackup + { + get + { + return autoBackup; + } + set + { + autoBackup = value; + } + } + private bool autoBackup; + + public int MaxLogSize + { + get + { + return maxLogSize; + } + set + { + maxLogSize = value; + } + } + private int maxLogSize; + + public LogDetails(string name, bool enabled, string type, bool retention, bool autoBackup, int maxLogSize) + { + this.name = name; + this.enabled = enabled; + this.type = type; + this.retention = retention; + this.autoBackup = autoBackup; + this.maxLogSize = maxLogSize; + } + } +} +"@ + + +if ($psedition -eq 'Core') + { + # Currently we only support these cmdlets as logman.exe is not working on Nano/Lot system. + Export-ModuleMember Enable-PSTrace, Disable-PSTrace, Get-LogProperties, Set-LogProperties + } + else + { + Export-ModuleMember Start-Trace, Stop-Trace, Enable-WSManTrace, Disable-WSManTrace, Enable-PSTrace, Disable-PSTrace, Enable-PSWSManCombinedTrace, Disable-PSWSManCombinedTrace, Get-LogProperties, Set-LogProperties + } diff --git a/src/Modules/Windows-Core/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 b/src/Modules/Windows-Core/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 index daaea553726..8dc0d9cada6 100644 --- a/src/Modules/Windows-Core/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 +++ b/src/Modules/Windows-Core/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 @@ -1,13 +1,13 @@ -@{ -GUID="CA046F10-CA64-4740-8FF9-2565DBA61A4F" -Author="Microsoft Corporation" -CompanyName="Microsoft Corporation" -Copyright="© Microsoft Corporation. All rights reserved." -ModuleVersion="3.0.0.0" -PowerShellVersion="3.0" -CmdletsToExport="Get-WinEvent", "New-WinEvent" # Counter CmdLets Disabled #4272: "Get-Counter", "Import-Counter", "Export-Counter" -NestedModules="Microsoft.PowerShell.Commands.Diagnostics.dll" -TypesToProcess="GetEvent.types.ps1xml" -FormatsToProcess="Event.format.ps1xml", "Diagnostics.format.ps1xml" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390783' -} +@{ +GUID="CA046F10-CA64-4740-8FF9-2565DBA61A4F" +Author="Microsoft Corporation" +CompanyName="Microsoft Corporation" +Copyright="© Microsoft Corporation. All rights reserved." +ModuleVersion="3.0.0.0" +PowerShellVersion="3.0" +CmdletsToExport="Get-WinEvent", "New-WinEvent" # Counter CmdLets Disabled #4272: "Get-Counter", "Import-Counter", "Export-Counter" +NestedModules="Microsoft.PowerShell.Commands.Diagnostics.dll" +TypesToProcess="GetEvent.types.ps1xml" +FormatsToProcess="Event.format.ps1xml", "Diagnostics.format.ps1xml" +HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390783' +} diff --git a/src/Modules/Windows-Core/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows-Core/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 1fc9d4e1ad3..7c7b3d302c8 100644 --- a/src/Modules/Windows-Core/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows-Core/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -1,30 +1,30 @@ -@{ -GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" -Author="Microsoft Corporation" -CompanyName="Microsoft Corporation" -Copyright="© Microsoft Corporation. All rights reserved." -ModuleVersion="3.1.0.0" -PowerShellVersion="3.0" -CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", - "Out-File", "Out-String", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", - "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", - "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", - "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", - "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", - "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", - "Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData", - "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", - "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", - "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile","ConvertTo-Xml", "Select-Xml", "Write-Debug", - "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", - "Get-PSBreakpoint", "Remove-PSBreakpoint", "New-TemporaryFile", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", - "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash", - "Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", - "Get-RunspaceDebug", "Wait-Debugger" , "Get-Uptime", "Get-Verb", "Format-Hex" -FunctionsToExport= "ConvertFrom-SddlString" -AliasesToExport= "fhx" -NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' -} +@{ +GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" +Author="Microsoft Corporation" +CompanyName="Microsoft Corporation" +Copyright="© Microsoft Corporation. All rights reserved." +ModuleVersion="3.1.0.0" +PowerShellVersion="3.0" +CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", + "Out-File", "Out-String", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", + "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", + "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", + "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", + "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", + "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", + "Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData", + "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", + "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", + "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile","ConvertTo-Xml", "Select-Xml", "Write-Debug", + "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", + "Get-PSBreakpoint", "Remove-PSBreakpoint", "New-TemporaryFile", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", + "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash", + "Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", + "Get-RunspaceDebug", "Wait-Debugger" , "Get-Uptime", "Get-Verb", "Format-Hex" +FunctionsToExport= "ConvertFrom-SddlString" +AliasesToExport= "fhx" +NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" +HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' +} diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml index a290c620ce5..8e0c106f7dd 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml @@ -1,79 +1,79 @@ - - - - - - - - Counter - - Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet - - - - - - 25 - left - - - - left - 100 - - - - - - - - Timestamp - - - Readings - - - - - - - - Counter - - Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo - - - - - 30 - left - - - 30 - left - - - 30 - left - - - - - - - - OldestRecord - - - NewestRecord - - - SampleCount - - - - - - - - + + + + + + + + Counter + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + + + + 25 + left + + + + left + 100 + + + + + + + + Timestamp + + + Readings + + + + + + + + Counter + + Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo + + + + + 30 + left + + + 30 + left + + + 30 + left + + + + + + + + OldestRecord + + + NewestRecord + + + SampleCount + + + + + + + + diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml index 476af9f5e2d..3d105bc7c31 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml @@ -1,121 +1,121 @@ - - - - - Default - - System.Diagnostics.Eventing.Reader.EventLogRecord - - - ProviderName - - - - - - 25 - - - 8 - right - - - 16 - - - - - - - - - TimeCreated - - - Id - - - LevelDisplayName - - - Message - - - - - - - - - Default - - System.Diagnostics.Eventing.Reader.EventLogConfiguration - - - - - - - 9 - - - - 18 - right - - - - 11 - right - - - - - - - - LogMode - - - MaximumSizeInBytes - - - RecordCount - - - LogName - - - - - - - - Default - - System.Diagnostics.Eventing.Reader.ProviderMetadata - - - - - - - Name - - - LogLinks - - - Opcodes - - - Tasks - - - - - - - - - + + + + + Default + + System.Diagnostics.Eventing.Reader.EventLogRecord + + + ProviderName + + + + + + 25 + + + 8 + right + + + 16 + + + + + + + + + TimeCreated + + + Id + + + LevelDisplayName + + + Message + + + + + + + + + Default + + System.Diagnostics.Eventing.Reader.EventLogConfiguration + + + + + + + 9 + + + + 18 + right + + + + 11 + right + + + + + + + + LogMode + + + MaximumSizeInBytes + + + RecordCount + + + LogName + + + + + + + + Default + + System.Diagnostics.Eventing.Reader.ProviderMetadata + + + + + + + Name + + + LogLinks + + + Opcodes + + + Tasks + + + + + + + + + diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml index 6a9bc8edafe..d9dcc2034bb 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml @@ -1,139 +1,139 @@ - - - - - - System.Diagnostics.Eventing.Reader.EventLogConfiguration - - - PSStandardMembers - - - DefaultDisplayPropertySet - - LogName - MaximumSizeInBytes - RecordCount - LogMode - - - - - - - - System.Diagnostics.Eventing.Reader.EventLogRecord - - - PSStandardMembers - - - DefaultDisplayPropertySet - - TimeCreated - ProviderName - Id - Message - - - - - - - - System.Diagnostics.Eventing.Reader.ProviderMetadata - - - ProviderName - Name - - - PSStandardMembers - - - DefaultDisplayPropertySet - - Name - LogLinks - - - - - - - - Microsoft.PowerShell.Commands.GetCounter.CounterSet - - - Counter - Paths - - - - - Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample - - - PSStandardMembers - - - DefaultDisplayPropertySet - - Path - InstanceName - CookedValue - - - - - - - - Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet - - - PSStandardMembers - - - DefaultDisplayPropertySet - - Timestamp - Readings - - - - - - - - Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet - - - Readings - - $strPaths = "" - foreach ($ctr in $this.CounterSamples) - { - $strPaths += ($ctr.Path + " :" + "`n") - $strPaths += ($ctr.CookedValue.ToString() + "`n`n") - } - return $strPaths - - - - - + + + + + + System.Diagnostics.Eventing.Reader.EventLogConfiguration + + + PSStandardMembers + + + DefaultDisplayPropertySet + + LogName + MaximumSizeInBytes + RecordCount + LogMode + + + + + + + + System.Diagnostics.Eventing.Reader.EventLogRecord + + + PSStandardMembers + + + DefaultDisplayPropertySet + + TimeCreated + ProviderName + Id + Message + + + + + + + + System.Diagnostics.Eventing.Reader.ProviderMetadata + + + ProviderName + Name + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Name + LogLinks + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.CounterSet + + + Counter + Paths + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Path + InstanceName + CookedValue + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + PSStandardMembers + + + DefaultDisplayPropertySet + + Timestamp + Readings + + + + + + + + Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet + + + Readings + + $strPaths = "" + foreach ($ctr in $this.CounterSamples) + { + $strPaths += ($ctr.Path + " :" + "`n") + $strPaths += ($ctr.CookedValue.ToString() + "`n`n") + } + return $strPaths + + + + + diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.psd1 b/src/Modules/Windows-Full/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.psd1 index b2b562f0002..ee3091ecc55 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.psd1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.psd1 @@ -1,32 +1,32 @@ -@{ -RootModule = 'Microsoft.Powershell.LocalAccounts' -ModuleVersion = '1.0.0.0' -GUID = '8e362604-2c0b-448f-a414-a6a690a644e2' -Author = 'Microsoft Corporation' -CompanyName = 'Microsoft Corporation' -Copyright = '© Microsoft Corporation. All rights reserved.' -Description = 'Provides cmdlets to work with local users and local groups' -PowerShellVersion = '3.0' -CLRVersion = '4.0' -FormatsToProcess = @('LocalAccounts.format.ps1xml') -CmdletsToExport = @( - 'Add-LocalGroupMember', - 'Disable-LocalUser', - 'Enable-LocalUser', - 'Get-LocalGroup', - 'Get-LocalGroupMember', - 'Get-LocalUser', - 'New-LocalGroup', - 'New-LocalUser', - 'Remove-LocalGroup', - 'Remove-LocalGroupMember', - 'Remove-LocalUser', - 'Rename-LocalGroup', - 'Rename-LocalUser', - 'Set-LocalGroup', - 'Set-LocalUser' - ) -AliasesToExport= @( "algm", "dlu", "elu", "glg", "glgm", "glu", "nlg", "nlu", "rlg", "rlgm", "rlu", "rnlg", "rnlu", "slg", "slu") -HelpInfoURI = 'https://go.microsoft.com/fwlink/?LinkId=717973' -} - +@{ +RootModule = 'Microsoft.Powershell.LocalAccounts' +ModuleVersion = '1.0.0.0' +GUID = '8e362604-2c0b-448f-a414-a6a690a644e2' +Author = 'Microsoft Corporation' +CompanyName = 'Microsoft Corporation' +Copyright = '© Microsoft Corporation. All rights reserved.' +Description = 'Provides cmdlets to work with local users and local groups' +PowerShellVersion = '3.0' +CLRVersion = '4.0' +FormatsToProcess = @('LocalAccounts.format.ps1xml') +CmdletsToExport = @( + 'Add-LocalGroupMember', + 'Disable-LocalUser', + 'Enable-LocalUser', + 'Get-LocalGroup', + 'Get-LocalGroupMember', + 'Get-LocalUser', + 'New-LocalGroup', + 'New-LocalUser', + 'Remove-LocalGroup', + 'Remove-LocalGroupMember', + 'Remove-LocalUser', + 'Rename-LocalGroup', + 'Rename-LocalUser', + 'Set-LocalGroup', + 'Set-LocalUser' + ) +AliasesToExport= @( "algm", "dlu", "elu", "glg", "glgm", "glu", "nlg", "nlu", "rlg", "rlgm", "rlu", "rnlg", "rnlu", "slg", "slu") +HelpInfoURI = 'https://go.microsoft.com/fwlink/?LinkId=717973' +} + diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 index 22ad15fb766..0c0921821d9 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 @@ -1,2070 +1,2070 @@ -Import-LocalizedData LocalizedData -FileName Microsoft.PowerShell.ODataUtilsStrings.psd1 - - -# Add .NET classes used by the module -Add-Type -TypeDefinition $global:BaseClassDefinitions - -######################################################### -# Generates PowerShell module containing client side -# proxy cmdlets that can be used to interact with an -# OData based server side endpoint. -######################################################### -function ExportODataEndpointProxy -{ - param - ( - [string] $Uri, - [string] $OutputModule, - [string] $MetadataUri, - [PSCredential] $Credential, - [string] $CreateRequestMethod, - [string] $UpdateRequestMethod, - [string] $CmdletAdapter, - [Hashtable] $ResourceNameMapping, - [switch] $Force, - [Hashtable] $CustomData, - [switch] $AllowClobber, - [switch] $AllowUnsecureConnection, - [Hashtable] $Headers, - [string] $ProgressBarStatus, - [System.Management.Automation.PSCmdlet] $PSCmdlet - ) - - [xml] $metadataXML = GetMetaData $MetadataUri $PSCmdlet $Credential $Headers - - [ODataUtils.Metadata] $metaData = ParseMetadata $metadataXML $MetadataUri $CmdletAdapter $PSCmdlet - - VerifyMetaData $MetadataUri $metaData $AllowClobber.IsPresent $PSCmdlet $progressBarStatus $CmdletAdapter $CustomData $ResourceNameMapping - - GenerateClientSideProxyModule $metaData $MetadataUri $Uri $OutputModule $CreateRequestMethod $UpdateRequestMethod $CmdletAdapter $ResourceNameMapping $CustomData $ProgressBarStatus $PSCmdlet -} - -######################################################### -# ParseMetaData is a helper function used to parse the -# metadata to convert it in to an object structure for -# further consumption during proxy generation. -######################################################### -function ParseMetaData -{ - param - ( - [xml] $metadataXml, - [string] $metaDataUri, - [string] $cmdletAdapter, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - # $metaDataUri is already validated at the cmdlet layer. - if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ParseMetadata") } - - if($null -eq $metadataXml) - { - $errorMessage = ($LocalizedData.InValidXmlInMetadata -f $metaDataUri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadataUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - Write-Verbose $LocalizedData.VerboseParsingMetadata - - # Check the OData version in the fetched metadata to make sure that - # OData version (and hence the protocol) used in the metadata is - # supported by the adapter used for executing the generated - # proxy cmdlets. - if(($null -ne $metadataXML) -and ($null -ne $metadataXML.Edmx)) - { - if($null -eq $metadataXML.Edmx.Version) - { - $errorMessage = ($LocalizedData.ODataVersionNotFound -f $MetadataUri) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyODataVersionNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - $metaDataVersion = New-Object -TypeName System.Version -ArgumentList @($metadataXML.Edmx.Version) - - # When we support plug-in model, We would have to fetch the - # $minSupportedVersionString & $maxSupportedVersionString - # from the plug-in instead of using an hardcoded value. - $minSupportedVersionString = '1.0' - $maxSupportedVersionString = '3.0' - $minSupportedVersion = New-Object -TypeName System.Version -ArgumentList @($minSupportedVersionString) - $maxSupportedVersion = New-Object -TypeName System.Version -ArgumentList @($maxSupportedVersionString) - - $minVersionComparisonResult = $minSupportedVersion.CompareTo($metaDataVersion) - $maxVersionComparisonResult = $maxSupportedVersion.CompareTo($metaDataVersion) - - if(-not($minVersionComparisonResult -lt $maxVersionComparisonResult)) - { - $errorMessage = ($LocalizedData.ODataVersionNotSupported -f $metadataXML.Edmx.Version, $MetadataUri, $minSupportedVersionString, $maxSupportedVersionString, $CmdletAdapter) - $exception = [System.NotSupportedException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyODataVersionNotSupported" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - else - { - $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - foreach ($schema in $MetadataXML.Edmx.DataServices.Schema) - { - if (($null -ne $schema) -and [string]::IsNullOrEmpty($schema.NameSpace )) - { - $callerPSCmdlet = $callerPSCmdlet -as [System.Management.Automation.PSCmdlet] - $errorMessage = ($LocalizedData.InValidSchemaNamespace -f $metaDataUri) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidSchemaNamespace" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - - $metaData = New-Object -TypeName ODataUtils.Metadata - - # this is a processing queue for those types that require base types that haven't been defined yet - $entityAndComplexTypesQueue = @{} - - foreach ($schema in $metadataXml.Edmx.DataServices.Schema) - { - if ($null -eq $schema) - { - Write-Error $LocalizedData.EmptySchema - continue - } - - if ($null -eq $metadata.Namespace) - { - $metaData.Namespace = $schema.Namespace - } - - foreach ($entityType in $schema.EntityType) - { - $baseType = $null - - if ($null -ne $entityType.BaseType) - { - # add it to the processing queue - $baseType = GetBaseType $entityType $metaData - if ($null -eq $baseType) - { - $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='EntityType'; value=$entityType}) - continue - } - } - - [ODataUtils.EntityType] $newType = ParseMetadataTypeDefinition $entityType $baseType $metaData $schema.Namespace $true - $metaData.EntityTypes += $newType - AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $schema.Namespace - } - - foreach ($complexType in $schema.ComplexType) - { - $baseType = $null - - if ($null -ne $complexType.BaseType) - { - # add it to the processing queue - $baseType = GetBaseType $complexType $metaData - if ($null -eq $baseType) - { - $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='ComplexType'; value=$complexType}) - continue - } - } - - [ODataUtils.EntityType] $newType = ParseMetadataTypeDefinition $complexType $baseType $metaData $schema.Namespace $false - $metaData.ComplexTypes += $newType - AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $schema.Namespace - } - } - - foreach ($schema in $metadataXml.Edmx.DataServices.Schema) - { - foreach ($entityContainer in $schema.EntityContainer) - { - if ($entityContainer.IsDefaultEntityContainer) - { - $metaData.DefaultEntityContainerName = $entityContainer.Name - } - - $entityTypeToEntitySetMapping = @{}; - foreach ($entitySet in $entityContainer.EntitySet) - { - $entityType = $metaData.EntityTypes | Where-Object { $_.Name -eq $entitySet.EntityType.Split('.')[-1] } - $entityTypeName = $entityType.Name - - if($entityTypeToEntitySetMapping.ContainsKey($entityTypeName)) - { - $existingEntitySetName = $entityTypeToEntitySetMapping[$entityTypeName] - - $errorMessage = ($LocalizedData.EntityNameConflictError -f $metaDataUri, $existingEntitySetName, $entitySet.Name, $entityTypeName) - $exception = [System.NotSupportedException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyEntityTypeMappingError" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - else - { - $entityTypeToEntitySetMapping.Add($entityTypeName, $entitySet.Name) - } - - $newEntitySet = [ODataUtils.EntitySet] @{ - "Namespace" = $schema.Namespace; - "Name" = $entitySet.Name; - "Type" = $entityType; - } - - $metaData.EntitySets += $newEntitySet - } - } - } - - foreach ($schema in $metadataXml.Edmx.DataServices.Schema) - { - foreach ($association in $schema.Association) - { - $newAssociationType = [ODataUtils.AssociationType] @{ - "Namespace" = $schema.Namespace; - "EndType1" = $metaData.EntityTypes | Where-Object { $_.Name -eq $association.End[0].Type.Split('.')[-1] }; - "NavPropertyName1" = $association.End[0].Role; - "Multiplicity1" = $association.End[0].Multiplicity; - - "EndType2" = $metaData.EntityTypes | Where-Object { $_.Name -eq $association.End[1].Type.Split('.')[-1] }; - "NavPropertyName2" = $association.End[1].Role; - "Multiplicity2" = $association.End[1].Multiplicity; - } - - $newAssociation = [ODataUtils.AssociationSet] @{ - "Namespace" = $schema.Namespace; - "Name" = $association.Name; - "Type" = $newAssociationType; - } - - $metaData.Associations += $newAssociation - } - } - - foreach ($schema in $metadataXml.Edmx.DataServices.Schema) - { - foreach ($action in $schema.EntityContainer.FunctionImport) - { - # HttpMethod is only used for legacy Service Operations - if ($null -eq $action.HttpMethod) - { - if ($null -ne $action.IsSideEffecting) - { - $isSideEffecting = $action.IsSideEffecting - } - else - { - $isSideEffecting = $true - } - - $newAction = [ODataUtils.Action] @{ - "Namespace" = $schema.Namespace; - "Verb" = $action.Name; - "IsSideEffecting" = $isSideEffecting; - "IsBindable" = $action.IsBindable; - # we don't care about IsAlwaysBindable, since we populate actions information from $metaData - # so we can't know the state of the entity - } - - # Actions are always SideEffecting, otherwise it's an OData function - if ($newAction.IsSideEffecting -ne $false) - { - foreach ($parameter in $action.Parameter) - { - if ($null -ne $parameter.Nullable) - { - $parameterIsNullable = [System.Convert]::ToBoolean($parameter.Nullable); - } - - $newParameter = [ODataUtils.TypeProperty] @{ - "Name" = $parameter.Name; - "TypeName" = $parameter.Type; - "IsNullable" = $parameterIsNullable - } - - $newAction.Parameters += $newParameter - } - - # IsBindable means it operates on Entity/ies - if ($newAction.IsBindable) - { - $regex = "Collection\((.+)\)" - - if ($newAction.Parameters[0].TypeName -match $regex) - { - # action operating on a collection of entities - $insideTypeName = Convert-ODataTypeToCLRType $Matches[1] - - $newAction.EntitySet = $metaData.EntitySets | Where-Object { ($_.Type.Namespace + "." + $_.Type.Name) -eq $insideTypeName } - $newAction.IsSingleInstance = $false - } - else - { - # actions operating on a single instance - $newAction.EntitySet = $metaData.EntitySets | Where-Object { ($_.Type.Namespace + "." + $_.Type.Name) -eq $newAction.Parameters[0].TypeName } - - $newAction.IsSingleInstance = $true - } - } - - $metaData.Actions += $newAction - } - } - } - } - - $metaData -} - -######################################################### -# VerifyMetaData is a helper function used to validate -# the processed metadata to make sure client side proxy -# can be created for the supplied metadata. -######################################################### -function VerifyMetaData -{ - param - ( - [string] $metaDataUri, - [ODataUtils.Metadata] $metaData, - [boolean] $allowClobber, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet, - [string] $progressBarStatus, - [string] $cmdletAdapter, - [Hashtable] $customData, - [Hashtable] $resourceNameMapping - ) - - # $metaDataUri & $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "VerifyMetaData") } - if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } - if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } - - Write-Verbose $LocalizedData.VerboseVerifyingMetadata - - if ($metadata.EntitySets.Count -le 0) - { - $errorMessage = ($LocalizedData.NoEntitySets -f $metaDataUri) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - if ($metadata.EntityTypes.Count -le 0) - { - $errorMessage = ($LocalizedData.NoEntityTypes -f $metaDataUri) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - # All the generated proxy cmdlets would have the following parameters added. - # The ODataAdapter has the default implementation on how to handle the - # scenario when these parameters are used during proxy invocations. - # The default implementation can be overridden using adapter derivation model. - $reservedProperties = @("Filter", "IncludeTotalResponseCount", "OrderBy", "Select", "Skip", "Top", "ConnectionUri", "CertificateThumbprint", "Credential") - $validEntitySets = @() - $sessionCommands = Get-Command -All - - foreach ($entitySet in $metaData.EntitySets) - { - if ($null -eq $entitySet.Type) - { - $errorMessage = ($LocalizedData.EntitySetUndefinedType -f $metaDataUri, $entitySet.Name) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - if ($cmdletAdapter -eq "NetworkControllerAdapter" -And $customData -And $customData.Contains($entitySet.Name) -eq $false) - { - continue - } - - $hasConflictingProperty = $false - $hasConflictingCommand = $false - - $entityAndNavigationProperties = (GetAllProperties $entitySet.Type) + (GetAllProperties $entitySet.Type -IncludeOnlyNavigationProperties) - foreach($entityProperty in $entityAndNavigationProperties) - { - if($reservedProperties.Contains($entityProperty.Name)) - { - $hasConflictingProperty = $true - if(!$allowClobber) - { - # Write Error message and skip current Entity Set. - $errorMessage = ($LocalizedData.SkipEntitySetProxyCreation -f $entitySet.Name, $entitySet.Type.Name, $entityProperty.Name) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointDefaultPropertyCollision" $null ([System.Management.Automation.ErrorCategory]::InvalidOperation) $exception $metaDataUri - $callerPSCmdlet.WriteError($errorRecord) - } - else - { - $warningMessage = ($LocalizedData.EntitySetProxyCreationWithWarning -f $entitySet.Name, $entityProperty.Name, $entitySet.Type.Name) - $callerPSCmdlet.WriteWarning($warningMessage) - } - } - } - - foreach($currentCommand in $sessionCommands) - { - # The generated command Noun can be set using ResourceNameMapping - $generatedCommandName = $entitySet.Name - if ($resourceNameMapping -And $resourceNameMapping.Contains($entitySet.Name)) { - $generatedCommandName = $resourceNameMapping[$entitySet.Name] - } - - if(($null -ne $currentCommand.Noun -and $currentCommand.Noun -eq $generatedCommandName) -and - ($currentCommand.Verb -eq "Get" -or - $currentCommand.Verb -eq "Set" -or - $currentCommand.Verb -eq "New" -or - $currentCommand.Verb -eq "Remove")) - { - $hasConflictingCommand = $true - VerifyMetadataHelper $LocalizedData.SkipEntitySetConflictCommandCreation ` - $LocalizedData.EntitySetConflictCommandCreationWithWarning ` - $entitySet.Name $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet - } - } - - foreach($currentAction in $metaData.Actions) - { - $actionCommand = "Invoke-" + "$($entitySet.Name)$($currentAction.Verb)" - - foreach($currentCommand in $sessionCommands) - { - if($actionCommand -eq $currentCommand.Name) - { - $hasConflictingCommand = $true - VerifyMetadataHelper $LocalizedData.SkipEntitySetConflictCommandCreation ` - $LocalizedData.EntitySetConflictCommandCreationWithWarning $entitySet.Name ` - $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet - } - } - } - - if(!($hasConflictingProperty -or $hasConflictingCommand)-or $allowClobber) - { - $validEntitySets += $entitySet - } - } - - if ($cmdletAdapter -ne "NetworkControllerAdapter") { - - $metaData.EntitySets = $validEntitySets - - $validServiceActions = @() - $hasConflictingServiceActionCommand = $true - foreach($currentAction in $metaData.Actions) - { - $serviceActionCommand = "Invoke-" + "$($currentAction.Verb)" - - foreach($currentCommand in $sessionCommands) - { - if($serviceActionCommand -eq $currentCommand.Name) - { - $hasConflictingServiceActionCommand = $true - VerifyMetadataHelper $LocalizedData.SkipConflictServiceActionCommandCreation ` - $LocalizedData.ConflictServiceActionCommandCreationWithWarning $entitySet.Name ` - $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet - } - } - - if(!$hasConflictingServiceActionCommand -or $allowClobber) - { - $validServiceActions += $currentAction - } - } - - $metaData.Actions = $validServiceActions - } - - # Update Progress bar. - ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 5 20 1 1 -} - -######################################################### -# GenerateClientSideProxyModule is a helper function used -# to generate a PowerShell module that serves as a client -# side proxy for interacting with the server side -# OData endpoint. The proxy module contains proxy cmdlets -# implemented in CDXML modules and they are exposed -# through module manifest as nested modules. -# One CDXML module is created for each EntitySet -# described in the metadata. Each CDXML module contains -# CRUD & Service Action specific proxy cmdlets targeting -# the underlying EntityType. There is 1:M mapping between -# EntitySet & its underlying EntityTypes (i.e., all -# entities with in the single EntitySet will be of the -# same EntityType but there can be multiple entities -# of the same type with in an EntitySet). -######################################################### -function GenerateClientSideProxyModule -{ - param - ( - [ODataUtils.Metadata] $metaData, - [string] $metaDataUri, - [string] $uri, - [string] $outputModule, - [string] $createRequestMethod, - [string] $updateRequestMethod, - [string] $cmdletAdapter, - [Hashtable] $resourceNameMapping, - [Hashtable] $customData, - [string] $progressBarStatus, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } - if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } - if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } - - # This function performs the following set of tasks - # while creating the client side proxy module: - # 1. If the server side endpoint exposes complex types, - # the client side proxy complex types are created - # as C# class in ComplexTypeDefinitions.psm1 - # 2. Creates proxy cmdlets for CRUD operations. - # 3. Creates proxy cmdlets for Service action operations. - # 4. Creates module manifest. - - Write-Verbose ($LocalizedData.VerboseSavingModule -f $outputModule) - - $typeDefinitionFileName = "ComplexTypeDefinitions.psm1" - $complexTypeMapping = GenerateComplexTypeDefinition $metaData $metaDataUri $outputModule $typeDefinitionFileName $cmdletAdapter $callerPSCmdlet - - ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 20 20 1 1 - - $complexTypeFileDefinitionPath = Join-Path -Path $outputModule -ChildPath $typeDefinitionFileName - - if(Test-Path -Path $complexTypeFileDefinitionPath) - { - $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $complexTypeFileDefinitionPath | Get-Item - if($null -ne $callerPSCmdlet) - { - $callerPSCmdlet.WriteObject($proxyFile) - } - } - - $currentEntryCount = 0 - foreach ($entitySet in $metaData.EntitySets) - { - $currentEntryCount += 1 - if ($cmdletAdapter -eq "NetworkControllerAdapter" -And $customData -And $customData.Contains($entitySet.Name) -eq $false) - { - ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 40 20 $metaData.EntitySets.Count $currentEntryCount - continue - } - - GenerateCRUDProxyCmdlet $entitySet $metaData $uri $outputModule $createRequestMethod $updateRequestMethod $cmdletAdapter $resourceNameMapping $customData $complexTypeMapping "Export-ODataEndpointProxy" $progressBarStatus 40 20 $metaData.EntitySets.Count $currentEntryCount $callerPSCmdlet - } - - GenerateServiceActionProxyCmdlet $metaData $uri "$outputModule\ServiceActions.cdxml" $complexTypeMapping $progressBarStatus $callerPSCmdlet - - $moduleDirInfo = [System.IO.DirectoryInfo]::new($outputModule) - $moduleManifestName = $moduleDirInfo.Name + ".psd1" - GenerateModuleManifest $metaData $outputModule\$moduleManifestName @($typeDefinitionFileName, 'ServiceActions.cdxml') $resourceNameMapping $progressBarStatus $callerPSCmdlet -} - -######################################################### -# GenerateCRUDProxyCmdlet is a helper function used -# to generate Get, Set, New & Remove proxy cmdlet. -# The proxy cmdlet is generated in the CDXML -# compliant format. -######################################################### -function GenerateCRUDProxyCmdlet -{ - param - ( - [ODataUtils.EntitySet] $entitySet, - [ODataUtils.Metadata] $metaData, - [string] $uri, - [string] $outputModule, - [string] $createRequestMethod, - [string] $UpdateRequestMethod, - [string] $cmdletAdapter, - [Hashtable] $resourceNameMapping, - [Hashtable] $customData, - [Hashtable] $complexTypeMapping, - [string] $progressBarActivityName, - [string] $progressBarStatus, - [double] $previousSegmentWeight, - [double] $currentSegmentWeight, - [int] $totalNumberofEntries, - [int] $currentEntryCount, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $entitySet) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } - if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } - if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } - - $entitySetName = $entitySet.Name - if(($null -ne $resourceNameMapping) -and - $resourceNameMapping.ContainsKey($entitySetName)) - { - $entitySetName = $resourceNameMapping[$entitySetName] - } - else - { - $entitySetName = $entitySet.Type.Name - } - - $Path = "$OutputModule\$entitySetName.cdxml" - - $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) - - if ($null -eq $xmlWriter) - { - throw ($LocalizedData.XmlWriterInitializationError -f $entitySet.Name) - } - - $xmlWriter = SaveCDXMLHeader $xmlWriter $uri $entitySet.Name $entitySetName $cmdletAdapter - - # Get the keys depending on whether the url contains variables or not - if ($CmdletAdapter -ne "NetworkControllerAdapter") - { - $keys = (GetAllProperties $entitySet.Type) | Where-Object { $_.IsKey } - } - else - { - $name = $entitySet.Name - $keys = GetKeys $entitySet $customData.$name 'Get' - } - - $navigationProperties = GetAllProperties $entitySet.Type -IncludeOnlyNavigationProperties - - GenerateGetProxyCmdlet $xmlWriter $metaData $keys $navigationProperties $cmdletAdapter $complexTypeMapping - - $nonKeyProperties = (GetAllProperties $entitySet.Type) | Where-Object { -not $_.isKey } - $nullableProperties = $nonKeyProperties | Where-Object { $_.isNullable } - $nonNullableProperties = $nonKeyProperties | Where-Object { -not $_.isNullable } - - $xmlWriter.WriteStartElement('StaticCmdlets') - - $keyProperties = $keys - - # Do operations specifically needed for NetworkController cmdlets - if ($CmdletAdapter -eq "NetworkControllerAdapter") - { - $keyProperties = GetKeys $entitySet $customData.$name 'New' - $additionalProperties = GetNetworkControllerAdditionalProperties $navigationProperties $metaData - $nullableProperties = UpdateNetworkControllerSpecificProperties $nullableProperties $additionalProperties $keyProperties $true - $nonNullableProperties = UpdateNetworkControllerSpecificProperties $nonNullableProperties $additionalProperties $keyProperties $false - } - - GenerateNewProxyCmdlet $xmlWriter $metaData $keyProperties $nonNullableProperties $nullableProperties $navigationProperties $cmdletAdapter $complexTypeMapping - - if ($CmdletAdapter -ne "NetworkControllerAdapter") - { - GenerateSetProxyCmdlet $xmlWriter $keyProperties $nonKeyProperties $complexTypeMapping - } - - if ($CmdletAdapter -eq "NetworkControllerAdapter") - { - $keyProperties = GetKeys $entitySet $customData.$name 'Remove' - } - - GenerateRemoveProxyCmdlet $xmlWriter $metaData $keyProperties $navigationProperties $cmdletAdapter $complexTypeMapping - - $entityActions = $metaData.Actions | Where-Object { ($_.EntitySet.Namespace -eq $entitySet.Namespace) -and ($_.EntitySet.Name -eq $entitySet.Name) } - - if ($entityActions.Length -gt 0) - { - foreach($action in $entityActions) - { - $xmlWriter = GenerateActionProxyCmdlet $xmlWriter $metaData $action $entitySet.Name $true $keys $complexTypeMapping - } - } - - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('CmdletAdapterPrivateData') - - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', 'EntityTypeName') - $xmlWriter.WriteString("$($entitySet.Type.Namespace).$($entitySet.Type.Name)") - $xmlWriter.WriteEndElement() - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', 'EntitySetName') - $xmlWriter.WriteString("$($entitySet.Namespace).$($entitySet.Name)") - $xmlWriter.WriteEndElement() - - # Add the customUri to privateData - if ($CmdletAdapter -eq "NetworkControllerAdapter") - { - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', "CustomUriSuffix") - $xmlWriter.WriteString($CustomData.$name) - $xmlWriter.WriteEndElement() - } - - # Add CreateRequestMethod and UpdateRequestMethod to privateData - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', 'CreateRequestMethod') - $xmlWriter.WriteString("$CreateRequestMethod") - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', 'UpdateRequestMethod') - $xmlWriter.WriteString("$UpdateRequestMethod") - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteEndElement() - - SaveCDXMLFooter $xmlWriter - - ProcessStreamHelper ($LocalizedData.VerboseSavedCDXML -f $($entitySetName), $Path) $progressBarActivityName $progressBarStatus $previousSegmentWeight $currentSegmentWeight $totalNumberofEntries $currentEntryCount $Path $callerPSCmdlet -} - -######################################################### -# GenerateGetProxyCmdlet is a helper function used -# to generate Get-* proxy cmdlet. The proxy cmdlet is -# generated in the CDXML compliant format. -######################################################### -function GenerateGetProxyCmdlet -{ - param - ( - [System.XMl.XmlTextWriter] $xmlWriter, - [ODataUtils.Metadata] $metaData, - [object[]] $keys, - [object[]] $navigationProperties, - [string] $cmdletAdapter, - [Hashtable] $complexTypeMapping - ) - - # $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateGetProxyCmdlet") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateGetProxyCmdlet") } - - $xmlWriter.WriteStartElement('InstanceCmdlets') - $xmlWriter.WriteStartElement('GetCmdletParameters') - $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') - - # adding key parameters and association parameters to QueryableProperties, each in a different parameter set - # to be used by GET cmdlet - if (($null -ne $keys -and $keys.Length -gt 0) -or (($null -ne $navigationProperties -and $navigationProperties.Length -gt 0) -and $cmdletAdapter -ne "NetworkControllerAdapter")) - { - $xmlWriter.WriteStartElement('QueryableProperties') - $position = 0 - - $keys | Where-Object { $null -ne $_ } | ForEach-Object { - $xmlWriter.WriteStartElement('Property') - $xmlWriter.WriteAttributeString('PropertyName', $_.Name) - - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('RegularQuery') - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $_.Name) - $xmlWriter.WriteAttributeString('CmdletParameterSets', 'Default') - $xmlWriter.WriteAttributeString('IsMandatory', $_.IsMandatory.ToString().ToLower()) - $xmlWriter.WriteAttributeString('Position', $position) - if($_.IsMandatory) - { - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - } - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - $position++ - } - - # This behaviour is different for NetworkController specific cmdlets. - if ($CmdletAdapter -ne "NetworkControllerAdapter") - { - $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { - $associatedType = GetAssociatedType $metaData $_ - $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType - $nvgProperty = $_ - - (GetAllProperties $associatedType) | Where-Object { $_.IsKey } | ForEach-Object { - $xmlWriter.WriteStartElement('Property') - $xmlWriter.WriteAttributeString('PropertyName', $associatedEntitySet.Name + ':' + $_.Name + ':Key') - - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('RegularQuery') - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', 'Associated' + $nvgProperty.Name + $_.Name) - $xmlWriter.WriteAttributeString('CmdletParameterSets', $nvgProperty.AssociationName) - $xmlWriter.WriteAttributeString('IsMandatory', 'true') - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - } - } - - - # Add Query Parameters (i.e., Top, Skip, OrderBy, Filter) to the generated Get-* cmdlets. - $queryParameters = - @{ - "Filter" = "Edm.String"; - "IncludeTotalResponseCount" = "switch"; - "OrderBy" = "Edm.String"; - "Select" = "Edm.String"; - "Skip" = "Edm.Int32"; - "Top" = "Edm.Int32"; - } - - foreach($currentQueryParameter in $queryParameters.Keys) - { - $xmlWriter.WriteStartElement('Property') - $xmlWriter.WriteAttributeString('PropertyName', "QueryOption:" + $currentQueryParameter) - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $queryParameters[$currentQueryParameter] - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - $xmlWriter.WriteStartElement('RegularQuery') - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $currentQueryParameter) - - if($queryParameters[$currentQueryParameter] -eq "Edm.String") - { - $xmlWriter.WriteStartElement('ValidateNotNullOrEmpty') - $xmlWriter.WriteEndElement() - } - - if($queryParameters[$currentQueryParameter] -eq "Edm.Int32") - { - $minValue = 1 - # For Skip Query parameter we want to support 0 as the - # minimum skip value in order to support client side paging. - if($currentQueryParameter -eq 'Skip') - { - $minValue = 0 - } - $xmlWriter.WriteStartElement('ValidateRange') - $xmlWriter.WriteAttributeString('Min', $minValue) - $xmlWriter.WriteAttributeString('Max', [int]::MaxValue) - $xmlWriter.WriteEndElement() - } - - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - } - } - - $xmlWriter.WriteEndElement() - } - - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('GetCmdlet') - $xmlWriter.WriteStartElement('CmdletMetadata') - $xmlWriter.WriteAttributeString('Verb', 'Get') - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteEndElement() -} - -######################################################### -# GenerateNewProxyCmdlet is a helper function used -# to generate New-* proxy cmdlet. The proxy cmdlet is -# generated in the CDXML compliant format. -######################################################### -function GenerateNewProxyCmdlet -{ - param - ( - [System.XMl.XmlTextWriter] $xmlWriter, - [ODataUtils.Metadata] $metaData, - [object[]] $keyProperties, - [object[]] $nonNullableProperties, - [object[]] $nullableProperties, - [object[]] $navigationProperties, - [string] $cmdletAdapter, - [Hashtable] $complexTypeMapping - ) - - # $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateNewProxyCmdlet") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateNewProxyCmdlet") } - - $xmlWriter.WriteStartElement('Cmdlet') - $xmlWriter.WriteStartElement('CmdletMetadata') - $xmlWriter.WriteAttributeString('Verb', 'New') - $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') - $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', 'Create') - $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') - - AddParametersNode $xmlWriter $keyProperties $nonNullableProperties $nullableProperties $null $true $true $complexTypeMapping - $xmlWriter.WriteEndElement() - - # This behaviour is different for NetworkControllerCmdlets - if ($CmdletAdapter -ne "NetworkControllerAdapter") - { - $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { - $associatedType = GetAssociatedType $metaData $_ - $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', "Association:Create:$($associatedEntitySet.Name)") - $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) - - $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) - - AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping - $xmlWriter.WriteEndElement() - } - } - - $xmlWriter.WriteEndElement() -} - -######################################################### -# GenerateRemoveProxyCmdlet is a helper function used -# to generate Remove-* proxy cmdlet. The proxy cmdlet is -# generated in the CDXML compliant format. -######################################################### -function GenerateRemoveProxyCmdlet -{ - param - ( - - [System.XMl.XmlTextWriter] $xmlWriter, - [ODataUtils.Metadata] $metaData, - [object[]] $keyProperties, - [object[]] $navigationProperties, - [string] $cmdletAdapter, - [Hashtable] $complexTypeMapping - ) - - # $metaData, $cmdletAdapter & $cmdletAdapter are already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateRemoveProxyCmdlet") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateRemoveProxyCmdlet") } - - $xmlWriter.WriteStartElement('Cmdlet') - $xmlWriter.WriteStartElement('CmdletMetadata') - $xmlWriter.WriteAttributeString('Verb', 'Remove') - $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') - $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', 'Delete') - $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') - - # This behaviour is different for NetworkControllerCmdlets - if ($CmdletAdapter -eq "NetworkControllerAdapter") - { - # Add etag for NetworkControllerCmdlets - $otherProperties = @([ODataUtils.TypeProperty] @{ - "Name" = "Etag"; - "TypeName" = "Edm.String"; - "IsNullable" = $true; - }) - - AddParametersNode $xmlWriter $keyProperties $null $otherProperties $null $true $true $complexTypeMapping - } - else - { - AddParametersNode $xmlWriter $keyProperties $null $null $null $true $true $complexTypeMapping - } - - $xmlWriter.WriteEndElement() - - # This behaviour is different for NetworkControllerCmdlets - if ($CmdletAdapter -ne "NetworkControllerAdapter") - { - $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { - - $associatedType = GetAssociatedType $metaData $_ - $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', "Association:Delete:$($associatedEntitySet.Name)") - $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) - - $associatedType = GetAssociatedType $metaData $_ - $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) - - AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping - $xmlWriter.WriteEndElement() - } - } - $xmlWriter.WriteEndElement() -} - -######################################################### -# GenerateActionProxyCmdlet is a helper function used -# to generate Invoke-* proxy cmdlet. These proxy cmdlets -# support Instance/Service level actions. They are -# generated in the CDXML compliant format. -######################################################### -function GenerateActionProxyCmdlet -{ - param - ( - [System.Xml.XmlWriter] $xmlWriter, - [ODataUtils.Metadata] $metaData, - [ODataUtils.Action] $action, - [string] $noun, - [bool] $isInstanceAction, - [ODataUtils.TypeProperty] $keys, - [Hashtable] $complexTypeMapping - ) - - # $metaData is already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateActionProxyCmdlet") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateActionProxyCmdlet") } - if($null -eq $action) { throw ($LocalizedData.ArguementNullError -f "Action", "GenerateActionProxyCmdlet") } - if($null -eq $noun) { throw ($LocalizedData.ArguementNullError -f "Noun", "GenerateActionProxyCmdlet") } - - $xmlWriter.WriteStartElement('Cmdlet') - - $xmlWriter.WriteStartElement('CmdletMetadata') - $xmlWriter.WriteAttributeString('Verb', 'Invoke') - $xmlWriter.WriteAttributeString('Noun', "$($noun)$($action.Verb)") - $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', "Action:$($action.Verb):$($action.EntitySet.Name)") - - $xmlWriter.WriteStartElement('Parameters') - - $keys | Where-Object { $null -ne $_ } | ForEach-Object { - $xmlWriter.WriteStartElement('Parameter') - $xmlWriter.WriteAttributeString('ParameterName', $_.Name + ':Key') - - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $_.Name) - $xmlWriter.WriteAttributeString('IsMandatory', 'true') - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - } - - $i = -1 - foreach ($parameter in $action.Parameters) - { - $i++ - - # for Instance actions, first parameter is Entity Set which we refer to using keys - if ($isInstanceAction -and ($i -eq 0)) - { - continue - } - - $xmlWriter.WriteStartElement('Parameter') - $xmlWriter.WriteAttributeString('ParameterName', $parameter.Name) - - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $parameter.TypeName - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $parameter.Name) - if (-not $parameter.IsNullable) - { - $xmlWriter.WriteAttributeString('IsMandatory', 'true') - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - } - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - } - - # Add -Force parameter to Service Action cmdlets. - AddParametersNode $xmlWriter $null $null $null $null $true $false $complexTypeMapping - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteEndElement() - - $xmlWriter -} - -######################################################### -# GenerateServiceActionProxyCmdlet is a helper function -# used to generate Invoke-* proxy cmdlet. These proxy -# cmdlets support all Service-level actions. They are -# generated in the CDXML compliant format. -######################################################### -function GenerateServiceActionProxyCmdlet -{ - param - ( - [Parameter(Mandatory=$true)] - [ODataUtils.Metadata] $metaData, - [Parameter(Mandatory=$true)] - [string] $uri, - [Parameter(Mandatory=$true)] - [string] $path, - [Hashtable] $complexTypeMapping, - [string] $progressBarStatus, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - # $uri is already validated at the cmdlet layer. - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateServiceActionProxyCmdlet") } - - $xmlWriter = New-Object System.XMl.XmlTextWriter($path,$Null) - - if ($null -eq $xmlWriter) - { - throw $LocalizedData.XmlWriterInitializationError -f "ServiceActions" - } - - $xmlWriter = SaveCDXMLHeader $xmlWriter $uri 'ServiceActions' 'ServiceActions' - - $actions = $metaData.Actions | Where-Object { $null -eq $_.EntitySet } - - if ($actions.Length -gt 0) - { - $xmlWriter.WriteStartElement('StaticCmdlets') - - foreach ($action in $actions) - { - $xmlWriter = GenerateActionProxyCmdlet $xmlWriter $metaData $action '' $false $null $complexTypeMapping - } - - $xmlWriter.WriteEndElement() - } - - $xmlWriter.WriteStartElement('CmdletAdapterPrivateData') - $xmlWriter.WriteStartElement('Data') - $xmlWriter.WriteAttributeString('Name', 'Namespace') - $xmlWriter.WriteString("$($EntitySet.Namespace)") - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - SaveCDXMLFooter $xmlWriter - - ProcessStreamHelper ($LocalizedData.VerboseSavedServiceActions -f $path) "Export-ODataEndpointProxy" $progressBarStatus 60 20 1 1 $path $callerPSCmdlet -} - -######################################################### -# GenerateModuleManifest is a helper function used -# to generate a wrapper module manifest file. The -# generated module manifest is persisted to the disk at -# the specified OutPutModule path. When the module -# manifest is imported, the following commands will -# be imported: -# 1. Get, Set, New & Remove proxy cmdlets. -# 2. If the server side Odata endpoint exposes complex -# types, then the corresponding client side proxy -# complex types imported. -# 3. Service Action proxy cmdlets. -######################################################### -function GenerateModuleManifest -{ - param - ( - [ODataUtils.Metadata] $metaData, - [String] $modulePath, - [string[]] $additionalModules, - [Hashtable] $resourceNameMapping, - [string] $progressBarStatus, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateModuleManifest") } - if($null -eq $modulePath) { throw ($LocalizedData.ArguementNullError -f "ModulePath", "GenerateModuleManifest") } - if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateModuleManifest") } - - $NestedModules = @() - foreach ($entitySet in $metaData.EntitySets) - { - $entitySetName = $entitySet.Name - if(($null -ne $resourceNameMapping) -and - $resourceNameMapping.ContainsKey($entitySetName)) - { - $entitySetName = $resourceNameMapping[$entitySetName] - } - else - { - $entitySetName = $entitySet.Type.Name - } - - $NestedModules += "$OutputModule\$($entitySetName).cdxml" - } - - New-ModuleManifest -Path $modulePath -NestedModules ($AdditionalModules + $NestedModules) - - ProcessStreamHelper ($LocalizedData.VerboseSavedModuleManifest -f $modulePath) "Export-ODataEndpointProxy" $progressBarStatus 80 20 1 1 $modulePath $callerPSCmdlet -} - -######################################################### -# GetBaseType is a helper function used to fetch the -# base type of the given type. -######################################################### -function GetBaseType -{ - param - ( - [System.Xml.XmlElement] $metadataEntityDefinition, - [ODataUtils.Metadata] $metaData - ) - - if ($null -ne $metadataEntityDefinition -and - $null -ne $metaData -and - $null -ne $metadataEntityDefinition.BaseType) - { - $baseType = $metaData.EntityTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} - if ($null -eq $baseType) - { - $baseType = $metaData.ComplexTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} - } - } - - if ($null -ne $baseType) - { - $baseType[0] - } -} - -######################################################### -# AddDerivedTypes is a helper function used to process -# derived types of a newly added type, that were -# previously waiting in the queue. -######################################################### -function AddDerivedTypes -{ - param - ( - [ODataUtils.EntityType] $baseType, - [Hashtable]$entityAndComplexTypesQueue, - [ODataUtils.Metadata] $metaData, - [string] $namespace - ) - - # $metaData is already validated at the cmdlet layer. - if($null -eq $baseType) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } - if($null -eq $entityAndComplexTypesQueue) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } - if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } - - $baseTypeFullName = $baseType.Namespace + '.' + $baseType.Name - - if ($entityAndComplexTypesQueue.ContainsKey($baseTypeFullName)) - { - foreach ($type in $entityAndComplexTypesQueue[$baseTypeFullName]) - { - if ($type.type -eq 'EntityType') - { - $newType = ParseMetadataTypeDefinition ($type.value) $baseType $metaData $namespace $true - $metaData.EntityTypes += $newType - } - else - { - $newType = ParseMetadataTypeDefinition ($type.value) $baseType $metaData $namespace $false - $metaData.ComplexTypes += $newType - } - - AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $namespace - } - } -} - -######################################################### -# ParseMetadataTypeDefinition is a helper function used -# to parse types definitions element of metadata xml. -######################################################### -function ParseMetadataTypeDefinition -{ - param - ( - [Parameter(Mandatory=$true)] - [System.Xml.XmlElement] $metadataEntityDefinition, - [ODataUtils.EntityType] $baseType, - [ODataUtils.Metadata] $metaData, - [string] $namespace, - [bool] $isEntity - ) - - # $metaData is already validated at the cmdlet layer. - if($null -eq $metadataEntityDefinition) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } - if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } - - $newEntityType = [ODataUtils.EntityType] @{ - "Namespace" = $namespace; - "Name" = $metadataEntityDefinition.Name; - "IsEntity" = $isEntity; - "BaseType" = $baseType; - } - - # properties defined on EntityType - $newEntityType.EntityProperties = $metadataEntityDefinition.Property | ForEach-Object { - if ($null -ne $_) - { - if ($null -ne $_.Nullable) - { - $newPropertyIsNullable = [System.Convert]::ToBoolean($_.Nullable) - } - else - { - $newPropertyIsNullable = $true - } - - [ODataUtils.TypeProperty] @{ - "Name" = $_.Name; - "TypeName" = $_.Type; - "IsNullable" = $newPropertyIsNullable; - } - } - } - - # navigation properties defined on EntityType - $newEntityType.NavigationProperties = $metadataEntityDefinition.NavigationProperty | ForEach-Object { - if ($null -ne $_) - { - ($AssociationNamespace, $AssociationName) = SplitNamespaceAndName $_.Relationship - [ODataUtils.NavigationProperty] @{ - "Name" = $_.Name; - "FromRole" = $_.FromRole; - "ToRole" = $_.ToRole; - "AssociationNamespace" = $AssociationNamespace; - "AssociationName" = $AssociationName; - } - } - } - - foreach ($entityTypeKey in $metadataEntityDefinition.Key.PropertyRef) - { - ((GetAllProperties $newEntityType) | Where-Object { $_.Name -eq $entityTypeKey.Name }).IsKey = $true - } - - $newEntityType -} - -######################################################### -# GetAllProperties is a helper function used to fetch -# the entity properties or navigation properties of -# the entity type as well as that of complete base -# type hierarchy. -######################################################### -function GetAllProperties -{ - param - ( - [ODataUtils.EntityType] $entityType, - [switch] $IncludeOnlyNavigationProperties - ) - - if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetAllProperties") } - - $requestedProperties = @() - - # Populate EntityType property from current EntityType as well - # as from the corresponding base types recursively if - # $IncludeOnlyNavigationProperties switch parameter is used then follow - # the same routine for navigation properties. - $currentEntityType = $entityType - while($null -ne $currentEntityType) - { - if($IncludeOnlyNavigationProperties.IsPresent) - { - $chosenProperties = $currentEntityType.NavigationProperties - } - else - { - $chosenProperties = $currentEntityType.EntityProperties - } - - $requestedProperties += $chosenProperties - $currentEntityType = $currentEntityType.BaseType - } - - return $requestedProperties -} - -######################################################### -# SplitNamespaceAndName is a helper function used -# to split Namespace and actual Name. -# e.g. "a.b.c" is namespace "a.b" and name "c" -######################################################### -function SplitNamespaceAndName -{ - param - ( - [string] $fullyQualifiedName - ) - - if($null -eq $fullyQualifiedName) { throw ($LocalizedData.ArguementNullError -f "FUllyQualifiedName", "SplitNamespaceAndName") } - - $sa = $fullyQualifiedName -split "(.*)\.(.*)" - - if ($sa.Length -gt 1) - { - # return Namespace - $sa[1] - - # return Name - $sa[2] - } - else - { - # return Namespace - "" - - # return Name - $sa[0] - } -} - -######################################################### -# GetEntitySetForEntityType is a helper function used -# to fetch EntitySet for a given EntityType by -# searching the inheritance hierarchy in the -# supplied metadata. -######################################################### -function GetEntitySetForEntityType -{ - param - ( - [ODataUtils.Metadata] $metaData, - [ODataUtils.EntityType] $entityType - ) - - # $metaData is already validated at the cmdlet layer. - if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } - - $result = $metaData.EntitySets | Where-Object { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } - - if (($result.Count -eq 0) -and ($null -ne $entityType.BaseType)) - { - GetEntitySetForEntityType $metaData $entityType.BaseType - } - elseif ($result.Count -gt 1) - { - throw ($LocalizedData.WrongCountEntitySet -f (($entityType.Namespace + "." + $entityType.Name), $result.Count)) - } - - $result -} - -######################################################### -# ProcessStreamHelper is a helper function that performs -# the following utility tasks: -# 1. Writes verbose messages to the stream. -# 2. Writes FileInfo objects for the proxy modules -# saved to the disk. This is done to keep the user -# experience in consistent with Export-PSSession. -# 3. Updates progress bar. -######################################################### -function ProcessStreamHelper -{ - param - ( - [string] $verboseMessage, - [string] $progressBarActivityName, - [string] $status, - [double] $previousSegmentWeight, - [double] $currentSegmentWeight, - [int] $totalNumberofEntries, - [int] $currentEntryCount, - [string] $path, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - Write-Verbose -Message $verboseMessage - ProgressBarHelper $progressBarActivityName $status $previousSegmentWeight $currentSegmentWeight $totalNumberofEntries $currentEntryCount - $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $path | Get-Item - if($null -ne $callerPSCmdlet) - { - $callerPSCmdlet.WriteObject($proxyFile) - } -} - -######################################################### -# GetAssociatedType is a helper function used -# to fetch associated instance's EntityType -# for a given Navigation property in the -# supplied metadata. -######################################################### -function GetAssociatedType -{ - param - ( - [ODataUtils.Metadata] $Metadata, - [ODataUtils.NavigationProperty] $navProperty - ) - - # $metaData is already validated at the cmdlet layer. - if($null -eq $navProperty) { throw ($LocalizedData.ArguementNullError -f "NavigationProperty", "GetAssociatedType") } - - $associationName = $navProperty.AssociationName - $association = $Metadata.Associations | Where-Object { $_.Name -eq $associationName } - $associationType = $association.Type - - if ($associationType.Count -lt 1) - { - throw ($LocalizedData.AssociationNotFound -f $associationName) - } - elseif ($associationType.Count -gt 1) - { - throw ($LocalizedData.TooManyMatchingAssociationTypes -f $associationType.Count, $associationName) - } - - if ($associationType.NavPropertyName1 -eq $navProperty.ToRole) - { - $associatedType = $associationType.EndType1 - } - elseif ($associationType.NavPropertyName2 -eq $navProperty.ToRole) - { - $associatedType = $associationType.EndType2 - } - else - { - throw ($LocalizedData.ZeroMatchingAssociationTypes -f $navProperty.ToRole, $association.Name) - } - - # return associated EntityType - $associatedType -} - -######################################################### -# AddParametersNode is a helper function used -# to add parameters to the generated proxy cmdlet, -# based on mandatoryProperties and otherProperties. -# PrefixForKeys is used by associations to append a -# prefix to PowerShell parameter name. -######################################################### -function AddParametersNode -{ - param - ( - [Parameter(Mandatory=$true)] - [System.Xml.XmlWriter] $xmlWriter, - [ODataUtils.TypeProperty[]] $keyProperties, - [ODataUtils.TypeProperty[]] $mandatoryProperties, - [ODataUtils.TypeProperty[]] $otherProperties, - [string] $prefixForKeys, - [boolean] $addForceParameter, - [boolean] $addParametersElement, - [Hashtable] $complexTypeMapping - ) - - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } - - if(($keyProperties.Length -gt 0) -or - ($mandatoryProperties.Length -gt 0) -or - ($otherProperties.Length -gt 0) -or - ($addForceParameter)) - { - if($addParametersElement) - { - $xmlWriter.WriteStartElement('Parameters') - } - - $pos = 0 - - if ($null -ne $keyProperties) - { - $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping - } - - if ($null -ne $mandatoryProperties) - { - $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping - } - - if ($null -ne $otherProperties) - { - $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping - } - - if($addForceParameter) - { - $forceParameter = [ODataUtils.TypeProperty] @{ - "Name" = "Force"; - "TypeName" = "switch"; - "IsNullable" = $false - } - - $pos = AddParametersCDXML $xmlWriter $forceParameter $pos $false $null $null $complexTypeMapping - } - - if($addParametersElement) - { - $xmlWriter.WriteEndElement() - } - } -} - -######################################################### -# AddParametersNode is a helper function used -# to add Parameter node to CDXML based on properties. -# Prefix is appended to PS parameter names, used for -# associations. Suffix is appended to all parameter -# names, for ex. to differentiate keys. returns new $pos -######################################################### -function AddParametersCDXML -{ - param - ( - [Parameter(Mandatory=$true)] - [System.Xml.XmlWriter] $xmlWriter, - [ODataUtils.TypeProperty[]] $properties, - [Parameter(Mandatory=$true)] - [int] $pos, - [bool] $isMandatory, - [string] $prefix, - [string] $suffix, - [Hashtable] $complexTypeMapping - ) - - $properties | Where-Object { $null -ne $_ } | ForEach-Object { - $xmlWriter.WriteStartElement('Parameter') - $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $prefix + $_.Name) - $xmlWriter.WriteAttributeString('IsMandatory', ($isMandatory).ToString().ToLowerInvariant()) - $xmlWriter.WriteAttributeString('Position', $pos) - if($isMandatory) - { - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - } - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - $pos++ - } - - $pos -} - -######################################################### -# GenerateComplexTypeDefinition is a helper function used -# to generate complex type definition from the metadata. -######################################################### -function GenerateComplexTypeDefinition -{ - param - ( - [ODataUtils.Metadata] $metaData, - [string] $metaDataUri, - [string] $OutputModule, - [string] $typeDefinitionFileName, - [string] $cmdletAdapter, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - #metadataUri, $OutputModule & $cmdletAdapter are already validated at the cmdlet layer. - if($null -eq $typeDefinationFileName) { throw ($LocalizedData.ArguementNullError -f "TypeDefinationFileName", "GenerateComplexTypeDefination") } - if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateComplexTypeDefination") } - if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateComplexTypeDefination") } - - $Path = "$OutputModule\$typeDefinitionFileName" - - # We are currently generating classes for EntityType & ComplexType - # definition exposed in the metadata. - $typesToBeGenerated = $metaData.EntityTypes+$metadata.ComplexTypes - - if($null -ne $typesToBeGenerated -and $typesToBeGenerated.Count -gt 0) - { - $complexTypeMapping = @{} - $entityTypeNameSpaceMapping = @{} - - foreach ($entityType in $typesToBeGenerated) - { - if ($null -ne $entityType) - { - $entityTypeFullName = $entityType.Namespace + '.' + $entityType.Name - if(!$complexTypeMapping.ContainsKey($entityTypeFullName)) - { - $complexTypeMapping.Add($entityTypeFullName, $entityType.Name) - } - - if(!$entityTypeNameSpaceMapping.ContainsKey($entityType.Namespace)) - { - $entityTypes = @() - $entityTypeNameSpaceMapping.Add($entityType.Namespace, $entityTypes) - } - - $entityTypeNameSpaceMapping[$entityType.Namespace] += $entityType - } - } - - if($entityTypeNameSpaceMapping.Count -gt 0) - { -$output = @" -`$typeDefinitions = @" -using System; -using System.Management.Automation; - -"@ - - foreach($currentNameSpace in $entityTypeNameSpaceMapping.Keys) - { - $entityTypes = $entityTypeNameSpaceMapping[$currentNameSpace] - - $output += "`r`nnamespace $(ValidateComplexTypeIdentifier $currentNameSpace $true $metaDataUri $callerPSCmdlet)`r`n{" - - foreach ($entityType in $entityTypes) - { - $entityTypeFullName = (ValidateComplexTypeIdentifier $entityType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + $entityType.Name - Write-Verbose ($LocalizedData.VerboseAddingTypeDefinationToGeneratedModule -f $entityTypeFullName, "$OutputModule\$typeDefinationFileName") - - if($null -ne $entityType.BaseType) - { - $entityBaseFullName = (ValidateComplexTypeIdentifier $entityType.BaseType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + (ValidateComplexTypeIdentifier $entityType.BaseType.Name $false $metaDataUri $callerPSCmdlet) - $output += "`r`n public class $(ValidateComplexTypeIdentifier $entityType.Name $false $metaDataUri $callerPSCmdlet) : $($entityBaseFullName)`r`n {" - } - else - { - $output += "`r`n public class $(ValidateComplexTypeIdentifier $entityType.Name $false $metaDataUri $callerPSCmdlet)`r`n {" - } - - $properties = $null - - for($index = 0; $index -lt $entityType.EntityProperties.Count; $index++) - { - $property = $entityType.EntityProperties[$index] - $typeName = Convert-ODataTypeToCLRType $property.TypeName $complexTypeMapping - $properties += "`r`n public $typeName $(ValidateComplexTypeIdentifier $property.Name $false $metaDataUri $callerPSCmdlet);" - } - - # Navigation properties are treated like any other property for NetworkController scenario. - if ($cmdletAdapter -eq "NetworkControllerAdapter") - { - for($index = 0; $index -lt $entityType.NavigationProperties.Count; $index++) - { - $property = $entityType.NavigationProperties[$index] - $navigationTypeName = GetNavigationPropertyTypeName $property $metaData - $typeName = Convert-ODataTypeToCLRType $navigationTypeName $complexTypeMapping - $properties += "`r`n public $typeName $(ValidateComplexTypeIdentifier $property.Name $false $metaDataUri $callerPSCmdlet);" - } - } - - $output += $properties - $output += "`r`n }`r`n" - } - - $output += "}`r`n" - } - $output += """@`r`n" - - $output += "Add-Type -TypeDefinition `$typeDefinitions `r`n" - $output | Out-File -FilePath $Path - Write-Verbose ($LocalizedData.VerboseSavedTypeDefinationModule -f $typeDefinationFileName, $OutputModule) - } - } - - return $complexTypeMapping -} - -# Creating a single instance of CSharpCodeProvider that would be used -# for Identifier validation in the ValidateComplexTypeIdentifier helper method. -$cSharpCodeProvider = [Microsoft.CSharp.CSharpCodeProvider]::new() - -######################################################### -# ValidateComplexTypeIdentifier is a helper function to -# make sure that the type names defined in the -# metadata are valid C# Identifier names. This validation -# is performed to make sure that there are no security -# threat from importing the generated complex type -# (which is created using the metadata file). -# This method return the identifier name if its a -# valid identifier, else a terminating error in thrown. -######################################################### -function ValidateComplexTypeIdentifier -{ - param - ( - [string] $identifierName, - [bool] $isNameSpaceName, - [string] $metaDataUri, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ValidateComplexTypeIdentifier") } - - if($isNameSpaceName) - { - $independentIdentifiers = $identifierName.Split('.') - $result = $true - foreach($currentIdentifier in $independentIdentifiers) - { - if(![System.CodeDom.Compiler.CodeGenerator]::IsValidLanguageIndependentIdentifier($currentIdentifier)) - { - $result = $false - break - } - } - } - else - { - $result = $cSharpCodeProvider.IsValidIdentifier($identifierName) - } - - if(!$result) - { - $errorMessage = ($LocalizedData.InValidIdentifierInMetadata -f $metaDataUri, $identifierName) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidIdentifier" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidData) $null $identifierName - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - else - { - return $identifierName - } -} - -######################################################### -# GetKeys is a helper function used to -# return the keys for the entity if customUri -# is specified. -######################################################### -function GetKeys -{ - param - ( - [ODataUtils.EntitySet] $entitySet, - [string] $customUri, - [string] $actionName - ) - - # Get the original keys - $key = (GetAllProperties $entitySet.Type) | Where-Object { $_.IsKey } - - # Get the keys with delimiters - $keys = $customUri -split "/" | ForEach-Object { - if ($_ -match '{*}') - { - [ODataUtils.TypeProperty] @{ - "Name" = $_.Substring($_.IndexOf('{')+1,$_.IndexOf('}')-$_.IndexOf('{')-1); - "TypeName" = "Edm.String"; - "IsNullable" = $false; - "IsMandatory" = $true; - } - } - elseif ($_ -match '\[*\]') - { - if ($ActionName -eq 'Get') { - [ODataUtils.TypeProperty] @{ - "Name" = $_.Substring($_.IndexOf('[')+1,$_.IndexOf(']')-$_.IndexOf('[')-1); - "TypeName" = "Edm.String"; - "IsNullable" = $false; - "IsMandatory" = $false; - } - } - else { - [ODataUtils.TypeProperty] @{ - "Name" = $_.Substring($_.IndexOf('[')+1,$_.IndexOf(']')-$_.IndexOf('[')-1); - "TypeName" = "Edm.String"; - "IsNullable" = $false; - "IsMandatory" = $true; - } - } - } - } - - # Now combine the two keys and avoid duplication - # Make a list of names already present in the new keys - # Foreach old key check if that key is present in the new keyList - # Else add the key to new key list - $keyParams = $keys | ForEach-Object {$_.Name} - - if ($null -eq $keyParams -Or $keyParams.Count -eq 0) { - $keys = $key - } - else { - if ($keyParams.Count -eq 1) { - $keys = @($keys) - } - - $key | ForEach-Object { - if ($keyParams.Contains($_.Name) -eq $false) - { - $keys += $_ - } - } - } - - $keys -} - -######################################################### -# GetNetworkControllerAdditionalProperties is a helper -# function used to fetch network controller specific -# additional properties. -######################################################### -function GetNetworkControllerAdditionalProperties -{ - param - ( - $navigationProperties, - $metaData - ) - - # Additional properties contains the types present as navigation properties - - $additionalProperties = $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { - $typeName = GetNavigationPropertyTypeName $_ $metaData - - if ($_.Name -eq "Properties") { - $isNullable = $false - } - else { - $isNullable = $true - } - - [ODataUtils.TypeProperty] @{ - "Name" = $_.Name; - "TypeName" = $typeName - "IsNullable" = $isNullable; - } - } - - # Add etag to the additionalProperties - - if ($null -ne $additionalProperties) - { - if ($additionalProperties.Count -eq 1) { - $additionalProperties = @($additionalProperties) - } - - $additionalProperties += [ODataUtils.TypeProperty] @{ - "Name" = "Etag"; - "TypeName" = "Edm.String"; - "IsNullable" = $true; - } - } - else - { - $additionalProperties = [ODataUtils.TypeProperty] @{ - "Name" = "Etag"; - "TypeName" = "Edm.String"; - "IsNullable" = $true; - } - } - - $additionalProperties -} - -######################################################### -# UpdateNetworkControllerSpecificProperties is a -# helper function used to append additionalProperties -# to nullable/nonNullable Properties. This is network controller -# specific logic. -######################################################### -function UpdateNetworkControllerSpecificProperties -{ - param - ( - $nullableProperties, - $additionalProperties, - $keyProperties, - $isNullable - ) - - if ($isNullable) { - $additionalProperties = $additionalProperties | Where-Object { $_.isNullable } - } - else { - $additionalProperties = $additionalProperties | Where-Object { -not $_.isNullable } - } - - if ($null -eq $nullableProperties) - { - $nullableProperties = $additionalProperties - } - else { - if ($nullableProperties.Count -eq 1) { - $nullableProperties = @($nullableProperties) - } - if ($null -ne $additionalProperties) { - $nullableProperties += $additionalProperties - } - } - - if ($null -ne $nullableProperties -And $null -ne $keyProperties) - { - if ($keyProperties.Count -eq 1) { - $keyProperties = @($keyProperties) - } - - $keys = $keyProperties | ForEach-Object {$_.Name} - - if ($keys.Count -eq 1) { - $keys = @($keys) - } - - $nullableProperties = $nullableProperties | Where-Object {$keys.Contains($_.Name) -eq $false} - } - - $nullableProperties -} - -######################################################### -# GetNavigationPropertyTypeName is a -# helper function used to fetch the type corresponding -# to navigation property in this metadata. This is -# network controller specific logic. -######################################################### -function GetNavigationPropertyTypeName -{ - param - ( - $navigationProperty, - $metaData - ) - - foreach($association in $metaData.Associations) - { - if ($association.Name -ne $navigationProperty.AssociationName -Or $association.Namespace -ne $navigationProperty.AssociationNamespace) - { - continue - } - - # Now get the type for this association - - if ($association.Type.NavPropertyName1 -eq $navigationProperty.Name) - { - $type = $association.Type.EndType1 - $multiplicity = $association.Type.Multiplicity1 - } - elseif ($associationType.NavPropertyName2 -eq $navigationProperty.Name) - { - $type = $association.Type.EndType2 - $multiplicity = $association.Type.Multiplicity2 - } - - break - } - - $fullName = $type.Namespace + '.' + $type.Name - - # Check the multiplicity and convert to array if needed - if ($multiplicity -eq "*") - { - $fullName = "Collection($fullName)" - } - - $fullName -} +Import-LocalizedData LocalizedData -FileName Microsoft.PowerShell.ODataUtilsStrings.psd1 + + +# Add .NET classes used by the module +Add-Type -TypeDefinition $global:BaseClassDefinitions + +######################################################### +# Generates PowerShell module containing client side +# proxy cmdlets that can be used to interact with an +# OData based server side endpoint. +######################################################### +function ExportODataEndpointProxy +{ + param + ( + [string] $Uri, + [string] $OutputModule, + [string] $MetadataUri, + [PSCredential] $Credential, + [string] $CreateRequestMethod, + [string] $UpdateRequestMethod, + [string] $CmdletAdapter, + [Hashtable] $ResourceNameMapping, + [switch] $Force, + [Hashtable] $CustomData, + [switch] $AllowClobber, + [switch] $AllowUnsecureConnection, + [Hashtable] $Headers, + [string] $ProgressBarStatus, + [System.Management.Automation.PSCmdlet] $PSCmdlet + ) + + [xml] $metadataXML = GetMetaData $MetadataUri $PSCmdlet $Credential $Headers + + [ODataUtils.Metadata] $metaData = ParseMetadata $metadataXML $MetadataUri $CmdletAdapter $PSCmdlet + + VerifyMetaData $MetadataUri $metaData $AllowClobber.IsPresent $PSCmdlet $progressBarStatus $CmdletAdapter $CustomData $ResourceNameMapping + + GenerateClientSideProxyModule $metaData $MetadataUri $Uri $OutputModule $CreateRequestMethod $UpdateRequestMethod $CmdletAdapter $ResourceNameMapping $CustomData $ProgressBarStatus $PSCmdlet +} + +######################################################### +# ParseMetaData is a helper function used to parse the +# metadata to convert it in to an object structure for +# further consumption during proxy generation. +######################################################### +function ParseMetaData +{ + param + ( + [xml] $metadataXml, + [string] $metaDataUri, + [string] $cmdletAdapter, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + # $metaDataUri is already validated at the cmdlet layer. + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ParseMetadata") } + + if($null -eq $metadataXml) + { + $errorMessage = ($LocalizedData.InValidXmlInMetadata -f $metaDataUri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadataUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + Write-Verbose $LocalizedData.VerboseParsingMetadata + + # Check the OData version in the fetched metadata to make sure that + # OData version (and hence the protocol) used in the metadata is + # supported by the adapter used for executing the generated + # proxy cmdlets. + if(($null -ne $metadataXML) -and ($null -ne $metadataXML.Edmx)) + { + if($null -eq $metadataXML.Edmx.Version) + { + $errorMessage = ($LocalizedData.ODataVersionNotFound -f $MetadataUri) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyODataVersionNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + $metaDataVersion = New-Object -TypeName System.Version -ArgumentList @($metadataXML.Edmx.Version) + + # When we support plug-in model, We would have to fetch the + # $minSupportedVersionString & $maxSupportedVersionString + # from the plug-in instead of using an hardcoded value. + $minSupportedVersionString = '1.0' + $maxSupportedVersionString = '3.0' + $minSupportedVersion = New-Object -TypeName System.Version -ArgumentList @($minSupportedVersionString) + $maxSupportedVersion = New-Object -TypeName System.Version -ArgumentList @($maxSupportedVersionString) + + $minVersionComparisonResult = $minSupportedVersion.CompareTo($metaDataVersion) + $maxVersionComparisonResult = $maxSupportedVersion.CompareTo($metaDataVersion) + + if(-not($minVersionComparisonResult -lt $maxVersionComparisonResult)) + { + $errorMessage = ($LocalizedData.ODataVersionNotSupported -f $metadataXML.Edmx.Version, $MetadataUri, $minSupportedVersionString, $maxSupportedVersionString, $CmdletAdapter) + $exception = [System.NotSupportedException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyODataVersionNotSupported" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + else + { + $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + foreach ($schema in $MetadataXML.Edmx.DataServices.Schema) + { + if (($null -ne $schema) -and [string]::IsNullOrEmpty($schema.NameSpace )) + { + $callerPSCmdlet = $callerPSCmdlet -as [System.Management.Automation.PSCmdlet] + $errorMessage = ($LocalizedData.InValidSchemaNamespace -f $metaDataUri) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidSchemaNamespace" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + + $metaData = New-Object -TypeName ODataUtils.Metadata + + # this is a processing queue for those types that require base types that haven't been defined yet + $entityAndComplexTypesQueue = @{} + + foreach ($schema in $metadataXml.Edmx.DataServices.Schema) + { + if ($null -eq $schema) + { + Write-Error $LocalizedData.EmptySchema + continue + } + + if ($null -eq $metadata.Namespace) + { + $metaData.Namespace = $schema.Namespace + } + + foreach ($entityType in $schema.EntityType) + { + $baseType = $null + + if ($null -ne $entityType.BaseType) + { + # add it to the processing queue + $baseType = GetBaseType $entityType $metaData + if ($null -eq $baseType) + { + $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='EntityType'; value=$entityType}) + continue + } + } + + [ODataUtils.EntityType] $newType = ParseMetadataTypeDefinition $entityType $baseType $metaData $schema.Namespace $true + $metaData.EntityTypes += $newType + AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $schema.Namespace + } + + foreach ($complexType in $schema.ComplexType) + { + $baseType = $null + + if ($null -ne $complexType.BaseType) + { + # add it to the processing queue + $baseType = GetBaseType $complexType $metaData + if ($null -eq $baseType) + { + $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='ComplexType'; value=$complexType}) + continue + } + } + + [ODataUtils.EntityType] $newType = ParseMetadataTypeDefinition $complexType $baseType $metaData $schema.Namespace $false + $metaData.ComplexTypes += $newType + AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $schema.Namespace + } + } + + foreach ($schema in $metadataXml.Edmx.DataServices.Schema) + { + foreach ($entityContainer in $schema.EntityContainer) + { + if ($entityContainer.IsDefaultEntityContainer) + { + $metaData.DefaultEntityContainerName = $entityContainer.Name + } + + $entityTypeToEntitySetMapping = @{}; + foreach ($entitySet in $entityContainer.EntitySet) + { + $entityType = $metaData.EntityTypes | Where-Object { $_.Name -eq $entitySet.EntityType.Split('.')[-1] } + $entityTypeName = $entityType.Name + + if($entityTypeToEntitySetMapping.ContainsKey($entityTypeName)) + { + $existingEntitySetName = $entityTypeToEntitySetMapping[$entityTypeName] + + $errorMessage = ($LocalizedData.EntityNameConflictError -f $metaDataUri, $existingEntitySetName, $entitySet.Name, $entityTypeName) + $exception = [System.NotSupportedException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyEntityTypeMappingError" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + else + { + $entityTypeToEntitySetMapping.Add($entityTypeName, $entitySet.Name) + } + + $newEntitySet = [ODataUtils.EntitySet] @{ + "Namespace" = $schema.Namespace; + "Name" = $entitySet.Name; + "Type" = $entityType; + } + + $metaData.EntitySets += $newEntitySet + } + } + } + + foreach ($schema in $metadataXml.Edmx.DataServices.Schema) + { + foreach ($association in $schema.Association) + { + $newAssociationType = [ODataUtils.AssociationType] @{ + "Namespace" = $schema.Namespace; + "EndType1" = $metaData.EntityTypes | Where-Object { $_.Name -eq $association.End[0].Type.Split('.')[-1] }; + "NavPropertyName1" = $association.End[0].Role; + "Multiplicity1" = $association.End[0].Multiplicity; + + "EndType2" = $metaData.EntityTypes | Where-Object { $_.Name -eq $association.End[1].Type.Split('.')[-1] }; + "NavPropertyName2" = $association.End[1].Role; + "Multiplicity2" = $association.End[1].Multiplicity; + } + + $newAssociation = [ODataUtils.AssociationSet] @{ + "Namespace" = $schema.Namespace; + "Name" = $association.Name; + "Type" = $newAssociationType; + } + + $metaData.Associations += $newAssociation + } + } + + foreach ($schema in $metadataXml.Edmx.DataServices.Schema) + { + foreach ($action in $schema.EntityContainer.FunctionImport) + { + # HttpMethod is only used for legacy Service Operations + if ($null -eq $action.HttpMethod) + { + if ($null -ne $action.IsSideEffecting) + { + $isSideEffecting = $action.IsSideEffecting + } + else + { + $isSideEffecting = $true + } + + $newAction = [ODataUtils.Action] @{ + "Namespace" = $schema.Namespace; + "Verb" = $action.Name; + "IsSideEffecting" = $isSideEffecting; + "IsBindable" = $action.IsBindable; + # we don't care about IsAlwaysBindable, since we populate actions information from $metaData + # so we can't know the state of the entity + } + + # Actions are always SideEffecting, otherwise it's an OData function + if ($newAction.IsSideEffecting -ne $false) + { + foreach ($parameter in $action.Parameter) + { + if ($null -ne $parameter.Nullable) + { + $parameterIsNullable = [System.Convert]::ToBoolean($parameter.Nullable); + } + + $newParameter = [ODataUtils.TypeProperty] @{ + "Name" = $parameter.Name; + "TypeName" = $parameter.Type; + "IsNullable" = $parameterIsNullable + } + + $newAction.Parameters += $newParameter + } + + # IsBindable means it operates on Entity/ies + if ($newAction.IsBindable) + { + $regex = "Collection\((.+)\)" + + if ($newAction.Parameters[0].TypeName -match $regex) + { + # action operating on a collection of entities + $insideTypeName = Convert-ODataTypeToCLRType $Matches[1] + + $newAction.EntitySet = $metaData.EntitySets | Where-Object { ($_.Type.Namespace + "." + $_.Type.Name) -eq $insideTypeName } + $newAction.IsSingleInstance = $false + } + else + { + # actions operating on a single instance + $newAction.EntitySet = $metaData.EntitySets | Where-Object { ($_.Type.Namespace + "." + $_.Type.Name) -eq $newAction.Parameters[0].TypeName } + + $newAction.IsSingleInstance = $true + } + } + + $metaData.Actions += $newAction + } + } + } + } + + $metaData +} + +######################################################### +# VerifyMetaData is a helper function used to validate +# the processed metadata to make sure client side proxy +# can be created for the supplied metadata. +######################################################### +function VerifyMetaData +{ + param + ( + [string] $metaDataUri, + [ODataUtils.Metadata] $metaData, + [boolean] $allowClobber, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet, + [string] $progressBarStatus, + [string] $cmdletAdapter, + [Hashtable] $customData, + [Hashtable] $resourceNameMapping + ) + + # $metaDataUri & $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "VerifyMetaData") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } + + Write-Verbose $LocalizedData.VerboseVerifyingMetadata + + if ($metadata.EntitySets.Count -le 0) + { + $errorMessage = ($LocalizedData.NoEntitySets -f $metaDataUri) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + if ($metadata.EntityTypes.Count -le 0) + { + $errorMessage = ($LocalizedData.NoEntityTypes -f $metaDataUri) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + # All the generated proxy cmdlets would have the following parameters added. + # The ODataAdapter has the default implementation on how to handle the + # scenario when these parameters are used during proxy invocations. + # The default implementation can be overridden using adapter derivation model. + $reservedProperties = @("Filter", "IncludeTotalResponseCount", "OrderBy", "Select", "Skip", "Top", "ConnectionUri", "CertificateThumbprint", "Credential") + $validEntitySets = @() + $sessionCommands = Get-Command -All + + foreach ($entitySet in $metaData.EntitySets) + { + if ($null -eq $entitySet.Type) + { + $errorMessage = ($LocalizedData.EntitySetUndefinedType -f $metaDataUri, $entitySet.Name) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetaDataUri" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $metaDataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + if ($cmdletAdapter -eq "NetworkControllerAdapter" -And $customData -And $customData.Contains($entitySet.Name) -eq $false) + { + continue + } + + $hasConflictingProperty = $false + $hasConflictingCommand = $false + + $entityAndNavigationProperties = (GetAllProperties $entitySet.Type) + (GetAllProperties $entitySet.Type -IncludeOnlyNavigationProperties) + foreach($entityProperty in $entityAndNavigationProperties) + { + if($reservedProperties.Contains($entityProperty.Name)) + { + $hasConflictingProperty = $true + if(!$allowClobber) + { + # Write Error message and skip current Entity Set. + $errorMessage = ($LocalizedData.SkipEntitySetProxyCreation -f $entitySet.Name, $entitySet.Type.Name, $entityProperty.Name) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointDefaultPropertyCollision" $null ([System.Management.Automation.ErrorCategory]::InvalidOperation) $exception $metaDataUri + $callerPSCmdlet.WriteError($errorRecord) + } + else + { + $warningMessage = ($LocalizedData.EntitySetProxyCreationWithWarning -f $entitySet.Name, $entityProperty.Name, $entitySet.Type.Name) + $callerPSCmdlet.WriteWarning($warningMessage) + } + } + } + + foreach($currentCommand in $sessionCommands) + { + # The generated command Noun can be set using ResourceNameMapping + $generatedCommandName = $entitySet.Name + if ($resourceNameMapping -And $resourceNameMapping.Contains($entitySet.Name)) { + $generatedCommandName = $resourceNameMapping[$entitySet.Name] + } + + if(($null -ne $currentCommand.Noun -and $currentCommand.Noun -eq $generatedCommandName) -and + ($currentCommand.Verb -eq "Get" -or + $currentCommand.Verb -eq "Set" -or + $currentCommand.Verb -eq "New" -or + $currentCommand.Verb -eq "Remove")) + { + $hasConflictingCommand = $true + VerifyMetadataHelper $LocalizedData.SkipEntitySetConflictCommandCreation ` + $LocalizedData.EntitySetConflictCommandCreationWithWarning ` + $entitySet.Name $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet + } + } + + foreach($currentAction in $metaData.Actions) + { + $actionCommand = "Invoke-" + "$($entitySet.Name)$($currentAction.Verb)" + + foreach($currentCommand in $sessionCommands) + { + if($actionCommand -eq $currentCommand.Name) + { + $hasConflictingCommand = $true + VerifyMetadataHelper $LocalizedData.SkipEntitySetConflictCommandCreation ` + $LocalizedData.EntitySetConflictCommandCreationWithWarning $entitySet.Name ` + $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet + } + } + } + + if(!($hasConflictingProperty -or $hasConflictingCommand)-or $allowClobber) + { + $validEntitySets += $entitySet + } + } + + if ($cmdletAdapter -ne "NetworkControllerAdapter") { + + $metaData.EntitySets = $validEntitySets + + $validServiceActions = @() + $hasConflictingServiceActionCommand = $true + foreach($currentAction in $metaData.Actions) + { + $serviceActionCommand = "Invoke-" + "$($currentAction.Verb)" + + foreach($currentCommand in $sessionCommands) + { + if($serviceActionCommand -eq $currentCommand.Name) + { + $hasConflictingServiceActionCommand = $true + VerifyMetadataHelper $LocalizedData.SkipConflictServiceActionCommandCreation ` + $LocalizedData.ConflictServiceActionCommandCreationWithWarning $entitySet.Name ` + $currentCommand.Name $metaDataUri $allowClobber $callerPSCmdlet + } + } + + if(!$hasConflictingServiceActionCommand -or $allowClobber) + { + $validServiceActions += $currentAction + } + } + + $metaData.Actions = $validServiceActions + } + + # Update Progress bar. + ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 5 20 1 1 +} + +######################################################### +# GenerateClientSideProxyModule is a helper function used +# to generate a PowerShell module that serves as a client +# side proxy for interacting with the server side +# OData endpoint. The proxy module contains proxy cmdlets +# implemented in CDXML modules and they are exposed +# through module manifest as nested modules. +# One CDXML module is created for each EntitySet +# described in the metadata. Each CDXML module contains +# CRUD & Service Action specific proxy cmdlets targeting +# the underlying EntityType. There is 1:M mapping between +# EntitySet & its underlying EntityTypes (i.e., all +# entities with in the single EntitySet will be of the +# same EntityType but there can be multiple entities +# of the same type with in an EntitySet). +######################################################### +function GenerateClientSideProxyModule +{ + param + ( + [ODataUtils.Metadata] $metaData, + [string] $metaDataUri, + [string] $uri, + [string] $outputModule, + [string] $createRequestMethod, + [string] $updateRequestMethod, + [string] $cmdletAdapter, + [Hashtable] $resourceNameMapping, + [Hashtable] $customData, + [string] $progressBarStatus, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } + + # This function performs the following set of tasks + # while creating the client side proxy module: + # 1. If the server side endpoint exposes complex types, + # the client side proxy complex types are created + # as C# class in ComplexTypeDefinitions.psm1 + # 2. Creates proxy cmdlets for CRUD operations. + # 3. Creates proxy cmdlets for Service action operations. + # 4. Creates module manifest. + + Write-Verbose ($LocalizedData.VerboseSavingModule -f $outputModule) + + $typeDefinitionFileName = "ComplexTypeDefinitions.psm1" + $complexTypeMapping = GenerateComplexTypeDefinition $metaData $metaDataUri $outputModule $typeDefinitionFileName $cmdletAdapter $callerPSCmdlet + + ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 20 20 1 1 + + $complexTypeFileDefinitionPath = Join-Path -Path $outputModule -ChildPath $typeDefinitionFileName + + if(Test-Path -Path $complexTypeFileDefinitionPath) + { + $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $complexTypeFileDefinitionPath | Get-Item + if($null -ne $callerPSCmdlet) + { + $callerPSCmdlet.WriteObject($proxyFile) + } + } + + $currentEntryCount = 0 + foreach ($entitySet in $metaData.EntitySets) + { + $currentEntryCount += 1 + if ($cmdletAdapter -eq "NetworkControllerAdapter" -And $customData -And $customData.Contains($entitySet.Name) -eq $false) + { + ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 40 20 $metaData.EntitySets.Count $currentEntryCount + continue + } + + GenerateCRUDProxyCmdlet $entitySet $metaData $uri $outputModule $createRequestMethod $updateRequestMethod $cmdletAdapter $resourceNameMapping $customData $complexTypeMapping "Export-ODataEndpointProxy" $progressBarStatus 40 20 $metaData.EntitySets.Count $currentEntryCount $callerPSCmdlet + } + + GenerateServiceActionProxyCmdlet $metaData $uri "$outputModule\ServiceActions.cdxml" $complexTypeMapping $progressBarStatus $callerPSCmdlet + + $moduleDirInfo = [System.IO.DirectoryInfo]::new($outputModule) + $moduleManifestName = $moduleDirInfo.Name + ".psd1" + GenerateModuleManifest $metaData $outputModule\$moduleManifestName @($typeDefinitionFileName, 'ServiceActions.cdxml') $resourceNameMapping $progressBarStatus $callerPSCmdlet +} + +######################################################### +# GenerateCRUDProxyCmdlet is a helper function used +# to generate Get, Set, New & Remove proxy cmdlet. +# The proxy cmdlet is generated in the CDXML +# compliant format. +######################################################### +function GenerateCRUDProxyCmdlet +{ + param + ( + [ODataUtils.EntitySet] $entitySet, + [ODataUtils.Metadata] $metaData, + [string] $uri, + [string] $outputModule, + [string] $createRequestMethod, + [string] $UpdateRequestMethod, + [string] $cmdletAdapter, + [Hashtable] $resourceNameMapping, + [Hashtable] $customData, + [Hashtable] $complexTypeMapping, + [string] $progressBarActivityName, + [string] $progressBarStatus, + [double] $previousSegmentWeight, + [double] $currentSegmentWeight, + [int] $totalNumberofEntries, + [int] $currentEntryCount, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $entitySet) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } + + $entitySetName = $entitySet.Name + if(($null -ne $resourceNameMapping) -and + $resourceNameMapping.ContainsKey($entitySetName)) + { + $entitySetName = $resourceNameMapping[$entitySetName] + } + else + { + $entitySetName = $entitySet.Type.Name + } + + $Path = "$OutputModule\$entitySetName.cdxml" + + $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) + + if ($null -eq $xmlWriter) + { + throw ($LocalizedData.XmlWriterInitializationError -f $entitySet.Name) + } + + $xmlWriter = SaveCDXMLHeader $xmlWriter $uri $entitySet.Name $entitySetName $cmdletAdapter + + # Get the keys depending on whether the url contains variables or not + if ($CmdletAdapter -ne "NetworkControllerAdapter") + { + $keys = (GetAllProperties $entitySet.Type) | Where-Object { $_.IsKey } + } + else + { + $name = $entitySet.Name + $keys = GetKeys $entitySet $customData.$name 'Get' + } + + $navigationProperties = GetAllProperties $entitySet.Type -IncludeOnlyNavigationProperties + + GenerateGetProxyCmdlet $xmlWriter $metaData $keys $navigationProperties $cmdletAdapter $complexTypeMapping + + $nonKeyProperties = (GetAllProperties $entitySet.Type) | Where-Object { -not $_.isKey } + $nullableProperties = $nonKeyProperties | Where-Object { $_.isNullable } + $nonNullableProperties = $nonKeyProperties | Where-Object { -not $_.isNullable } + + $xmlWriter.WriteStartElement('StaticCmdlets') + + $keyProperties = $keys + + # Do operations specifically needed for NetworkController cmdlets + if ($CmdletAdapter -eq "NetworkControllerAdapter") + { + $keyProperties = GetKeys $entitySet $customData.$name 'New' + $additionalProperties = GetNetworkControllerAdditionalProperties $navigationProperties $metaData + $nullableProperties = UpdateNetworkControllerSpecificProperties $nullableProperties $additionalProperties $keyProperties $true + $nonNullableProperties = UpdateNetworkControllerSpecificProperties $nonNullableProperties $additionalProperties $keyProperties $false + } + + GenerateNewProxyCmdlet $xmlWriter $metaData $keyProperties $nonNullableProperties $nullableProperties $navigationProperties $cmdletAdapter $complexTypeMapping + + if ($CmdletAdapter -ne "NetworkControllerAdapter") + { + GenerateSetProxyCmdlet $xmlWriter $keyProperties $nonKeyProperties $complexTypeMapping + } + + if ($CmdletAdapter -eq "NetworkControllerAdapter") + { + $keyProperties = GetKeys $entitySet $customData.$name 'Remove' + } + + GenerateRemoveProxyCmdlet $xmlWriter $metaData $keyProperties $navigationProperties $cmdletAdapter $complexTypeMapping + + $entityActions = $metaData.Actions | Where-Object { ($_.EntitySet.Namespace -eq $entitySet.Namespace) -and ($_.EntitySet.Name -eq $entitySet.Name) } + + if ($entityActions.Length -gt 0) + { + foreach($action in $entityActions) + { + $xmlWriter = GenerateActionProxyCmdlet $xmlWriter $metaData $action $entitySet.Name $true $keys $complexTypeMapping + } + } + + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('CmdletAdapterPrivateData') + + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', 'EntityTypeName') + $xmlWriter.WriteString("$($entitySet.Type.Namespace).$($entitySet.Type.Name)") + $xmlWriter.WriteEndElement() + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', 'EntitySetName') + $xmlWriter.WriteString("$($entitySet.Namespace).$($entitySet.Name)") + $xmlWriter.WriteEndElement() + + # Add the customUri to privateData + if ($CmdletAdapter -eq "NetworkControllerAdapter") + { + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', "CustomUriSuffix") + $xmlWriter.WriteString($CustomData.$name) + $xmlWriter.WriteEndElement() + } + + # Add CreateRequestMethod and UpdateRequestMethod to privateData + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', 'CreateRequestMethod') + $xmlWriter.WriteString("$CreateRequestMethod") + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', 'UpdateRequestMethod') + $xmlWriter.WriteString("$UpdateRequestMethod") + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteEndElement() + + SaveCDXMLFooter $xmlWriter + + ProcessStreamHelper ($LocalizedData.VerboseSavedCDXML -f $($entitySetName), $Path) $progressBarActivityName $progressBarStatus $previousSegmentWeight $currentSegmentWeight $totalNumberofEntries $currentEntryCount $Path $callerPSCmdlet +} + +######################################################### +# GenerateGetProxyCmdlet is a helper function used +# to generate Get-* proxy cmdlet. The proxy cmdlet is +# generated in the CDXML compliant format. +######################################################### +function GenerateGetProxyCmdlet +{ + param + ( + [System.XMl.XmlTextWriter] $xmlWriter, + [ODataUtils.Metadata] $metaData, + [object[]] $keys, + [object[]] $navigationProperties, + [string] $cmdletAdapter, + [Hashtable] $complexTypeMapping + ) + + # $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateGetProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateGetProxyCmdlet") } + + $xmlWriter.WriteStartElement('InstanceCmdlets') + $xmlWriter.WriteStartElement('GetCmdletParameters') + $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') + + # adding key parameters and association parameters to QueryableProperties, each in a different parameter set + # to be used by GET cmdlet + if (($null -ne $keys -and $keys.Length -gt 0) -or (($null -ne $navigationProperties -and $navigationProperties.Length -gt 0) -and $cmdletAdapter -ne "NetworkControllerAdapter")) + { + $xmlWriter.WriteStartElement('QueryableProperties') + $position = 0 + + $keys | Where-Object { $null -ne $_ } | ForEach-Object { + $xmlWriter.WriteStartElement('Property') + $xmlWriter.WriteAttributeString('PropertyName', $_.Name) + + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('RegularQuery') + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $_.Name) + $xmlWriter.WriteAttributeString('CmdletParameterSets', 'Default') + $xmlWriter.WriteAttributeString('IsMandatory', $_.IsMandatory.ToString().ToLower()) + $xmlWriter.WriteAttributeString('Position', $position) + if($_.IsMandatory) + { + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + } + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + $position++ + } + + # This behaviour is different for NetworkController specific cmdlets. + if ($CmdletAdapter -ne "NetworkControllerAdapter") + { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { + $associatedType = GetAssociatedType $metaData $_ + $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType + $nvgProperty = $_ + + (GetAllProperties $associatedType) | Where-Object { $_.IsKey } | ForEach-Object { + $xmlWriter.WriteStartElement('Property') + $xmlWriter.WriteAttributeString('PropertyName', $associatedEntitySet.Name + ':' + $_.Name + ':Key') + + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('RegularQuery') + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', 'Associated' + $nvgProperty.Name + $_.Name) + $xmlWriter.WriteAttributeString('CmdletParameterSets', $nvgProperty.AssociationName) + $xmlWriter.WriteAttributeString('IsMandatory', 'true') + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + } + } + + + # Add Query Parameters (i.e., Top, Skip, OrderBy, Filter) to the generated Get-* cmdlets. + $queryParameters = + @{ + "Filter" = "Edm.String"; + "IncludeTotalResponseCount" = "switch"; + "OrderBy" = "Edm.String"; + "Select" = "Edm.String"; + "Skip" = "Edm.Int32"; + "Top" = "Edm.Int32"; + } + + foreach($currentQueryParameter in $queryParameters.Keys) + { + $xmlWriter.WriteStartElement('Property') + $xmlWriter.WriteAttributeString('PropertyName', "QueryOption:" + $currentQueryParameter) + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $queryParameters[$currentQueryParameter] + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + $xmlWriter.WriteStartElement('RegularQuery') + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $currentQueryParameter) + + if($queryParameters[$currentQueryParameter] -eq "Edm.String") + { + $xmlWriter.WriteStartElement('ValidateNotNullOrEmpty') + $xmlWriter.WriteEndElement() + } + + if($queryParameters[$currentQueryParameter] -eq "Edm.Int32") + { + $minValue = 1 + # For Skip Query parameter we want to support 0 as the + # minimum skip value in order to support client side paging. + if($currentQueryParameter -eq 'Skip') + { + $minValue = 0 + } + $xmlWriter.WriteStartElement('ValidateRange') + $xmlWriter.WriteAttributeString('Min', $minValue) + $xmlWriter.WriteAttributeString('Max', [int]::MaxValue) + $xmlWriter.WriteEndElement() + } + + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + } + } + + $xmlWriter.WriteEndElement() + } + + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('GetCmdlet') + $xmlWriter.WriteStartElement('CmdletMetadata') + $xmlWriter.WriteAttributeString('Verb', 'Get') + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteEndElement() +} + +######################################################### +# GenerateNewProxyCmdlet is a helper function used +# to generate New-* proxy cmdlet. The proxy cmdlet is +# generated in the CDXML compliant format. +######################################################### +function GenerateNewProxyCmdlet +{ + param + ( + [System.XMl.XmlTextWriter] $xmlWriter, + [ODataUtils.Metadata] $metaData, + [object[]] $keyProperties, + [object[]] $nonNullableProperties, + [object[]] $nullableProperties, + [object[]] $navigationProperties, + [string] $cmdletAdapter, + [Hashtable] $complexTypeMapping + ) + + # $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateNewProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateNewProxyCmdlet") } + + $xmlWriter.WriteStartElement('Cmdlet') + $xmlWriter.WriteStartElement('CmdletMetadata') + $xmlWriter.WriteAttributeString('Verb', 'New') + $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') + $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', 'Create') + $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') + + AddParametersNode $xmlWriter $keyProperties $nonNullableProperties $nullableProperties $null $true $true $complexTypeMapping + $xmlWriter.WriteEndElement() + + # This behaviour is different for NetworkControllerCmdlets + if ($CmdletAdapter -ne "NetworkControllerAdapter") + { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { + $associatedType = GetAssociatedType $metaData $_ + $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', "Association:Create:$($associatedEntitySet.Name)") + $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) + + $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) + + AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping + $xmlWriter.WriteEndElement() + } + } + + $xmlWriter.WriteEndElement() +} + +######################################################### +# GenerateRemoveProxyCmdlet is a helper function used +# to generate Remove-* proxy cmdlet. The proxy cmdlet is +# generated in the CDXML compliant format. +######################################################### +function GenerateRemoveProxyCmdlet +{ + param + ( + + [System.XMl.XmlTextWriter] $xmlWriter, + [ODataUtils.Metadata] $metaData, + [object[]] $keyProperties, + [object[]] $navigationProperties, + [string] $cmdletAdapter, + [Hashtable] $complexTypeMapping + ) + + # $metaData, $cmdletAdapter & $cmdletAdapter are already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateRemoveProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateRemoveProxyCmdlet") } + + $xmlWriter.WriteStartElement('Cmdlet') + $xmlWriter.WriteStartElement('CmdletMetadata') + $xmlWriter.WriteAttributeString('Verb', 'Remove') + $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') + $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', 'Delete') + $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') + + # This behaviour is different for NetworkControllerCmdlets + if ($CmdletAdapter -eq "NetworkControllerAdapter") + { + # Add etag for NetworkControllerCmdlets + $otherProperties = @([ODataUtils.TypeProperty] @{ + "Name" = "Etag"; + "TypeName" = "Edm.String"; + "IsNullable" = $true; + }) + + AddParametersNode $xmlWriter $keyProperties $null $otherProperties $null $true $true $complexTypeMapping + } + else + { + AddParametersNode $xmlWriter $keyProperties $null $null $null $true $true $complexTypeMapping + } + + $xmlWriter.WriteEndElement() + + # This behaviour is different for NetworkControllerCmdlets + if ($CmdletAdapter -ne "NetworkControllerAdapter") + { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { + + $associatedType = GetAssociatedType $metaData $_ + $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', "Association:Delete:$($associatedEntitySet.Name)") + $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) + + $associatedType = GetAssociatedType $metaData $_ + $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) + + AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping + $xmlWriter.WriteEndElement() + } + } + $xmlWriter.WriteEndElement() +} + +######################################################### +# GenerateActionProxyCmdlet is a helper function used +# to generate Invoke-* proxy cmdlet. These proxy cmdlets +# support Instance/Service level actions. They are +# generated in the CDXML compliant format. +######################################################### +function GenerateActionProxyCmdlet +{ + param + ( + [System.Xml.XmlWriter] $xmlWriter, + [ODataUtils.Metadata] $metaData, + [ODataUtils.Action] $action, + [string] $noun, + [bool] $isInstanceAction, + [ODataUtils.TypeProperty] $keys, + [Hashtable] $complexTypeMapping + ) + + # $metaData is already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateActionProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateActionProxyCmdlet") } + if($null -eq $action) { throw ($LocalizedData.ArguementNullError -f "Action", "GenerateActionProxyCmdlet") } + if($null -eq $noun) { throw ($LocalizedData.ArguementNullError -f "Noun", "GenerateActionProxyCmdlet") } + + $xmlWriter.WriteStartElement('Cmdlet') + + $xmlWriter.WriteStartElement('CmdletMetadata') + $xmlWriter.WriteAttributeString('Verb', 'Invoke') + $xmlWriter.WriteAttributeString('Noun', "$($noun)$($action.Verb)") + $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', "Action:$($action.Verb):$($action.EntitySet.Name)") + + $xmlWriter.WriteStartElement('Parameters') + + $keys | Where-Object { $null -ne $_ } | ForEach-Object { + $xmlWriter.WriteStartElement('Parameter') + $xmlWriter.WriteAttributeString('ParameterName', $_.Name + ':Key') + + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $_.Name) + $xmlWriter.WriteAttributeString('IsMandatory', 'true') + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + } + + $i = -1 + foreach ($parameter in $action.Parameters) + { + $i++ + + # for Instance actions, first parameter is Entity Set which we refer to using keys + if ($isInstanceAction -and ($i -eq 0)) + { + continue + } + + $xmlWriter.WriteStartElement('Parameter') + $xmlWriter.WriteAttributeString('ParameterName', $parameter.Name) + + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $parameter.TypeName + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $parameter.Name) + if (-not $parameter.IsNullable) + { + $xmlWriter.WriteAttributeString('IsMandatory', 'true') + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + } + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + } + + # Add -Force parameter to Service Action cmdlets. + AddParametersNode $xmlWriter $null $null $null $null $true $false $complexTypeMapping + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteEndElement() + + $xmlWriter +} + +######################################################### +# GenerateServiceActionProxyCmdlet is a helper function +# used to generate Invoke-* proxy cmdlet. These proxy +# cmdlets support all Service-level actions. They are +# generated in the CDXML compliant format. +######################################################### +function GenerateServiceActionProxyCmdlet +{ + param + ( + [Parameter(Mandatory=$true)] + [ODataUtils.Metadata] $metaData, + [Parameter(Mandatory=$true)] + [string] $uri, + [Parameter(Mandatory=$true)] + [string] $path, + [Hashtable] $complexTypeMapping, + [string] $progressBarStatus, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + # $uri is already validated at the cmdlet layer. + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateServiceActionProxyCmdlet") } + + $xmlWriter = New-Object System.XMl.XmlTextWriter($path,$Null) + + if ($null -eq $xmlWriter) + { + throw $LocalizedData.XmlWriterInitializationError -f "ServiceActions" + } + + $xmlWriter = SaveCDXMLHeader $xmlWriter $uri 'ServiceActions' 'ServiceActions' + + $actions = $metaData.Actions | Where-Object { $null -eq $_.EntitySet } + + if ($actions.Length -gt 0) + { + $xmlWriter.WriteStartElement('StaticCmdlets') + + foreach ($action in $actions) + { + $xmlWriter = GenerateActionProxyCmdlet $xmlWriter $metaData $action '' $false $null $complexTypeMapping + } + + $xmlWriter.WriteEndElement() + } + + $xmlWriter.WriteStartElement('CmdletAdapterPrivateData') + $xmlWriter.WriteStartElement('Data') + $xmlWriter.WriteAttributeString('Name', 'Namespace') + $xmlWriter.WriteString("$($EntitySet.Namespace)") + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + SaveCDXMLFooter $xmlWriter + + ProcessStreamHelper ($LocalizedData.VerboseSavedServiceActions -f $path) "Export-ODataEndpointProxy" $progressBarStatus 60 20 1 1 $path $callerPSCmdlet +} + +######################################################### +# GenerateModuleManifest is a helper function used +# to generate a wrapper module manifest file. The +# generated module manifest is persisted to the disk at +# the specified OutPutModule path. When the module +# manifest is imported, the following commands will +# be imported: +# 1. Get, Set, New & Remove proxy cmdlets. +# 2. If the server side Odata endpoint exposes complex +# types, then the corresponding client side proxy +# complex types imported. +# 3. Service Action proxy cmdlets. +######################################################### +function GenerateModuleManifest +{ + param + ( + [ODataUtils.Metadata] $metaData, + [String] $modulePath, + [string[]] $additionalModules, + [Hashtable] $resourceNameMapping, + [string] $progressBarStatus, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateModuleManifest") } + if($null -eq $modulePath) { throw ($LocalizedData.ArguementNullError -f "ModulePath", "GenerateModuleManifest") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateModuleManifest") } + + $NestedModules = @() + foreach ($entitySet in $metaData.EntitySets) + { + $entitySetName = $entitySet.Name + if(($null -ne $resourceNameMapping) -and + $resourceNameMapping.ContainsKey($entitySetName)) + { + $entitySetName = $resourceNameMapping[$entitySetName] + } + else + { + $entitySetName = $entitySet.Type.Name + } + + $NestedModules += "$OutputModule\$($entitySetName).cdxml" + } + + New-ModuleManifest -Path $modulePath -NestedModules ($AdditionalModules + $NestedModules) + + ProcessStreamHelper ($LocalizedData.VerboseSavedModuleManifest -f $modulePath) "Export-ODataEndpointProxy" $progressBarStatus 80 20 1 1 $modulePath $callerPSCmdlet +} + +######################################################### +# GetBaseType is a helper function used to fetch the +# base type of the given type. +######################################################### +function GetBaseType +{ + param + ( + [System.Xml.XmlElement] $metadataEntityDefinition, + [ODataUtils.Metadata] $metaData + ) + + if ($null -ne $metadataEntityDefinition -and + $null -ne $metaData -and + $null -ne $metadataEntityDefinition.BaseType) + { + $baseType = $metaData.EntityTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} + if ($null -eq $baseType) + { + $baseType = $metaData.ComplexTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} + } + } + + if ($null -ne $baseType) + { + $baseType[0] + } +} + +######################################################### +# AddDerivedTypes is a helper function used to process +# derived types of a newly added type, that were +# previously waiting in the queue. +######################################################### +function AddDerivedTypes +{ + param + ( + [ODataUtils.EntityType] $baseType, + [Hashtable]$entityAndComplexTypesQueue, + [ODataUtils.Metadata] $metaData, + [string] $namespace + ) + + # $metaData is already validated at the cmdlet layer. + if($null -eq $baseType) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } + if($null -eq $entityAndComplexTypesQueue) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } + + $baseTypeFullName = $baseType.Namespace + '.' + $baseType.Name + + if ($entityAndComplexTypesQueue.ContainsKey($baseTypeFullName)) + { + foreach ($type in $entityAndComplexTypesQueue[$baseTypeFullName]) + { + if ($type.type -eq 'EntityType') + { + $newType = ParseMetadataTypeDefinition ($type.value) $baseType $metaData $namespace $true + $metaData.EntityTypes += $newType + } + else + { + $newType = ParseMetadataTypeDefinition ($type.value) $baseType $metaData $namespace $false + $metaData.ComplexTypes += $newType + } + + AddDerivedTypes $newType $entityAndComplexTypesQueue $metaData $namespace + } + } +} + +######################################################### +# ParseMetadataTypeDefinition is a helper function used +# to parse types definitions element of metadata xml. +######################################################### +function ParseMetadataTypeDefinition +{ + param + ( + [Parameter(Mandatory=$true)] + [System.Xml.XmlElement] $metadataEntityDefinition, + [ODataUtils.EntityType] $baseType, + [ODataUtils.Metadata] $metaData, + [string] $namespace, + [bool] $isEntity + ) + + # $metaData is already validated at the cmdlet layer. + if($null -eq $metadataEntityDefinition) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } + + $newEntityType = [ODataUtils.EntityType] @{ + "Namespace" = $namespace; + "Name" = $metadataEntityDefinition.Name; + "IsEntity" = $isEntity; + "BaseType" = $baseType; + } + + # properties defined on EntityType + $newEntityType.EntityProperties = $metadataEntityDefinition.Property | ForEach-Object { + if ($null -ne $_) + { + if ($null -ne $_.Nullable) + { + $newPropertyIsNullable = [System.Convert]::ToBoolean($_.Nullable) + } + else + { + $newPropertyIsNullable = $true + } + + [ODataUtils.TypeProperty] @{ + "Name" = $_.Name; + "TypeName" = $_.Type; + "IsNullable" = $newPropertyIsNullable; + } + } + } + + # navigation properties defined on EntityType + $newEntityType.NavigationProperties = $metadataEntityDefinition.NavigationProperty | ForEach-Object { + if ($null -ne $_) + { + ($AssociationNamespace, $AssociationName) = SplitNamespaceAndName $_.Relationship + [ODataUtils.NavigationProperty] @{ + "Name" = $_.Name; + "FromRole" = $_.FromRole; + "ToRole" = $_.ToRole; + "AssociationNamespace" = $AssociationNamespace; + "AssociationName" = $AssociationName; + } + } + } + + foreach ($entityTypeKey in $metadataEntityDefinition.Key.PropertyRef) + { + ((GetAllProperties $newEntityType) | Where-Object { $_.Name -eq $entityTypeKey.Name }).IsKey = $true + } + + $newEntityType +} + +######################################################### +# GetAllProperties is a helper function used to fetch +# the entity properties or navigation properties of +# the entity type as well as that of complete base +# type hierarchy. +######################################################### +function GetAllProperties +{ + param + ( + [ODataUtils.EntityType] $entityType, + [switch] $IncludeOnlyNavigationProperties + ) + + if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetAllProperties") } + + $requestedProperties = @() + + # Populate EntityType property from current EntityType as well + # as from the corresponding base types recursively if + # $IncludeOnlyNavigationProperties switch parameter is used then follow + # the same routine for navigation properties. + $currentEntityType = $entityType + while($null -ne $currentEntityType) + { + if($IncludeOnlyNavigationProperties.IsPresent) + { + $chosenProperties = $currentEntityType.NavigationProperties + } + else + { + $chosenProperties = $currentEntityType.EntityProperties + } + + $requestedProperties += $chosenProperties + $currentEntityType = $currentEntityType.BaseType + } + + return $requestedProperties +} + +######################################################### +# SplitNamespaceAndName is a helper function used +# to split Namespace and actual Name. +# e.g. "a.b.c" is namespace "a.b" and name "c" +######################################################### +function SplitNamespaceAndName +{ + param + ( + [string] $fullyQualifiedName + ) + + if($null -eq $fullyQualifiedName) { throw ($LocalizedData.ArguementNullError -f "FUllyQualifiedName", "SplitNamespaceAndName") } + + $sa = $fullyQualifiedName -split "(.*)\.(.*)" + + if ($sa.Length -gt 1) + { + # return Namespace + $sa[1] + + # return Name + $sa[2] + } + else + { + # return Namespace + "" + + # return Name + $sa[0] + } +} + +######################################################### +# GetEntitySetForEntityType is a helper function used +# to fetch EntitySet for a given EntityType by +# searching the inheritance hierarchy in the +# supplied metadata. +######################################################### +function GetEntitySetForEntityType +{ + param + ( + [ODataUtils.Metadata] $metaData, + [ODataUtils.EntityType] $entityType + ) + + # $metaData is already validated at the cmdlet layer. + if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } + + $result = $metaData.EntitySets | Where-Object { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } + + if (($result.Count -eq 0) -and ($null -ne $entityType.BaseType)) + { + GetEntitySetForEntityType $metaData $entityType.BaseType + } + elseif ($result.Count -gt 1) + { + throw ($LocalizedData.WrongCountEntitySet -f (($entityType.Namespace + "." + $entityType.Name), $result.Count)) + } + + $result +} + +######################################################### +# ProcessStreamHelper is a helper function that performs +# the following utility tasks: +# 1. Writes verbose messages to the stream. +# 2. Writes FileInfo objects for the proxy modules +# saved to the disk. This is done to keep the user +# experience in consistent with Export-PSSession. +# 3. Updates progress bar. +######################################################### +function ProcessStreamHelper +{ + param + ( + [string] $verboseMessage, + [string] $progressBarActivityName, + [string] $status, + [double] $previousSegmentWeight, + [double] $currentSegmentWeight, + [int] $totalNumberofEntries, + [int] $currentEntryCount, + [string] $path, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + Write-Verbose -Message $verboseMessage + ProgressBarHelper $progressBarActivityName $status $previousSegmentWeight $currentSegmentWeight $totalNumberofEntries $currentEntryCount + $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $path | Get-Item + if($null -ne $callerPSCmdlet) + { + $callerPSCmdlet.WriteObject($proxyFile) + } +} + +######################################################### +# GetAssociatedType is a helper function used +# to fetch associated instance's EntityType +# for a given Navigation property in the +# supplied metadata. +######################################################### +function GetAssociatedType +{ + param + ( + [ODataUtils.Metadata] $Metadata, + [ODataUtils.NavigationProperty] $navProperty + ) + + # $metaData is already validated at the cmdlet layer. + if($null -eq $navProperty) { throw ($LocalizedData.ArguementNullError -f "NavigationProperty", "GetAssociatedType") } + + $associationName = $navProperty.AssociationName + $association = $Metadata.Associations | Where-Object { $_.Name -eq $associationName } + $associationType = $association.Type + + if ($associationType.Count -lt 1) + { + throw ($LocalizedData.AssociationNotFound -f $associationName) + } + elseif ($associationType.Count -gt 1) + { + throw ($LocalizedData.TooManyMatchingAssociationTypes -f $associationType.Count, $associationName) + } + + if ($associationType.NavPropertyName1 -eq $navProperty.ToRole) + { + $associatedType = $associationType.EndType1 + } + elseif ($associationType.NavPropertyName2 -eq $navProperty.ToRole) + { + $associatedType = $associationType.EndType2 + } + else + { + throw ($LocalizedData.ZeroMatchingAssociationTypes -f $navProperty.ToRole, $association.Name) + } + + # return associated EntityType + $associatedType +} + +######################################################### +# AddParametersNode is a helper function used +# to add parameters to the generated proxy cmdlet, +# based on mandatoryProperties and otherProperties. +# PrefixForKeys is used by associations to append a +# prefix to PowerShell parameter name. +######################################################### +function AddParametersNode +{ + param + ( + [Parameter(Mandatory=$true)] + [System.Xml.XmlWriter] $xmlWriter, + [ODataUtils.TypeProperty[]] $keyProperties, + [ODataUtils.TypeProperty[]] $mandatoryProperties, + [ODataUtils.TypeProperty[]] $otherProperties, + [string] $prefixForKeys, + [boolean] $addForceParameter, + [boolean] $addParametersElement, + [Hashtable] $complexTypeMapping + ) + + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } + + if(($keyProperties.Length -gt 0) -or + ($mandatoryProperties.Length -gt 0) -or + ($otherProperties.Length -gt 0) -or + ($addForceParameter)) + { + if($addParametersElement) + { + $xmlWriter.WriteStartElement('Parameters') + } + + $pos = 0 + + if ($null -ne $keyProperties) + { + $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping + } + + if ($null -ne $mandatoryProperties) + { + $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping + } + + if ($null -ne $otherProperties) + { + $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping + } + + if($addForceParameter) + { + $forceParameter = [ODataUtils.TypeProperty] @{ + "Name" = "Force"; + "TypeName" = "switch"; + "IsNullable" = $false + } + + $pos = AddParametersCDXML $xmlWriter $forceParameter $pos $false $null $null $complexTypeMapping + } + + if($addParametersElement) + { + $xmlWriter.WriteEndElement() + } + } +} + +######################################################### +# AddParametersNode is a helper function used +# to add Parameter node to CDXML based on properties. +# Prefix is appended to PS parameter names, used for +# associations. Suffix is appended to all parameter +# names, for ex. to differentiate keys. returns new $pos +######################################################### +function AddParametersCDXML +{ + param + ( + [Parameter(Mandatory=$true)] + [System.Xml.XmlWriter] $xmlWriter, + [ODataUtils.TypeProperty[]] $properties, + [Parameter(Mandatory=$true)] + [int] $pos, + [bool] $isMandatory, + [string] $prefix, + [string] $suffix, + [Hashtable] $complexTypeMapping + ) + + $properties | Where-Object { $null -ne $_ } | ForEach-Object { + $xmlWriter.WriteStartElement('Parameter') + $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $prefix + $_.Name) + $xmlWriter.WriteAttributeString('IsMandatory', ($isMandatory).ToString().ToLowerInvariant()) + $xmlWriter.WriteAttributeString('Position', $pos) + if($isMandatory) + { + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + } + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + $pos++ + } + + $pos +} + +######################################################### +# GenerateComplexTypeDefinition is a helper function used +# to generate complex type definition from the metadata. +######################################################### +function GenerateComplexTypeDefinition +{ + param + ( + [ODataUtils.Metadata] $metaData, + [string] $metaDataUri, + [string] $OutputModule, + [string] $typeDefinitionFileName, + [string] $cmdletAdapter, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + #metadataUri, $OutputModule & $cmdletAdapter are already validated at the cmdlet layer. + if($null -eq $typeDefinationFileName) { throw ($LocalizedData.ArguementNullError -f "TypeDefinationFileName", "GenerateComplexTypeDefination") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateComplexTypeDefination") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateComplexTypeDefination") } + + $Path = "$OutputModule\$typeDefinitionFileName" + + # We are currently generating classes for EntityType & ComplexType + # definition exposed in the metadata. + $typesToBeGenerated = $metaData.EntityTypes+$metadata.ComplexTypes + + if($null -ne $typesToBeGenerated -and $typesToBeGenerated.Count -gt 0) + { + $complexTypeMapping = @{} + $entityTypeNameSpaceMapping = @{} + + foreach ($entityType in $typesToBeGenerated) + { + if ($null -ne $entityType) + { + $entityTypeFullName = $entityType.Namespace + '.' + $entityType.Name + if(!$complexTypeMapping.ContainsKey($entityTypeFullName)) + { + $complexTypeMapping.Add($entityTypeFullName, $entityType.Name) + } + + if(!$entityTypeNameSpaceMapping.ContainsKey($entityType.Namespace)) + { + $entityTypes = @() + $entityTypeNameSpaceMapping.Add($entityType.Namespace, $entityTypes) + } + + $entityTypeNameSpaceMapping[$entityType.Namespace] += $entityType + } + } + + if($entityTypeNameSpaceMapping.Count -gt 0) + { +$output = @" +`$typeDefinitions = @" +using System; +using System.Management.Automation; + +"@ + + foreach($currentNameSpace in $entityTypeNameSpaceMapping.Keys) + { + $entityTypes = $entityTypeNameSpaceMapping[$currentNameSpace] + + $output += "`r`nnamespace $(ValidateComplexTypeIdentifier $currentNameSpace $true $metaDataUri $callerPSCmdlet)`r`n{" + + foreach ($entityType in $entityTypes) + { + $entityTypeFullName = (ValidateComplexTypeIdentifier $entityType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + $entityType.Name + Write-Verbose ($LocalizedData.VerboseAddingTypeDefinationToGeneratedModule -f $entityTypeFullName, "$OutputModule\$typeDefinationFileName") + + if($null -ne $entityType.BaseType) + { + $entityBaseFullName = (ValidateComplexTypeIdentifier $entityType.BaseType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + (ValidateComplexTypeIdentifier $entityType.BaseType.Name $false $metaDataUri $callerPSCmdlet) + $output += "`r`n public class $(ValidateComplexTypeIdentifier $entityType.Name $false $metaDataUri $callerPSCmdlet) : $($entityBaseFullName)`r`n {" + } + else + { + $output += "`r`n public class $(ValidateComplexTypeIdentifier $entityType.Name $false $metaDataUri $callerPSCmdlet)`r`n {" + } + + $properties = $null + + for($index = 0; $index -lt $entityType.EntityProperties.Count; $index++) + { + $property = $entityType.EntityProperties[$index] + $typeName = Convert-ODataTypeToCLRType $property.TypeName $complexTypeMapping + $properties += "`r`n public $typeName $(ValidateComplexTypeIdentifier $property.Name $false $metaDataUri $callerPSCmdlet);" + } + + # Navigation properties are treated like any other property for NetworkController scenario. + if ($cmdletAdapter -eq "NetworkControllerAdapter") + { + for($index = 0; $index -lt $entityType.NavigationProperties.Count; $index++) + { + $property = $entityType.NavigationProperties[$index] + $navigationTypeName = GetNavigationPropertyTypeName $property $metaData + $typeName = Convert-ODataTypeToCLRType $navigationTypeName $complexTypeMapping + $properties += "`r`n public $typeName $(ValidateComplexTypeIdentifier $property.Name $false $metaDataUri $callerPSCmdlet);" + } + } + + $output += $properties + $output += "`r`n }`r`n" + } + + $output += "}`r`n" + } + $output += """@`r`n" + + $output += "Add-Type -TypeDefinition `$typeDefinitions `r`n" + $output | Out-File -FilePath $Path + Write-Verbose ($LocalizedData.VerboseSavedTypeDefinationModule -f $typeDefinationFileName, $OutputModule) + } + } + + return $complexTypeMapping +} + +# Creating a single instance of CSharpCodeProvider that would be used +# for Identifier validation in the ValidateComplexTypeIdentifier helper method. +$cSharpCodeProvider = [Microsoft.CSharp.CSharpCodeProvider]::new() + +######################################################### +# ValidateComplexTypeIdentifier is a helper function to +# make sure that the type names defined in the +# metadata are valid C# Identifier names. This validation +# is performed to make sure that there are no security +# threat from importing the generated complex type +# (which is created using the metadata file). +# This method return the identifier name if its a +# valid identifier, else a terminating error in thrown. +######################################################### +function ValidateComplexTypeIdentifier +{ + param + ( + [string] $identifierName, + [bool] $isNameSpaceName, + [string] $metaDataUri, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ValidateComplexTypeIdentifier") } + + if($isNameSpaceName) + { + $independentIdentifiers = $identifierName.Split('.') + $result = $true + foreach($currentIdentifier in $independentIdentifiers) + { + if(![System.CodeDom.Compiler.CodeGenerator]::IsValidLanguageIndependentIdentifier($currentIdentifier)) + { + $result = $false + break + } + } + } + else + { + $result = $cSharpCodeProvider.IsValidIdentifier($identifierName) + } + + if(!$result) + { + $errorMessage = ($LocalizedData.InValidIdentifierInMetadata -f $metaDataUri, $identifierName) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidIdentifier" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidData) $null $identifierName + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + else + { + return $identifierName + } +} + +######################################################### +# GetKeys is a helper function used to +# return the keys for the entity if customUri +# is specified. +######################################################### +function GetKeys +{ + param + ( + [ODataUtils.EntitySet] $entitySet, + [string] $customUri, + [string] $actionName + ) + + # Get the original keys + $key = (GetAllProperties $entitySet.Type) | Where-Object { $_.IsKey } + + # Get the keys with delimiters + $keys = $customUri -split "/" | ForEach-Object { + if ($_ -match '{*}') + { + [ODataUtils.TypeProperty] @{ + "Name" = $_.Substring($_.IndexOf('{')+1,$_.IndexOf('}')-$_.IndexOf('{')-1); + "TypeName" = "Edm.String"; + "IsNullable" = $false; + "IsMandatory" = $true; + } + } + elseif ($_ -match '\[*\]') + { + if ($ActionName -eq 'Get') { + [ODataUtils.TypeProperty] @{ + "Name" = $_.Substring($_.IndexOf('[')+1,$_.IndexOf(']')-$_.IndexOf('[')-1); + "TypeName" = "Edm.String"; + "IsNullable" = $false; + "IsMandatory" = $false; + } + } + else { + [ODataUtils.TypeProperty] @{ + "Name" = $_.Substring($_.IndexOf('[')+1,$_.IndexOf(']')-$_.IndexOf('[')-1); + "TypeName" = "Edm.String"; + "IsNullable" = $false; + "IsMandatory" = $true; + } + } + } + } + + # Now combine the two keys and avoid duplication + # Make a list of names already present in the new keys + # Foreach old key check if that key is present in the new keyList + # Else add the key to new key list + $keyParams = $keys | ForEach-Object {$_.Name} + + if ($null -eq $keyParams -Or $keyParams.Count -eq 0) { + $keys = $key + } + else { + if ($keyParams.Count -eq 1) { + $keys = @($keys) + } + + $key | ForEach-Object { + if ($keyParams.Contains($_.Name) -eq $false) + { + $keys += $_ + } + } + } + + $keys +} + +######################################################### +# GetNetworkControllerAdditionalProperties is a helper +# function used to fetch network controller specific +# additional properties. +######################################################### +function GetNetworkControllerAdditionalProperties +{ + param + ( + $navigationProperties, + $metaData + ) + + # Additional properties contains the types present as navigation properties + + $additionalProperties = $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { + $typeName = GetNavigationPropertyTypeName $_ $metaData + + if ($_.Name -eq "Properties") { + $isNullable = $false + } + else { + $isNullable = $true + } + + [ODataUtils.TypeProperty] @{ + "Name" = $_.Name; + "TypeName" = $typeName + "IsNullable" = $isNullable; + } + } + + # Add etag to the additionalProperties + + if ($null -ne $additionalProperties) + { + if ($additionalProperties.Count -eq 1) { + $additionalProperties = @($additionalProperties) + } + + $additionalProperties += [ODataUtils.TypeProperty] @{ + "Name" = "Etag"; + "TypeName" = "Edm.String"; + "IsNullable" = $true; + } + } + else + { + $additionalProperties = [ODataUtils.TypeProperty] @{ + "Name" = "Etag"; + "TypeName" = "Edm.String"; + "IsNullable" = $true; + } + } + + $additionalProperties +} + +######################################################### +# UpdateNetworkControllerSpecificProperties is a +# helper function used to append additionalProperties +# to nullable/nonNullable Properties. This is network controller +# specific logic. +######################################################### +function UpdateNetworkControllerSpecificProperties +{ + param + ( + $nullableProperties, + $additionalProperties, + $keyProperties, + $isNullable + ) + + if ($isNullable) { + $additionalProperties = $additionalProperties | Where-Object { $_.isNullable } + } + else { + $additionalProperties = $additionalProperties | Where-Object { -not $_.isNullable } + } + + if ($null -eq $nullableProperties) + { + $nullableProperties = $additionalProperties + } + else { + if ($nullableProperties.Count -eq 1) { + $nullableProperties = @($nullableProperties) + } + if ($null -ne $additionalProperties) { + $nullableProperties += $additionalProperties + } + } + + if ($null -ne $nullableProperties -And $null -ne $keyProperties) + { + if ($keyProperties.Count -eq 1) { + $keyProperties = @($keyProperties) + } + + $keys = $keyProperties | ForEach-Object {$_.Name} + + if ($keys.Count -eq 1) { + $keys = @($keys) + } + + $nullableProperties = $nullableProperties | Where-Object {$keys.Contains($_.Name) -eq $false} + } + + $nullableProperties +} + +######################################################### +# GetNavigationPropertyTypeName is a +# helper function used to fetch the type corresponding +# to navigation property in this metadata. This is +# network controller specific logic. +######################################################### +function GetNavigationPropertyTypeName +{ + param + ( + $navigationProperty, + $metaData + ) + + foreach($association in $metaData.Associations) + { + if ($association.Name -ne $navigationProperty.AssociationName -Or $association.Namespace -ne $navigationProperty.AssociationNamespace) + { + continue + } + + # Now get the type for this association + + if ($association.Type.NavPropertyName1 -eq $navigationProperty.Name) + { + $type = $association.Type.EndType1 + $multiplicity = $association.Type.Multiplicity1 + } + elseif ($associationType.NavPropertyName2 -eq $navigationProperty.Name) + { + $type = $association.Type.EndType2 + $multiplicity = $association.Type.Multiplicity2 + } + + break + } + + $fullName = $type.Namespace + '.' + $type.Name + + # Check the multiplicity and convert to array if needed + if ($multiplicity -eq "*") + { + $fullName = "Collection($fullName)" + } + + $fullName +} diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psd1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psd1 index 589b6cb824c..515040f7941 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psd1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psd1 @@ -1,240 +1,240 @@ -# -# Module manifest for module 'Microsoft.PowerShell.ODataUtils' -# -# Generated on: 8/15/2013 -# - -@{ - -# Script module or binary module file associated with this manifest. -RootModule = 'Microsoft.PowerShell.ODataUtils.psm1' - -# Version number of this module. -ModuleVersion = '1.0' - -# ID used to uniquely identify this module -GUID = 'fa1606d1-94cb-4264-bfb6-def714420084' - -# Author of this module -Author = 'Microsoft Corporation' - -# Company or vendor of this module -CompanyName = 'Microsoft Corporation' - -# Copyright statement for this module -Copyright = '(c) 2014 Microsoft. All rights reserved.' - -# Description of the functionality provided by this module -# Description = '' - -# Minimum version of the Windows PowerShell engine required by this module -# PowerShellVersion = '' - -# Name of the Windows PowerShell host required by this module -# PowerShellHostName = '' - -# Minimum version of the Windows PowerShell host required by this module -# PowerShellHostVersion = '' - -# Minimum version of Microsoft .NET Framework required by this module -# DotNetFrameworkVersion = '' - -# Minimum version of the common language runtime (CLR) required by this module -# CLRVersion = '' - -# Processor architecture (None, X86, Amd64) required by this module -# ProcessorArchitecture = '' - -# Modules that must be imported into the global environment prior to importing this module -# RequiredModules = @() - -# Assemblies that must be loaded prior to importing this module -# RequiredAssemblies = @() - -# Script files (.ps1) that are run in the caller's environment prior to importing this module. -# ScriptsToProcess = @() - -# Type files (.ps1xml) to be loaded when importing this module -# TypesToProcess = @() - -# Format files (.ps1xml) to be loaded when importing this module -# FormatsToProcess = @() - -# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess -# NestedModules = @() - -# Functions to export from this module -FunctionsToExport = @('Export-ODataEndpointProxy') - -# Cmdlets to export from this module -CmdletsToExport = '' - -# Variables to export from this module -VariablesToExport = '' - -# Aliases to export from this module -AliasesToExport = '' - -# List of all modules packaged with this module -# ModuleList = @() - -# List of all files packaged with this module -# FileList = @() - -# Private data to pass to the module specified in RootModule/ModuleToProcess -# PrivateData = '' - -# HelpInfo URI of this module -HelpInfoURI = 'https://go.microsoft.com/fwlink/?LinkId=509916' - -# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. -# DefaultCommandPrefix = '' - -} - - -# SIG # Begin signature block -# MIIavwYJKoZIhvcNAQcCoIIasDCCGqwCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB -# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR -# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU5qxxE9NAWfUb5Y4oxi1pHiiU -# j+GgghWCMIIEwzCCA6ugAwIBAgITMwAAAHQNgGQOfWd9owAAAAAAdDANBgkqhkiG -# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G -# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw -# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTUwMzIwMTczMjA1 -# WhcNMTYwNjIwMTczMjA1WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp -# bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw -# b3JhdGlvbjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO -# OjdEMkUtMzc4Mi1CMEY3MSUwIwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBT -# ZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4NFrifjVvo5Y -# gN/jD+4M6zszXn3GnmZHP9AerBSCDRiftpwnIvG2hpREQXSJkW8X9t+Y5jbLX3iS -# 6XJ+S7kExWIUc3HGf2NBW+tk8r1cVWJGzA9ewQnEr9nxvyV94BegUO4lqkXl48Z+ -# vxBZqcGPPtn77GQbY1u1p7jq681X6xtD9WWRv1D1+cEGvH2qzDfnBqmgzLH1M8wN -# ssh1ZgDRbTCTR8+OomdEXhoTf/McHucPncG8SPyBgW1UauJpE8bO9ZdnMmxIyhHC -# VjrW3Dpi9PwQl2RIC4pc8RbClfDLYBukA5sMyfe7kr8Ac2czHKJ673VKGUZaDH6a -# W6A6HVQ16wIDAQABo4IBCTCCAQUwHQYDVR0OBBYEFCUsOGYFtEU5DmC29u69PuDd -# r4wNMB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMPMFQGA1UdHwRNMEsw -# SaBHoEWGQ2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3Rz -# L01pY3Jvc29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEETDBKMEgGCCsG -# AQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jv -# c29mdFRpbWVTdGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZI -# hvcNAQEFBQADggEBAEEG50j6xJHcMBMNInjC0iPTszPL+yYh1978CncY+4Nyzu/U -# LIaP4xXj1RICZ1xbN9MDe02RW0FTZgn9457fLHgJORo2HYqBocllfJx7kbIPSptB -# 3cdEC2EFyUwu8rRrKKoIR+4IrGZUF1aQiMbpddAhEDh5yT+7VTDFpjmmU7/NXFbS -# ThcUvGISy+lL8MWR3J2EypjWDttWFGht21OLMM+6J2V1oDFvk6N1EGDqqu7uduvl -# jAup0655zzS+SR8i0MT1o+/zrjDcjohGI4ygqjyXrwfbdug2VN+Ls4mewOospGBr -# 8d/DthI6rzM4elFxNTXm5AjiUZaC+b7hG4N8e2cwggTsMIID1KADAgECAhMzAAAA -# ymzVMhI1xOFVAAEAAADKMA0GCSqGSIb3DQEBBQUAMHkxCzAJBgNVBAYTAlVTMRMw -# EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVN -# aWNyb3NvZnQgQ29ycG9yYXRpb24xIzAhBgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNp -# Z25pbmcgUENBMB4XDTE0MDQyMjE3MzkwMFoXDTE1MDcyMjE3MzkwMFowgYMxCzAJ -# BgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25k -# MR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xDTALBgNVBAsTBE1PUFIx -# HjAcBgNVBAMTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjCCASIwDQYJKoZIhvcNAQEB -# BQADggEPADCCAQoCggEBAJZxXe0GRvqEy51bt0bHsOG0ETkDrbEVc2Cc66e2bho8 -# P/9l4zTxpqUhXlaZbFjkkqEKXMLT3FIvDGWaIGFAUzGcbI8hfbr5/hNQUmCVOlu5 -# WKV0YUGplOCtJk5MoZdwSSdefGfKTx5xhEa8HUu24g/FxifJB+Z6CqUXABlMcEU4 -# LYG0UKrFZ9H6ebzFzKFym/QlNJj4VN8SOTgSL6RrpZp+x2LR3M/tPTT4ud81MLrs -# eTKp4amsVU1Mf0xWwxMLdvEH+cxHrPuI1VKlHij6PS3Pz4SYhnFlEc+FyQlEhuFv -# 57H8rEBEpamLIz+CSZ3VlllQE1kYc/9DDK0r1H8wQGcCAwEAAaOCAWAwggFcMBMG -# A1UdJQQMMAoGCCsGAQUFBwMDMB0GA1UdDgQWBBQfXuJdUI1Whr5KPM8E6KeHtcu/ -# gzBRBgNVHREESjBIpEYwRDENMAsGA1UECxMETU9QUjEzMDEGA1UEBRMqMzE1OTUr -# YjQyMThmMTMtNmZjYS00OTBmLTljNDctM2ZjNTU3ZGZjNDQwMB8GA1UdIwQYMBaA -# FMsR6MrStBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeGRWh0dHA6Ly9j -# cmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8w -# OC0zMS0yMDEwLmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKGPmh0dHA6 -# Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljQ29kU2lnUENBXzA4LTMx -# LTIwMTAuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQB3XOvXkT3NvXuD2YWpsEOdc3wX -# yQ/tNtvHtSwbXvtUBTqDcUCBCaK3cSZe1n22bDvJql9dAxgqHSd+B+nFZR+1zw23 -# VMcoOFqI53vBGbZWMrrizMuT269uD11E9dSw7xvVTsGvDu8gm/Lh/idd6MX/YfYZ -# 0igKIp3fzXCCnhhy2CPMeixD7v/qwODmHaqelzMAUm8HuNOIbN6kBjWnwlOGZRF3 -# CY81WbnYhqgA/vgxfSz0jAWdwMHVd3Js6U1ZJoPxwrKIV5M1AHxQK7xZ/P4cKTiC -# 095Sl0UpGE6WW526Xxuj8SdQ6geV6G00DThX3DcoNZU6OJzU7WqFXQ4iEV57MIIF -# vDCCA6SgAwIBAgIKYTMmGgAAAAAAMTANBgkqhkiG9w0BAQUFADBfMRMwEQYKCZIm -# iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0wKwYDVQQD -# EyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMTAwODMx -# MjIxOTMyWhcNMjAwODMxMjIyOTMyWjB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMK -# V2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 -# IENvcnBvcmF0aW9uMSMwIQYDVQQDExpNaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBD -# QTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJyWVwZMGS/HZpgICBC -# mXZTbD4b1m/My/Hqa/6XFhDg3zp0gxq3L6Ay7P/ewkJOI9VyANs1VwqJyq4gSfTw -# aKxNS42lvXlLcZtHB9r9Jd+ddYjPqnNEf9eB2/O98jakyVxF3K+tPeAoaJcap6Vy -# c1bxF5Tk/TWUcqDWdl8ed0WDhTgW0HNbBbpnUo2lsmkv2hkL/pJ0KeJ2L1TdFDBZ -# +NKNYv3LyV9GMVC5JxPkQDDPcikQKCLHN049oDI9kM2hOAaFXE5WgigqBTK3S9dP -# Y+fSLWLxRT3nrAgA9kahntFbjCZT6HqqSvJGzzc8OJ60d1ylF56NyxGPVjzBrAlf -# A9MCAwEAAaOCAV4wggFaMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMsR6MrS -# tBZYAck3LjMWFrlMmgofMAsGA1UdDwQEAwIBhjASBgkrBgEEAYI3FQEEBQIDAQAB -# MCMGCSsGAQQBgjcVAgQWBBT90TFO0yaKleGYYDuoMW+mPLzYLTAZBgkrBgEEAYI3 -# FAIEDB4KAFMAdQBiAEMAQTAfBgNVHSMEGDAWgBQOrIJgQFYnl+UlE/wq4QpTlVnk -# pDBQBgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtp -# L2NybC9wcm9kdWN0cy9taWNyb3NvZnRyb290Y2VydC5jcmwwVAYIKwYBBQUHAQEE -# SDBGMEQGCCsGAQUFBzAChjhodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2Nl -# cnRzL01pY3Jvc29mdFJvb3RDZXJ0LmNydDANBgkqhkiG9w0BAQUFAAOCAgEAWTk+ -# fyZGr+tvQLEytWrrDi9uqEn361917Uw7LddDrQv+y+ktMaMjzHxQmIAhXaw9L0y6 -# oqhWnONwu7i0+Hm1SXL3PupBf8rhDBdpy6WcIC36C1DEVs0t40rSvHDnqA2iA6VW -# 4LiKS1fylUKc8fPv7uOGHzQ8uFaa8FMjhSqkghyT4pQHHfLiTviMocroE6WRTsgb -# 0o9ylSpxbZsa+BzwU9ZnzCL/XB3Nooy9J7J5Y1ZEolHN+emjWFbdmwJFRC9f9Nqu -# 1IIybvyklRPk62nnqaIsvsgrEA5ljpnb9aL6EiYJZTiU8XofSrvR4Vbo0HiWGFzJ -# NRZf3ZMdSY4tvq00RBzuEBUaAF3dNVshzpjHCe6FDoxPbQ4TTj18KUicctHzbMrB -# 7HCjV5JXfZSNoBtIA1r3z6NnCnSlNu0tLxfI5nI3EvRvsTxngvlSso0zFmUeDord -# EN5k9G/ORtTTF+l5xAS00/ss3x+KnqwK+xMnQK3k+eGpf0a7B2BHZWBATrBC7E7t -# s3Z52Ao0CW0cgDEf4g5U3eWh++VHEK1kmP9QFi58vwUheuKVQSdpw5OPlcmN2Jsh -# rg1cnPCiroZogwxqLbt2awAdlq3yFnv2FoMkuYjPaqhHMS+a3ONxPdcAfmJH0c6I -# ybgY+g5yjcGjPa8CQGr/aZuW4hCoELQ3UAjWwz0wggYHMIID76ADAgECAgphFmg0 -# AAAAAAAcMA0GCSqGSIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20xGTAX -# BgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290 -# IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0wNzA0MDMxMjUzMDlaFw0yMTA0MDMx -# MzAzMDlaMHcxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYD -# VQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xITAf -# BgNVBAMTGE1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQTCCASIwDQYJKoZIhvcNAQEB -# BQADggEPADCCAQoCggEBAJ+hbLHf20iSKnxrLhnhveLjxZlRI1Ctzt0YTiQP7tGn -# 0UytdDAgEesH1VSVFUmUG0KSrphcMCbaAGvoe73siQcP9w4EmPCJzB/LMySHnfL0 -# Zxws/HvniB3q506jocEjU8qN+kXPCdBer9CwQgSi+aZsk2fXKNxGU7CG0OUoRi4n -# rIZPVVIM5AMs+2qQkDBuh/NZMJ36ftaXs+ghl3740hPzCLdTbVK0RZCfSABKR2YR -# JylmqJfk0waBSqL5hKcRRxQJgp+E7VV4/gGaHVAIhQAQMEbtt94jRrvELVSfrx54 -# QTF3zJvfO4OToWECtR0Nsfz3m7IBziJLVP/5BcPCIAsCAwEAAaOCAaswggGnMA8G -# A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFCM0+NlSRnAK7UD7dvuzK7DDNbMPMAsG -# A1UdDwQEAwIBhjAQBgkrBgEEAYI3FQEEAwIBADCBmAYDVR0jBIGQMIGNgBQOrIJg -# QFYnl+UlE/wq4QpTlVnkpKFjpGEwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcG -# CgmSJomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0IFJvb3Qg -# Q2VydGlmaWNhdGUgQXV0aG9yaXR5ghB5rRahSqClrUxzWPQHEy5lMFAGA1UdHwRJ -# MEcwRaBDoEGGP2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1 -# Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBUBggrBgEFBQcBAQRIMEYwRAYIKwYB -# BQUHMAKGOGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljcm9z -# b2Z0Um9vdENlcnQuY3J0MBMGA1UdJQQMMAoGCCsGAQUFBwMIMA0GCSqGSIb3DQEB -# BQUAA4ICAQAQl4rDXANENt3ptK132855UU0BsS50cVttDBOrzr57j7gu1BKijG1i -# uFcCy04gE1CZ3XpA4le7r1iaHOEdAYasu3jyi9DsOwHu4r6PCgXIjUji8FMV3U+r -# kuTnjWrVgMHmlPIGL4UD6ZEqJCJw+/b85HiZLg33B+JwvBhOnY5rCnKVuKE5nGct -# xVEO6mJcPxaYiyA/4gcaMvnMMUp2MT0rcgvI6nA9/4UKE9/CCmGO8Ne4F+tOi3/F -# NSteo7/rvH0LQnvUU3Ih7jDKu3hlXFsBFwoUDtLaFJj1PLlmWLMtL+f5hYbMUVbo -# nXCUbKw5TNT2eb+qGHpiKe+imyk0BncaYsk9Hm0fgvALxyy7z0Oz5fnsfbXjpKh0 -# NbhOxXEjEiZ2CzxSjHFaRkMUvLOzsE1nyJ9C/4B5IYCeFTBm6EISXhrIniIh0EPp -# K+m79EjMLNTYMoBMJipIJF9a6lbvpt6Znco6b72BJ3QGEe52Ib+bgsEnVLaxaj2J -# oXZhtG6hE6a/qkfwEm/9ijJssv7fUciMI8lmvZ0dhxJkAj0tr1mPuOQh5bWwymO0 -# eFQF1EEuUKyUsKV4q7OglnUa2ZKHE3UiLzKoCG6gW4wlv6DvhMoh1useT8ma7kng -# 9wFlb4kLfchpyOZu6qeXzjEp/w7FW1zYTRuh2Povnj8uVRZryROj/TGCBKcwggSj -# AgEBMIGQMHkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYD -# VQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xIzAh -# BgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBAhMzAAAAymzVMhI1xOFV -# AAEAAADKMAkGBSsOAwIaBQCggcAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQw -# HAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFFNt -# DhScbWHVDFMkTLRd2qRP8wFeMGAGCisGAQQBgjcCAQwxUjBQoCaAJABXAGkAbgBk -# AG8AdwBzACAAUABvAHcAZQByAFMAaABlAGwAbKEmgCRodHRwOi8vd3d3Lm1pY3Jv -# c29mdC5jb20vcG93ZXJzaGVsbCAwDQYJKoZIhvcNAQEBBQAEggEAddyT//E7Ysbi -# U9kfhQrYkjrhhZCKOzQPVAZSNxWx246MveRe1aj3A+Kr868dYH3x8or8g7MpeJig -# 0WOx4O+mw4fUCdTT6fLqo+W8Q+5qNpWjpfpP5eq7firhhh5D8jB1h7tJWI7fkvHN -# VwadYG4t4BxGIFgsn6YIgPn8ZipmOLb8zvCaDPpg9Xr5U5YKKUrA3sgiuW+zf0aK -# r506K+pfuC56XItbX25VEvf+hjazJr2UasFTweV4mCgKHoAG1UluKUZaX8B+KaKB -# DGMUJ3pCAqyt9RCTSQC9xZxWyK+g0byzn2dpCNxWDXHI7SxCs8ejBhp5yYtlBXl7 -# vkGAXdlJ9aGCAigwggIkBgkqhkiG9w0BCQYxggIVMIICEQIBATCBjjB3MQswCQYD -# VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe -# MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3Nv -# ZnQgVGltZS1TdGFtcCBQQ0ECEzMAAAB0DYBkDn1nfaMAAAAAAHQwCQYFKw4DAhoF -# AKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE1 -# MDUxMTE4MTE1M1owIwYJKoZIhvcNAQkEMRYEFJl30ao3ese0x5O4lPs3SVZVIOdq -# MA0GCSqGSIb3DQEBBQUABIIBAESrx9oY0vI7nyBV0AwzpSYTA/jQF/+MGVokP7ak -# 5i7x25UMc7+RRMROW9VxhzYpzPtotmF8H4rfZsJLxPRlbFF2pu+8MKiNAKiP851m -# tsD1Cw8AN7T31LG8Syk3yKtEvsvnc3yzZy6sXUbkn02yjHNp0PMsrQJNw9ALRc/p -# s3mHzZTqYkmFeHUHzsRa97ByExmjPnP4vcfK2HdZ+oq2EiLjGICooqimt2ys/BPy -# 7nYZaeHaKaNJtnOQHM2BqN38OcH7X7K4IzxCNceXEION6gZE6wqvp+dkvpN5wasL -# OkQhubomAuN/S2TGKwjx3H45G1dpl3LXqihqtqF/Sed7MZs= -# SIG # End signature block +# +# Module manifest for module 'Microsoft.PowerShell.ODataUtils' +# +# Generated on: 8/15/2013 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'Microsoft.PowerShell.ODataUtils.psm1' + +# Version number of this module. +ModuleVersion = '1.0' + +# ID used to uniquely identify this module +GUID = 'fa1606d1-94cb-4264-bfb6-def714420084' + +# Author of this module +Author = 'Microsoft Corporation' + +# Company or vendor of this module +CompanyName = 'Microsoft Corporation' + +# Copyright statement for this module +Copyright = '(c) 2014 Microsoft. All rights reserved.' + +# Description of the functionality provided by this module +# Description = '' + +# Minimum version of the Windows PowerShell engine required by this module +# PowerShellVersion = '' + +# Name of the Windows PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the Windows PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module +# CLRVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() + +# Functions to export from this module +FunctionsToExport = @('Export-ODataEndpointProxy') + +# Cmdlets to export from this module +CmdletsToExport = '' + +# Variables to export from this module +VariablesToExport = '' + +# Aliases to export from this module +AliasesToExport = '' + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess +# PrivateData = '' + +# HelpInfo URI of this module +HelpInfoURI = 'https://go.microsoft.com/fwlink/?LinkId=509916' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + + +# SIG # Begin signature block +# MIIavwYJKoZIhvcNAQcCoIIasDCCGqwCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB +# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR +# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU5qxxE9NAWfUb5Y4oxi1pHiiU +# j+GgghWCMIIEwzCCA6ugAwIBAgITMwAAAHQNgGQOfWd9owAAAAAAdDANBgkqhkiG +# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G +# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw +# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTUwMzIwMTczMjA1 +# WhcNMTYwNjIwMTczMjA1WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp +# bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw +# b3JhdGlvbjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO +# OjdEMkUtMzc4Mi1CMEY3MSUwIwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBT +# ZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4NFrifjVvo5Y +# gN/jD+4M6zszXn3GnmZHP9AerBSCDRiftpwnIvG2hpREQXSJkW8X9t+Y5jbLX3iS +# 6XJ+S7kExWIUc3HGf2NBW+tk8r1cVWJGzA9ewQnEr9nxvyV94BegUO4lqkXl48Z+ +# vxBZqcGPPtn77GQbY1u1p7jq681X6xtD9WWRv1D1+cEGvH2qzDfnBqmgzLH1M8wN +# ssh1ZgDRbTCTR8+OomdEXhoTf/McHucPncG8SPyBgW1UauJpE8bO9ZdnMmxIyhHC +# VjrW3Dpi9PwQl2RIC4pc8RbClfDLYBukA5sMyfe7kr8Ac2czHKJ673VKGUZaDH6a +# W6A6HVQ16wIDAQABo4IBCTCCAQUwHQYDVR0OBBYEFCUsOGYFtEU5DmC29u69PuDd +# r4wNMB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMPMFQGA1UdHwRNMEsw +# SaBHoEWGQ2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3Rz +# L01pY3Jvc29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEETDBKMEgGCCsG +# AQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jv +# c29mdFRpbWVTdGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZI +# hvcNAQEFBQADggEBAEEG50j6xJHcMBMNInjC0iPTszPL+yYh1978CncY+4Nyzu/U +# LIaP4xXj1RICZ1xbN9MDe02RW0FTZgn9457fLHgJORo2HYqBocllfJx7kbIPSptB +# 3cdEC2EFyUwu8rRrKKoIR+4IrGZUF1aQiMbpddAhEDh5yT+7VTDFpjmmU7/NXFbS +# ThcUvGISy+lL8MWR3J2EypjWDttWFGht21OLMM+6J2V1oDFvk6N1EGDqqu7uduvl +# jAup0655zzS+SR8i0MT1o+/zrjDcjohGI4ygqjyXrwfbdug2VN+Ls4mewOospGBr +# 8d/DthI6rzM4elFxNTXm5AjiUZaC+b7hG4N8e2cwggTsMIID1KADAgECAhMzAAAA +# ymzVMhI1xOFVAAEAAADKMA0GCSqGSIb3DQEBBQUAMHkxCzAJBgNVBAYTAlVTMRMw +# EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVN +# aWNyb3NvZnQgQ29ycG9yYXRpb24xIzAhBgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNp +# Z25pbmcgUENBMB4XDTE0MDQyMjE3MzkwMFoXDTE1MDcyMjE3MzkwMFowgYMxCzAJ +# BgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25k +# MR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xDTALBgNVBAsTBE1PUFIx +# HjAcBgNVBAMTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjCCASIwDQYJKoZIhvcNAQEB +# BQADggEPADCCAQoCggEBAJZxXe0GRvqEy51bt0bHsOG0ETkDrbEVc2Cc66e2bho8 +# P/9l4zTxpqUhXlaZbFjkkqEKXMLT3FIvDGWaIGFAUzGcbI8hfbr5/hNQUmCVOlu5 +# WKV0YUGplOCtJk5MoZdwSSdefGfKTx5xhEa8HUu24g/FxifJB+Z6CqUXABlMcEU4 +# LYG0UKrFZ9H6ebzFzKFym/QlNJj4VN8SOTgSL6RrpZp+x2LR3M/tPTT4ud81MLrs +# eTKp4amsVU1Mf0xWwxMLdvEH+cxHrPuI1VKlHij6PS3Pz4SYhnFlEc+FyQlEhuFv +# 57H8rEBEpamLIz+CSZ3VlllQE1kYc/9DDK0r1H8wQGcCAwEAAaOCAWAwggFcMBMG +# A1UdJQQMMAoGCCsGAQUFBwMDMB0GA1UdDgQWBBQfXuJdUI1Whr5KPM8E6KeHtcu/ +# gzBRBgNVHREESjBIpEYwRDENMAsGA1UECxMETU9QUjEzMDEGA1UEBRMqMzE1OTUr +# YjQyMThmMTMtNmZjYS00OTBmLTljNDctM2ZjNTU3ZGZjNDQwMB8GA1UdIwQYMBaA +# FMsR6MrStBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeGRWh0dHA6Ly9j +# cmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8w +# OC0zMS0yMDEwLmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKGPmh0dHA6 +# Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljQ29kU2lnUENBXzA4LTMx +# LTIwMTAuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQB3XOvXkT3NvXuD2YWpsEOdc3wX +# yQ/tNtvHtSwbXvtUBTqDcUCBCaK3cSZe1n22bDvJql9dAxgqHSd+B+nFZR+1zw23 +# VMcoOFqI53vBGbZWMrrizMuT269uD11E9dSw7xvVTsGvDu8gm/Lh/idd6MX/YfYZ +# 0igKIp3fzXCCnhhy2CPMeixD7v/qwODmHaqelzMAUm8HuNOIbN6kBjWnwlOGZRF3 +# CY81WbnYhqgA/vgxfSz0jAWdwMHVd3Js6U1ZJoPxwrKIV5M1AHxQK7xZ/P4cKTiC +# 095Sl0UpGE6WW526Xxuj8SdQ6geV6G00DThX3DcoNZU6OJzU7WqFXQ4iEV57MIIF +# vDCCA6SgAwIBAgIKYTMmGgAAAAAAMTANBgkqhkiG9w0BAQUFADBfMRMwEQYKCZIm +# iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0wKwYDVQQD +# EyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMTAwODMx +# MjIxOTMyWhcNMjAwODMxMjIyOTMyWjB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMK +# V2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 +# IENvcnBvcmF0aW9uMSMwIQYDVQQDExpNaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBD +# QTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJyWVwZMGS/HZpgICBC +# mXZTbD4b1m/My/Hqa/6XFhDg3zp0gxq3L6Ay7P/ewkJOI9VyANs1VwqJyq4gSfTw +# aKxNS42lvXlLcZtHB9r9Jd+ddYjPqnNEf9eB2/O98jakyVxF3K+tPeAoaJcap6Vy +# c1bxF5Tk/TWUcqDWdl8ed0WDhTgW0HNbBbpnUo2lsmkv2hkL/pJ0KeJ2L1TdFDBZ +# +NKNYv3LyV9GMVC5JxPkQDDPcikQKCLHN049oDI9kM2hOAaFXE5WgigqBTK3S9dP +# Y+fSLWLxRT3nrAgA9kahntFbjCZT6HqqSvJGzzc8OJ60d1ylF56NyxGPVjzBrAlf +# A9MCAwEAAaOCAV4wggFaMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMsR6MrS +# tBZYAck3LjMWFrlMmgofMAsGA1UdDwQEAwIBhjASBgkrBgEEAYI3FQEEBQIDAQAB +# MCMGCSsGAQQBgjcVAgQWBBT90TFO0yaKleGYYDuoMW+mPLzYLTAZBgkrBgEEAYI3 +# FAIEDB4KAFMAdQBiAEMAQTAfBgNVHSMEGDAWgBQOrIJgQFYnl+UlE/wq4QpTlVnk +# pDBQBgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtp +# L2NybC9wcm9kdWN0cy9taWNyb3NvZnRyb290Y2VydC5jcmwwVAYIKwYBBQUHAQEE +# SDBGMEQGCCsGAQUFBzAChjhodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2Nl +# cnRzL01pY3Jvc29mdFJvb3RDZXJ0LmNydDANBgkqhkiG9w0BAQUFAAOCAgEAWTk+ +# fyZGr+tvQLEytWrrDi9uqEn361917Uw7LddDrQv+y+ktMaMjzHxQmIAhXaw9L0y6 +# oqhWnONwu7i0+Hm1SXL3PupBf8rhDBdpy6WcIC36C1DEVs0t40rSvHDnqA2iA6VW +# 4LiKS1fylUKc8fPv7uOGHzQ8uFaa8FMjhSqkghyT4pQHHfLiTviMocroE6WRTsgb +# 0o9ylSpxbZsa+BzwU9ZnzCL/XB3Nooy9J7J5Y1ZEolHN+emjWFbdmwJFRC9f9Nqu +# 1IIybvyklRPk62nnqaIsvsgrEA5ljpnb9aL6EiYJZTiU8XofSrvR4Vbo0HiWGFzJ +# NRZf3ZMdSY4tvq00RBzuEBUaAF3dNVshzpjHCe6FDoxPbQ4TTj18KUicctHzbMrB +# 7HCjV5JXfZSNoBtIA1r3z6NnCnSlNu0tLxfI5nI3EvRvsTxngvlSso0zFmUeDord +# EN5k9G/ORtTTF+l5xAS00/ss3x+KnqwK+xMnQK3k+eGpf0a7B2BHZWBATrBC7E7t +# s3Z52Ao0CW0cgDEf4g5U3eWh++VHEK1kmP9QFi58vwUheuKVQSdpw5OPlcmN2Jsh +# rg1cnPCiroZogwxqLbt2awAdlq3yFnv2FoMkuYjPaqhHMS+a3ONxPdcAfmJH0c6I +# ybgY+g5yjcGjPa8CQGr/aZuW4hCoELQ3UAjWwz0wggYHMIID76ADAgECAgphFmg0 +# AAAAAAAcMA0GCSqGSIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20xGTAX +# BgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290 +# IENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw0wNzA0MDMxMjUzMDlaFw0yMTA0MDMx +# MzAzMDlaMHcxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYD +# VQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xITAf +# BgNVBAMTGE1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQTCCASIwDQYJKoZIhvcNAQEB +# BQADggEPADCCAQoCggEBAJ+hbLHf20iSKnxrLhnhveLjxZlRI1Ctzt0YTiQP7tGn +# 0UytdDAgEesH1VSVFUmUG0KSrphcMCbaAGvoe73siQcP9w4EmPCJzB/LMySHnfL0 +# Zxws/HvniB3q506jocEjU8qN+kXPCdBer9CwQgSi+aZsk2fXKNxGU7CG0OUoRi4n +# rIZPVVIM5AMs+2qQkDBuh/NZMJ36ftaXs+ghl3740hPzCLdTbVK0RZCfSABKR2YR +# JylmqJfk0waBSqL5hKcRRxQJgp+E7VV4/gGaHVAIhQAQMEbtt94jRrvELVSfrx54 +# QTF3zJvfO4OToWECtR0Nsfz3m7IBziJLVP/5BcPCIAsCAwEAAaOCAaswggGnMA8G +# A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFCM0+NlSRnAK7UD7dvuzK7DDNbMPMAsG +# A1UdDwQEAwIBhjAQBgkrBgEEAYI3FQEEAwIBADCBmAYDVR0jBIGQMIGNgBQOrIJg +# QFYnl+UlE/wq4QpTlVnkpKFjpGEwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcG +# CgmSJomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0IFJvb3Qg +# Q2VydGlmaWNhdGUgQXV0aG9yaXR5ghB5rRahSqClrUxzWPQHEy5lMFAGA1UdHwRJ +# MEcwRaBDoEGGP2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1 +# Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBUBggrBgEFBQcBAQRIMEYwRAYIKwYB +# BQUHMAKGOGh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljcm9z +# b2Z0Um9vdENlcnQuY3J0MBMGA1UdJQQMMAoGCCsGAQUFBwMIMA0GCSqGSIb3DQEB +# BQUAA4ICAQAQl4rDXANENt3ptK132855UU0BsS50cVttDBOrzr57j7gu1BKijG1i +# uFcCy04gE1CZ3XpA4le7r1iaHOEdAYasu3jyi9DsOwHu4r6PCgXIjUji8FMV3U+r +# kuTnjWrVgMHmlPIGL4UD6ZEqJCJw+/b85HiZLg33B+JwvBhOnY5rCnKVuKE5nGct +# xVEO6mJcPxaYiyA/4gcaMvnMMUp2MT0rcgvI6nA9/4UKE9/CCmGO8Ne4F+tOi3/F +# NSteo7/rvH0LQnvUU3Ih7jDKu3hlXFsBFwoUDtLaFJj1PLlmWLMtL+f5hYbMUVbo +# nXCUbKw5TNT2eb+qGHpiKe+imyk0BncaYsk9Hm0fgvALxyy7z0Oz5fnsfbXjpKh0 +# NbhOxXEjEiZ2CzxSjHFaRkMUvLOzsE1nyJ9C/4B5IYCeFTBm6EISXhrIniIh0EPp +# K+m79EjMLNTYMoBMJipIJF9a6lbvpt6Znco6b72BJ3QGEe52Ib+bgsEnVLaxaj2J +# oXZhtG6hE6a/qkfwEm/9ijJssv7fUciMI8lmvZ0dhxJkAj0tr1mPuOQh5bWwymO0 +# eFQF1EEuUKyUsKV4q7OglnUa2ZKHE3UiLzKoCG6gW4wlv6DvhMoh1useT8ma7kng +# 9wFlb4kLfchpyOZu6qeXzjEp/w7FW1zYTRuh2Povnj8uVRZryROj/TGCBKcwggSj +# AgEBMIGQMHkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYD +# VQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xIzAh +# BgNVBAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBAhMzAAAAymzVMhI1xOFV +# AAEAAADKMAkGBSsOAwIaBQCggcAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQw +# HAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFFNt +# DhScbWHVDFMkTLRd2qRP8wFeMGAGCisGAQQBgjcCAQwxUjBQoCaAJABXAGkAbgBk +# AG8AdwBzACAAUABvAHcAZQByAFMAaABlAGwAbKEmgCRodHRwOi8vd3d3Lm1pY3Jv +# c29mdC5jb20vcG93ZXJzaGVsbCAwDQYJKoZIhvcNAQEBBQAEggEAddyT//E7Ysbi +# U9kfhQrYkjrhhZCKOzQPVAZSNxWx246MveRe1aj3A+Kr868dYH3x8or8g7MpeJig +# 0WOx4O+mw4fUCdTT6fLqo+W8Q+5qNpWjpfpP5eq7firhhh5D8jB1h7tJWI7fkvHN +# VwadYG4t4BxGIFgsn6YIgPn8ZipmOLb8zvCaDPpg9Xr5U5YKKUrA3sgiuW+zf0aK +# r506K+pfuC56XItbX25VEvf+hjazJr2UasFTweV4mCgKHoAG1UluKUZaX8B+KaKB +# DGMUJ3pCAqyt9RCTSQC9xZxWyK+g0byzn2dpCNxWDXHI7SxCs8ejBhp5yYtlBXl7 +# vkGAXdlJ9aGCAigwggIkBgkqhkiG9w0BCQYxggIVMIICEQIBATCBjjB3MQswCQYD +# VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe +# MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3Nv +# ZnQgVGltZS1TdGFtcCBQQ0ECEzMAAAB0DYBkDn1nfaMAAAAAAHQwCQYFKw4DAhoF +# AKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE1 +# MDUxMTE4MTE1M1owIwYJKoZIhvcNAQkEMRYEFJl30ao3ese0x5O4lPs3SVZVIOdq +# MA0GCSqGSIb3DQEBBQUABIIBAESrx9oY0vI7nyBV0AwzpSYTA/jQF/+MGVokP7ak +# 5i7x25UMc7+RRMROW9VxhzYpzPtotmF8H4rfZsJLxPRlbFF2pu+8MKiNAKiP851m +# tsD1Cw8AN7T31LG8Syk3yKtEvsvnc3yzZy6sXUbkn02yjHNp0PMsrQJNw9ALRc/p +# s3mHzZTqYkmFeHUHzsRa97ByExmjPnP4vcfK2HdZ+oq2EiLjGICooqimt2ys/BPy +# 7nYZaeHaKaNJtnOQHM2BqN38OcH7X7K4IzxCNceXEION6gZE6wqvp+dkvpN5wasL +# OkQhubomAuN/S2TGKwjx3H45G1dpl3LXqihqtqF/Sed7MZs= +# SIG # End signature block diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psm1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psm1 index 611e45d815a..9d5e5254726 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psm1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.psm1 @@ -1,231 +1,231 @@ -Import-LocalizedData LocalizedData -FileName Microsoft.PowerShell.ODataUtilsStrings.psd1 - - -# This module doesn't support Arm because of Add-Type cmdlet -$ProcessorArchitecture = (Get-WmiObject -query "Select Architecture from Win32_Processor").Architecture - -# 0 = x86 -# 1 = MIPS -# 2 = Alpha -# 3 = PowerPC -# 5 = ARM -# 6 = Itanium -# 9 = x64 -if ($ProcessorArchitecture -eq 5) -{ - throw $LocalizedData.ArchitectureNotSupported -f "ARM" -} - -. "$PSScriptRoot\Microsoft.PowerShell.ODataUtilsHelper.ps1" - -######################################################### -# Generates PowerShell module containing client side -# proxy cmdlets that can be used to interact with an -# OData based server side endpoint. -######################################################### -function Export-ODataEndpointProxy -{ - [CmdletBinding( - DefaultParameterSetName='CDXML', - SupportsShouldProcess=$true, - HelpUri="https://go.microsoft.com/fwlink/?LinkId=510069")] - [OutputType([System.IO.FileInfo])] - param - ( - [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] - [ValidateNotNullOrEmpty()] - [string] $Uri, - - [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] - [ValidateNotNullOrEmpty()] - [string] $OutputModule, - - [Parameter(Position=2, ValueFromPipelineByPropertyName=$true)] - [ValidateNotNullOrEmpty()] - [string] $MetadataUri, - - [Parameter(Position=3, ValueFromPipelineByPropertyName=$true)] - [PSCredential] $Credential, - - [Parameter(Position=4, ValueFromPipelineByPropertyName=$true)] - [ValidateSet('Put', 'Post', 'Patch')] - [string] $CreateRequestMethod='Post', - - [Parameter(Position=5, ValueFromPipelineByPropertyName=$true)] - [ValidateSet('Put', 'Post', 'Patch')] - [string] $UpdateRequestMethod='Patch', - - [Parameter(Position=6, ValueFromPipelineByPropertyName=$true)] - [ValidateSet('ODataAdapter', 'NetworkControllerAdapter', 'ODataV4Adapter')] - [string] $CmdletAdapter='ODataAdapter', - - [Parameter(Position=7, ValueFromPipelineByPropertyName=$true)] - [Hashtable] $ResourceNameMapping, - - [parameter (Position=8,ValueFromPipelineByPropertyName=$true)] - [switch] $Force, - - [Parameter(Position=9, ValueFromPipelineByPropertyName=$true)] - [Hashtable] $CustomData, - - [parameter (Position=10,ValueFromPipelineByPropertyName=$true)] - [switch] $AllowClobber, - - [parameter (Position=11,ValueFromPipelineByPropertyName=$true)] - [switch] $AllowUnsecureConnection, - - [parameter (Position=12,ValueFromPipelineByPropertyName=$true)] - [ValidateNotNull()] - [Hashtable] $Headers - ) - - BEGIN - { - if (!$MetadataUri) - { - $Uri = $Uri.TrimEnd('/') - $MetadataUri = $Uri + '/$metadata' - $PSBoundParameters["MetadataUri"] = $MetadataUri - } - - # Validate to make sure that a valid URI is supplied as input. - try - { - $connectionUri = [System.Uri]::new($Uri) - } - catch - { - $errorMessage = ($LocalizedData.InValidUri -f $Uri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $Uri - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - # Block Redfish-support for in-box version of the module and advise user to use a version from PS Gallery instead. - # According to Redfish specification DSP0266v1.0.1 Redfish Service Metadata Document and Redfish Service Root URIs (used by Export-ODataEndpointProxy) are required to start with '/redfish/v1' (section "6.3 Redfish-Defined URIs and Relative URI Rules"). - # We use this as indicator of whether Export-ODataEndpointProxy was attempted against a Redfish endpoint. - if($connectionUri.AbsolutePath.StartsWith('/redfish/',[StringComparison]::OrdinalIgnoreCase)) - { - $errorMessage = $LocalizedData.RedfishNotEnabled - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyRedfishNotEnabled" $errorMessage ([System.Management.Automation.ErrorCategory]::NotEnabled) $exception $Uri - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - if($connectionUri.Scheme -eq "http" -and !$AllowUnsecureConnection.IsPresent) - { - $errorMessage = ($LocalizedData.AllowUnsecureConnectionMessage -f $PSCmdlet.MyInvocation.MyCommand.Name, $Uri, "Uri") - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyUnSecureConnection" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $Uri - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - $OutputModuleExists = Test-Path -Path $OutputModule -PathType Container - - if($OutputModuleExists -and ($Force -eq $false)) - { - $errorMessage = ($LocalizedData.ModuleAlreadyExistsAndForceParameterIsNotSpecified -f $OutputModule) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyOutputModuleExists" $errorMessage ([System.Management.Automation.ErrorCategory]::ResourceExists) $null $OutputModule - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - $isWhatIf = $psboundparameters.ContainsKey("WhatIf") - - if(!$OutputModuleExists) - { - if(!$isWhatIf) - { - $OutputModule = (New-Item -Path $OutputModule -ItemType Directory).FullName - } - } - else - { - $resolvedOutputModulePath = Resolve-Path -Path $OutputModule -ErrorAction Stop -Verbose - if($resolvedOutputModulePath.Count -gt 1) - { - $errorMessage = ($LocalizedData.OutputModulePathIsNotUnique -f $OutputModule) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyOutputModulePathIsNotUnique" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - # Make sure that the path specified is a valid file system directory path. - if([system.IO.Directory]::Exists($resolvedOutputModulePath)) - { - $OutputModule = $resolvedOutputModulePath - } - else - { - $errorMessage = ($LocalizedData.OutputModulePathIsNotFileSystemPath -f $OutputModule) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyPathIsNotFileSystemPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - } - - $rootDir = [System.IO.Directory]::GetDirectoryRoot($OutputModule) - - if($rootDir -eq $OutputModule) - { - $errorMessage = ($LocalizedData.InvalidOutputModulePath -f $OutputModule) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidOutputModulePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - - if(!$isWhatIf) - { - $progressBarStatus = ($LocalizedData.ProgressBarMessage -f $Uri) - ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 0 100 100 1 - } - - # Add parameters to $PSBoundParameters, which were not passed by user, but the default value is set - $parametersWithDefaultValue = @("CreateRequestMethod", "UpdateRequestMethod", "CmdletAdapter") - - foreach ($parameterWithDefaultValue in $parametersWithDefaultValue) - { - if (!$PSBoundParameters.ContainsKey($parameterWithDefaultValue)) - { - $PSBoundParameters.Add($parameterWithDefaultValue, (Get-Variable $parameterWithDefaultValue).Value) - } - } - } - - END - { - if($pscmdlet.ShouldProcess($Uri)) - { - try - { - $PSBoundParameters.Add("ProgressBarStatus", $progressBarStatus) - $PSBoundParameters.Add("PSCmdlet", $PSCmdlet) - - # Import module based on selected CmdletAdapter - $adapterToImport = $CmdletAdapter - - # NetworkControllerAdapter relies on ODataAdapter - if ($CmdletAdapter -eq 'NetworkControllerAdapter') - { - $adapterToImport = 'ODataAdapter' - } - - Write-Debug ($LocalizedData.SelectedAdapter -f $adapterPSScript) - - $adapterPSScript = "$PSScriptRoot\Microsoft.PowerShell." + $adapterToImport + ".ps1" - - . $adapterPSScript - ExportODataEndpointProxy @PSBoundParameters - } - catch - { - $errorMessage = ($LocalizedData.InValidMetadata -f $Uri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidInput" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $Uri - $PSCmdlet.ThrowTerminatingError($errorRecord) - } - finally - { - Write-Progress -Activity "Export-ODataEndpointProxy" -Completed - } - } - } -} - -Export-ModuleMember -Function @('Export-ODataEndpointProxy') +Import-LocalizedData LocalizedData -FileName Microsoft.PowerShell.ODataUtilsStrings.psd1 + + +# This module doesn't support Arm because of Add-Type cmdlet +$ProcessorArchitecture = (Get-WmiObject -query "Select Architecture from Win32_Processor").Architecture + +# 0 = x86 +# 1 = MIPS +# 2 = Alpha +# 3 = PowerPC +# 5 = ARM +# 6 = Itanium +# 9 = x64 +if ($ProcessorArchitecture -eq 5) +{ + throw $LocalizedData.ArchitectureNotSupported -f "ARM" +} + +. "$PSScriptRoot\Microsoft.PowerShell.ODataUtilsHelper.ps1" + +######################################################### +# Generates PowerShell module containing client side +# proxy cmdlets that can be used to interact with an +# OData based server side endpoint. +######################################################### +function Export-ODataEndpointProxy +{ + [CmdletBinding( + DefaultParameterSetName='CDXML', + SupportsShouldProcess=$true, + HelpUri="https://go.microsoft.com/fwlink/?LinkId=510069")] + [OutputType([System.IO.FileInfo])] + param + ( + [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [string] $Uri, + + [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [string] $OutputModule, + + [Parameter(Position=2, ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [string] $MetadataUri, + + [Parameter(Position=3, ValueFromPipelineByPropertyName=$true)] + [PSCredential] $Credential, + + [Parameter(Position=4, ValueFromPipelineByPropertyName=$true)] + [ValidateSet('Put', 'Post', 'Patch')] + [string] $CreateRequestMethod='Post', + + [Parameter(Position=5, ValueFromPipelineByPropertyName=$true)] + [ValidateSet('Put', 'Post', 'Patch')] + [string] $UpdateRequestMethod='Patch', + + [Parameter(Position=6, ValueFromPipelineByPropertyName=$true)] + [ValidateSet('ODataAdapter', 'NetworkControllerAdapter', 'ODataV4Adapter')] + [string] $CmdletAdapter='ODataAdapter', + + [Parameter(Position=7, ValueFromPipelineByPropertyName=$true)] + [Hashtable] $ResourceNameMapping, + + [parameter (Position=8,ValueFromPipelineByPropertyName=$true)] + [switch] $Force, + + [Parameter(Position=9, ValueFromPipelineByPropertyName=$true)] + [Hashtable] $CustomData, + + [parameter (Position=10,ValueFromPipelineByPropertyName=$true)] + [switch] $AllowClobber, + + [parameter (Position=11,ValueFromPipelineByPropertyName=$true)] + [switch] $AllowUnsecureConnection, + + [parameter (Position=12,ValueFromPipelineByPropertyName=$true)] + [ValidateNotNull()] + [Hashtable] $Headers + ) + + BEGIN + { + if (!$MetadataUri) + { + $Uri = $Uri.TrimEnd('/') + $MetadataUri = $Uri + '/$metadata' + $PSBoundParameters["MetadataUri"] = $MetadataUri + } + + # Validate to make sure that a valid URI is supplied as input. + try + { + $connectionUri = [System.Uri]::new($Uri) + } + catch + { + $errorMessage = ($LocalizedData.InValidUri -f $Uri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $Uri + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + # Block Redfish-support for in-box version of the module and advise user to use a version from PS Gallery instead. + # According to Redfish specification DSP0266v1.0.1 Redfish Service Metadata Document and Redfish Service Root URIs (used by Export-ODataEndpointProxy) are required to start with '/redfish/v1' (section "6.3 Redfish-Defined URIs and Relative URI Rules"). + # We use this as indicator of whether Export-ODataEndpointProxy was attempted against a Redfish endpoint. + if($connectionUri.AbsolutePath.StartsWith('/redfish/',[StringComparison]::OrdinalIgnoreCase)) + { + $errorMessage = $LocalizedData.RedfishNotEnabled + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyRedfishNotEnabled" $errorMessage ([System.Management.Automation.ErrorCategory]::NotEnabled) $exception $Uri + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + if($connectionUri.Scheme -eq "http" -and !$AllowUnsecureConnection.IsPresent) + { + $errorMessage = ($LocalizedData.AllowUnsecureConnectionMessage -f $PSCmdlet.MyInvocation.MyCommand.Name, $Uri, "Uri") + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyUnSecureConnection" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $Uri + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + $OutputModuleExists = Test-Path -Path $OutputModule -PathType Container + + if($OutputModuleExists -and ($Force -eq $false)) + { + $errorMessage = ($LocalizedData.ModuleAlreadyExistsAndForceParameterIsNotSpecified -f $OutputModule) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyOutputModuleExists" $errorMessage ([System.Management.Automation.ErrorCategory]::ResourceExists) $null $OutputModule + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + $isWhatIf = $psboundparameters.ContainsKey("WhatIf") + + if(!$OutputModuleExists) + { + if(!$isWhatIf) + { + $OutputModule = (New-Item -Path $OutputModule -ItemType Directory).FullName + } + } + else + { + $resolvedOutputModulePath = Resolve-Path -Path $OutputModule -ErrorAction Stop -Verbose + if($resolvedOutputModulePath.Count -gt 1) + { + $errorMessage = ($LocalizedData.OutputModulePathIsNotUnique -f $OutputModule) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyOutputModulePathIsNotUnique" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + # Make sure that the path specified is a valid file system directory path. + if([system.IO.Directory]::Exists($resolvedOutputModulePath)) + { + $OutputModule = $resolvedOutputModulePath + } + else + { + $errorMessage = ($LocalizedData.OutputModulePathIsNotFileSystemPath -f $OutputModule) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyPathIsNotFileSystemPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + } + + $rootDir = [System.IO.Directory]::GetDirectoryRoot($OutputModule) + + if($rootDir -eq $OutputModule) + { + $errorMessage = ($LocalizedData.InvalidOutputModulePath -f $OutputModule) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidOutputModulePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $OutputModule + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + + if(!$isWhatIf) + { + $progressBarStatus = ($LocalizedData.ProgressBarMessage -f $Uri) + ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 0 100 100 1 + } + + # Add parameters to $PSBoundParameters, which were not passed by user, but the default value is set + $parametersWithDefaultValue = @("CreateRequestMethod", "UpdateRequestMethod", "CmdletAdapter") + + foreach ($parameterWithDefaultValue in $parametersWithDefaultValue) + { + if (!$PSBoundParameters.ContainsKey($parameterWithDefaultValue)) + { + $PSBoundParameters.Add($parameterWithDefaultValue, (Get-Variable $parameterWithDefaultValue).Value) + } + } + } + + END + { + if($pscmdlet.ShouldProcess($Uri)) + { + try + { + $PSBoundParameters.Add("ProgressBarStatus", $progressBarStatus) + $PSBoundParameters.Add("PSCmdlet", $PSCmdlet) + + # Import module based on selected CmdletAdapter + $adapterToImport = $CmdletAdapter + + # NetworkControllerAdapter relies on ODataAdapter + if ($CmdletAdapter -eq 'NetworkControllerAdapter') + { + $adapterToImport = 'ODataAdapter' + } + + Write-Debug ($LocalizedData.SelectedAdapter -f $adapterPSScript) + + $adapterPSScript = "$PSScriptRoot\Microsoft.PowerShell." + $adapterToImport + ".ps1" + + . $adapterPSScript + ExportODataEndpointProxy @PSBoundParameters + } + catch + { + $errorMessage = ($LocalizedData.InValidMetadata -f $Uri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidInput" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $Uri + $PSCmdlet.ThrowTerminatingError($errorRecord) + } + finally + { + Write-Progress -Activity "Export-ODataEndpointProxy" -Completed + } + } + } +} + +Export-ModuleMember -Function @('Export-ODataEndpointProxy') diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 index 8a4c65424f1..473d39909e2 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 @@ -1,782 +1,782 @@ -# Base class definitions used by the actual Adapter modules -$global:BaseClassDefinitions = @" -using System; - -namespace ODataUtils -{ - public class TypeProperty - { - public String Name; - - // OData Type Name, e.g. Edm.Int32 - public String TypeName; - - public bool IsKey; - public bool IsMandatory; - public bool? IsNullable; - } - - public class NavigationProperty - { - public String Name; - - public String FromRole; - public String ToRole; - public String AssociationNamespace; - public String AssociationName; - } - - public class EntityTypeBase - { - public String Namespace; - public String Name; - public TypeProperty[] EntityProperties; - public bool IsEntity; - public EntityTypeBase BaseType; - } - - public class AssociationType - { - public String Namespace; - - public EntityTypeBase EndType1; - public String Multiplicity1; - public String NavPropertyName1; - - public EntityTypeBase EndType2; - public String Multiplicity2; - public String NavPropertyName2; - } - - public class EntitySet - { - public String Namespace; - public String Name; - public EntityTypeBase Type; - } - - public class AssociationSet - { - public String Namespace; - public String Name; - public AssociationType Type; - } - - public class Action - { - public String Namespace; - public String Verb; - public EntitySet EntitySet; - public Boolean IsSideEffecting; - public Boolean IsBindable; - public Boolean IsSingleInstance; - public TypeProperty[] Parameters; - } - - public class MetadataBase - { - // Desired destination namespace - public String Namespace; - } - - public class CmdletParameter - { - public CmdletParameter() - { - } - - public CmdletParameter(String type, String name) - { - this.Type = type; - this.Name = name; - this.Qualifiers = new String[] { "Parameter(ValueFromPipelineByPropertyName=`$true)" }; - } - - public String[] Qualifiers; - public String Type; - public String Name; - } - - public class CmdletParameters - { - public CmdletParameter[] Parameters; - } - - public class ReferentialConstraint - { - public String Property; - public String ReferencedProperty; - } - - public class OnDelete - { - public String Action; - } - - public class NavigationPropertyV4 - { - public String Name; - public String Type; - public bool Nullable; - public String Partner; - public bool ContainsTarget; - public ReferentialConstraint[] ReferentialConstraints; - public OnDelete OnDelete; - } - - public class NavigationPropertyBinding - { - public String Path; - public String Target; - } - - public class EntityTypeV4 : EntityTypeBase - { - public String Alias; - public NavigationPropertyV4[] NavigationProperties; - public String BaseTypeStr; - } - - public class SingletonType - { - public String Namespace; - public String Alias; - public String Name; - public String Type; - public NavigationPropertyBinding[] NavigationPropertyBindings; - } - - public class EntitySetV4 - { - public String Namespace; - public String Alias; - public String Name; - public EntityTypeV4 Type; - } - - public class EnumMember - { - public String Name; - public String Value; - } - - public class EnumType - { - public String Namespace; - public String Alias; - public String Name; - public String UnderlyingType; - public bool IsFlags; - public EnumMember[] Members; - } - - public class ActionV4 - { - public String Namespace; - public String Alias; - public String Name; - public String Action; - public EntitySetV4 EntitySet; - public TypeProperty[] Parameters; - } - - public class FunctionV4 - { - public String Namespace; - public String Alias; - public String Name; - public bool Function; - public String EntitySet; - public String ReturnType; - public Parameter[] Parameters; - } - - public class Parameter - { - public String Name; - public String Type; - public bool Nullable; - } - - public class ReferenceInclude - { - public String Namespace; - public String Alias; - } - - public class Reference - { - public String Uri; - } - - public class MetadataV4 : MetadataBase - { - public string ODataVersion; - public string Uri; - public string MetadataUri; - public string Alias; - public Reference[] References; - public string DefaultEntityContainerName; - public EntitySetV4[] EntitySets; - public EntityTypeV4[] EntityTypes; - public SingletonType[] SingletonTypes; - public EntityTypeV4[] ComplexTypes; - public EntityTypeV4[] TypeDefinitions; - public EnumType[] EnumTypes; - public ActionV4[] Actions; - public FunctionV4[] Functions; - } - - public class ReferencedMetadata - { - public System.Collections.ArrayList References; - } - - public class ODataEndpointProxyParameters - { - public String Uri; - public String MetadataUri; - public System.Management.Automation.PSCredential Credential; - public String OutputModule; - - public bool Force; - public bool AllowClobber; - public bool AllowUnsecureConnection; - } - - public class EntityType : EntityTypeBase - { - public NavigationProperty[] NavigationProperties; - } - - public class Metadata : MetadataBase - { - public String DefaultEntityContainerName; - public EntitySet[] EntitySets; - public EntityType[] EntityTypes; - public EntityType[] ComplexTypes; - public AssociationSet[] Associations; - public Action[] Actions; - } -} -"@ - -######################################################### -# GetMetaData is a helper function used to fetch metadata -# from the specified file or web URL. -######################################################### -function GetMetaData -{ - param - ( - [string] $metaDataUri, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet, - [PSCredential] $credential, - [Hashtable] $headers - ) - - # $metaDataUri is already validated at the cmdlet layer. - if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GetMetaData") } - Write-Verbose ($LocalizedData.VerboseReadingMetadata -f $metaDataUri) - - try - { - $uri = [System.Uri]::new($metadataUri) - - # By default, proxy generation is supported on secured Uri (i.e., https). - # However if the user trusts the unsecure http uri, then they can override - # the security check by specifying -AllowSecureConnection parameter during - # proxy generation. - if($uri.Scheme -eq "http" -and !$AllowUnsecureConnection.IsPresent) - { - $errorMessage = ($LocalizedData.AllowUnsecureConnectionMessage -f $callerPSCmdlet.MyInvocation.MyCommand.Name, $uri, "MetaDataUri") - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyUnSecureConnection" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $uri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - catch - { - $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadataUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - if($uri.IsFile) - { - if ($null -ne $credential) - { - $fileExists = Test-Path -Path $metaDataUri -PathType Leaf -Credential $credential -ErrorAction Stop - } - else - { - $fileExists = Test-Path -Path $metaDataUri -PathType Leaf -ErrorAction Stop - } - - if($fileExists) - { - $metaData = Get-Content -Path $metaDataUri -ErrorAction Stop - } - else - { - $errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataFileDoesNotExist" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - else - { - try - { - $cmdParams = @{'Uri'= $metaDataUri ; 'UseBasicParsing'=$true; 'ErrorAction'= 'Stop'} - - if ($null -ne $credential) - { - $cmdParams.Add('Credential', $credential) - } - - if ($null -ne $headers) - { - $cmdParams.Add('Headers', $headers) - } - - $webResponse = Invoke-WebRequest @cmdParams - } - catch - { - $errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataUriDoesNotExist" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - - if($null -ne $webResponse) - { - if ($webResponse.StatusCode -eq 200) - { - $metaData = $webResponse.Content - - if ($null -eq $metadata) - { - $errorMessage = ($LocalizedData.EmptyMetadata -f $MetadataUri) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataIsEmpty" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - else - { - $errorMessage = ($LocalizedData.InvalidEndpointAddress -f $MetadataUri, $webResponse.StatusCode) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidEndpointAddress" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - } - - if($null -ne $metaData) - { - try - { - [xml] $metadataXML = $metaData - } - catch - { - $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) - $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) - $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri - $callerPSCmdlet.ThrowTerminatingError($errorRecord) - } - } - - return $metadataXML -} - -######################################################### -# VerifyMetadataHelper is a helper function used to -# validate if Error/Warning message has to be displayed -# during command collision. -######################################################### -function VerifyMetadataHelper -{ - param - ( - [string] $localizedDataErrorString, - [string] $localizedDataWarningString, - [string] $entitySetName, - [string] $currentCommandName, - [string] $metaDataUri, - [boolean] $allowClobber, - [System.Management.Automation.PSCmdlet] $callerPSCmdlet - ) - - if($null -eq $localizedDataErrorString) { throw ($LocalizedData.ArguementNullError -f "localizedDataErrorString", "VerifyMetadataHelper") } - if($null -eq $localizedDataWarningString) { throw ($LocalizedData.ArguementNullError -f "localizedDataWarningString", "VerifyMetadataHelper") } - - if(!$allowClobber) - { - # Write Error message and skip current Entity Set. - $errorMessage = ($localizedDataErrorString -f $entitySetName, $currentCommandName) - $exception = [System.InvalidOperationException]::new($errorMessage) - $errorRecord = CreateErrorRecordHelper "ODataEndpointDefaultPropertyCollision" $null ([System.Management.Automation.ErrorCategory]::InvalidOperation) $exception $metaDataUri - $callerPSCmdlet.WriteError($errorRecord) - } - else - { - $warningMessage = ($localizedDataWarningString -f $entitySetName, $currentCommandName) - $callerPSCmdlet.WriteWarning($warningMessage) - } -} - -######################################################### -# CreateErrorRecordHelper is a helper function used to -# create an error record. -######################################################### -function CreateErrorRecordHelper -{ - param - ( - [string] $errorId, - [string] $errorMessage, - [System.Management.Automation.ErrorCategory] $errorCategory, - [Exception] $exception, - [object] $targetObject - ) - - if($null -eq $exception) - { - $exception = New-Object System.IO.IOException $errorMessage - } - - $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject - return $errorRecord -} - -######################################################### -# ProgressBarHelper is a helper function used to -# used to display progress message. -######################################################### -function ProgressBarHelper -{ - param - ( - [string] $cmdletName, - [string] $status, - [double] $previousSegmentWeight, - [double] $currentSegmentWeight, - [int] $totalNumberofEntries, - [int] $currentEntryCount - ) - - if($null -eq $cmdletName) { throw ($LocalizedData.ArguementNullError -f "CmdletName", "ProgressBarHelper") } - if($null -eq $status) { throw ($LocalizedData.ArguementNullError -f "Status", "ProgressBarHelper") } - - if($currentEntryCount -gt 0 -and - $totalNumberofEntries -gt 0 -and - $previousSegmentWeight -ge 0 -and - $currentSegmentWeight -gt 0) - { - $entryDefaultWeight = $currentSegmentWeight/[double]$totalNumberofEntries - $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount) - Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete - } -} - -######################################################### -# Convert-ODataTypeToCLRType is a helper function used to -# Convert OData type to its CLR equivalent. -######################################################### -function Convert-ODataTypeToCLRType -{ - param - ( - [string] $typeName, - [Hashtable] $complexTypeMapping - ) - - if($null -eq $typeName) { throw ($LocalizedData.ArguementNullError -f "TypeName", "Convert-ODataTypeToCLRType ") } - - switch ($typeName) - { - "Edm.Binary" {"Byte[]"} - "Edm.Boolean" {"Boolean"} - "Edm.Byte" {"Byte"} - "Edm.DateTime" {"DateTime"} - "Edm.Decimal" {"Decimal"} - "Edm.Double" {"Double"} - "Edm.Single" {"Single"} - "Edm.Guid" {"Guid"} - "Edm.Int16" {"Int16"} - "Edm.Int32" {"Int32"} - "Edm.Int64" {"Int64"} - "Edm.SByte" {"SByte"} - "Edm.String" {"String"} - "Edm.PropertyPath" {"String"} - "switch" {"switch"} - "Edm.DateTimeOffset" {"DateTimeOffset"} - default - { - if($null -ne $complexTypeMapping -and - $complexTypeMapping.Count -gt 0 -and - $complexTypeMapping.ContainsKey($typeName)) - { - $typeName - } - else - { - $regex = "Collection\((.+)\)" - if ($typeName -match $regex) - { - $insideTypeName = Convert-ODataTypeToCLRType $Matches[1] $complexTypeMapping - "$insideTypeName[]" - } - else - { - "PSObject" - } - } - } - } -} - -######################################################### -# SaveCDXMLHeader is a helper function used -# to save CDXML headers common to all -# PSODataUtils modules. -######################################################### -function SaveCDXMLHeader -{ - param - ( - [System.Xml.XmlWriter] $xmlWriter, - [string] $uri, - [string] $className, - [string] $defaultNoun, - [string] $cmdletAdapter - ) - - # $uri & $cmdletAdapter are already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLHeader") } - if($null -eq $defaultNoun) { throw ($LocalizedData.ArguementNullError -f "DefaultNoun", "SaveCDXMLHeader") } - - if ($className -eq 'ServiceActions' -Or $cmdletAdapter -eq "NetworkControllerAdapter") - { - $entityName = '' - } - else - { - $entityName = $className - } - - if ($uri[-1] -ne '/') - { - $fullName = "$uri/$entityName" - } - else - { - $fullName = "$uri$entityName" - } - - $xmlWriter.Formatting = 'Indented' - $xmlWriter.Indentation = 2 - $xmlWriter.IndentChar = ' ' - - $xmlWriter.WriteStartDocument() - - $today=Get-Date - $xmlWriter.WriteComment("This module was autogenerated by PSODataUtils on $today.") - - $xmlWriter.WriteStartElement('PowerShellMetadata') - $xmlWriter.WriteAttributeString('xmlns', 'http://schemas.microsoft.com/cmdlets-over-objects/2009/11') - - $xmlWriter.WriteStartElement('Class') - $xmlWriter.WriteAttributeString('ClassName', $fullName) - $xmlWriter.WriteAttributeString('ClassVersion', '1.0.0') - - $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataCmdletAdapter' - - if ($CmdletAdapter -eq "NetworkControllerAdapter") { - $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.NetworkControllerCmdletAdapter' - } - elseif ($CmdletAdapter -eq "ODataV4Adapter") { - $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataV4CmdletAdapter' - } - - $xmlWriter.WriteAttributeString('CmdletAdapter', $DotNetAdapter + ', Microsoft.PowerShell.Cmdletization.OData, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35') - - $xmlWriter.WriteElementString('Version', '1.0') - $xmlWriter.WriteElementString('DefaultNoun', $defaultNoun) - - $xmlWriter -} - -######################################################### -# SaveCDXMLFooter is a helper function used -# to save CDXML closing attributes corresponding -# to SaveCDXMLHeader function. -######################################################### -function SaveCDXMLFooter -{ - param - ( - [System.Xml.XmlWriter] $xmlWriter - ) - - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFooter") } - - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndDocument() - - $xmlWriter.Flush() - $xmlWriter.Close() -} - -######################################################### -# AddParametersNode is a helper function used -# to add parameters to the generated proxy cmdlet, -# based on mandatoryProperties and otherProperties. -# PrefixForKeys is used by associations to append a -# prefix to PowerShell parameter name. -######################################################### -function AddParametersNode -{ - param - ( - [Parameter(Mandatory=$true)] - [System.Xml.XmlWriter] $xmlWriter, - [ODataUtils.TypeProperty[]] $keyProperties, - [ODataUtils.TypeProperty[]] $mandatoryProperties, - [ODataUtils.TypeProperty[]] $otherProperties, - [string] $prefixForKeys, - [boolean] $addForceParameter, - [boolean] $addParametersElement, - [Hashtable] $complexTypeMapping - ) - - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } - - if(($keyProperties.Length -gt 0) -or - ($mandatoryProperties.Length -gt 0) -or - ($otherProperties.Length -gt 0) -or - ($addForceParameter)) - { - if($addParametersElement) - { - $xmlWriter.WriteStartElement('Parameters') - } - - $pos = 0 - - if ($null -ne $keyProperties) - { - $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping - } - - if ($null -ne $mandatoryProperties) - { - $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping - } - - if ($null -ne $otherProperties) - { - $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping - } - - if($addForceParameter) - { - $forceParameter = [ODataUtils.TypeProperty] @{ - "Name" = "Force"; - "TypeName" = "switch"; - "IsNullable" = $false - } - - $pos = AddParametersCDXML $xmlWriter $forceParameter $pos $false $null $null $complexTypeMapping - } - - if($addParametersElement) - { - $xmlWriter.WriteEndElement() - } - } -} - -######################################################### -# AddParametersCDXML is a helper function used -# to add Parameter node to CDXML based on properties. -# Prefix is appended to PS parameter names, used for -# associations. Suffix is appended to all parameter -# names, for ex. to differentiate keys. returns new $pos -######################################################### -function AddParametersCDXML -{ - param - ( - [Parameter(Mandatory=$true)] - [System.Xml.XmlWriter] $xmlWriter, - [ODataUtils.TypeProperty[]] $properties, - [Parameter(Mandatory=$true)] - [int] $pos, - [bool] $isMandatory, - [string] $prefix, - [string] $suffix, - [Hashtable] $complexTypeMapping - ) - - $properties | Where-Object { $null -ne $_ } | ForEach-Object { - $xmlWriter.WriteStartElement('Parameter') - $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) - $xmlWriter.WriteStartElement('Type') - $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping - $xmlWriter.WriteAttributeString('PSType', $PSTypeName) - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('CmdletParameterMetadata') - $xmlWriter.WriteAttributeString('PSName', $prefix + $_.Name) - $xmlWriter.WriteAttributeString('IsMandatory', ($isMandatory).ToString().ToLowerInvariant()) - $xmlWriter.WriteAttributeString('Position', $pos) - if($isMandatory) - { - $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') - } - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() - - $pos++ - } - - $pos -} - -######################################################### -# GenerateSetProxyCmdlet is a helper function used -# to generate Set-* proxy cmdlet. The proxy cmdlet is -# generated in the CDXML compliant format. -######################################################### -function GenerateSetProxyCmdlet -{ - param - ( - [System.XMl.XmlTextWriter] $xmlWriter, - [object[]] $keyProperties, - [object[]] $nonKeyProperties, - [Hashtable] $complexTypeMapping - ) - - # $cmdletAdapter is already validated at the cmdlet layer. - if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateSetProxyCmdlet") } - - $xmlWriter.WriteStartElement('Cmdlet') - $xmlWriter.WriteStartElement('CmdletMetadata') - $xmlWriter.WriteAttributeString('Verb', 'Set') - $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') - $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') - $xmlWriter.WriteEndElement() - - $xmlWriter.WriteStartElement('Method') - $xmlWriter.WriteAttributeString('MethodName', 'Update') - $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') - - AddParametersNode $xmlWriter $keyProperties $null $nonKeyProperties $null $true $true $complexTypeMapping - $xmlWriter.WriteEndElement() - $xmlWriter.WriteEndElement() -} +# Base class definitions used by the actual Adapter modules +$global:BaseClassDefinitions = @" +using System; + +namespace ODataUtils +{ + public class TypeProperty + { + public String Name; + + // OData Type Name, e.g. Edm.Int32 + public String TypeName; + + public bool IsKey; + public bool IsMandatory; + public bool? IsNullable; + } + + public class NavigationProperty + { + public String Name; + + public String FromRole; + public String ToRole; + public String AssociationNamespace; + public String AssociationName; + } + + public class EntityTypeBase + { + public String Namespace; + public String Name; + public TypeProperty[] EntityProperties; + public bool IsEntity; + public EntityTypeBase BaseType; + } + + public class AssociationType + { + public String Namespace; + + public EntityTypeBase EndType1; + public String Multiplicity1; + public String NavPropertyName1; + + public EntityTypeBase EndType2; + public String Multiplicity2; + public String NavPropertyName2; + } + + public class EntitySet + { + public String Namespace; + public String Name; + public EntityTypeBase Type; + } + + public class AssociationSet + { + public String Namespace; + public String Name; + public AssociationType Type; + } + + public class Action + { + public String Namespace; + public String Verb; + public EntitySet EntitySet; + public Boolean IsSideEffecting; + public Boolean IsBindable; + public Boolean IsSingleInstance; + public TypeProperty[] Parameters; + } + + public class MetadataBase + { + // Desired destination namespace + public String Namespace; + } + + public class CmdletParameter + { + public CmdletParameter() + { + } + + public CmdletParameter(String type, String name) + { + this.Type = type; + this.Name = name; + this.Qualifiers = new String[] { "Parameter(ValueFromPipelineByPropertyName=`$true)" }; + } + + public String[] Qualifiers; + public String Type; + public String Name; + } + + public class CmdletParameters + { + public CmdletParameter[] Parameters; + } + + public class ReferentialConstraint + { + public String Property; + public String ReferencedProperty; + } + + public class OnDelete + { + public String Action; + } + + public class NavigationPropertyV4 + { + public String Name; + public String Type; + public bool Nullable; + public String Partner; + public bool ContainsTarget; + public ReferentialConstraint[] ReferentialConstraints; + public OnDelete OnDelete; + } + + public class NavigationPropertyBinding + { + public String Path; + public String Target; + } + + public class EntityTypeV4 : EntityTypeBase + { + public String Alias; + public NavigationPropertyV4[] NavigationProperties; + public String BaseTypeStr; + } + + public class SingletonType + { + public String Namespace; + public String Alias; + public String Name; + public String Type; + public NavigationPropertyBinding[] NavigationPropertyBindings; + } + + public class EntitySetV4 + { + public String Namespace; + public String Alias; + public String Name; + public EntityTypeV4 Type; + } + + public class EnumMember + { + public String Name; + public String Value; + } + + public class EnumType + { + public String Namespace; + public String Alias; + public String Name; + public String UnderlyingType; + public bool IsFlags; + public EnumMember[] Members; + } + + public class ActionV4 + { + public String Namespace; + public String Alias; + public String Name; + public String Action; + public EntitySetV4 EntitySet; + public TypeProperty[] Parameters; + } + + public class FunctionV4 + { + public String Namespace; + public String Alias; + public String Name; + public bool Function; + public String EntitySet; + public String ReturnType; + public Parameter[] Parameters; + } + + public class Parameter + { + public String Name; + public String Type; + public bool Nullable; + } + + public class ReferenceInclude + { + public String Namespace; + public String Alias; + } + + public class Reference + { + public String Uri; + } + + public class MetadataV4 : MetadataBase + { + public string ODataVersion; + public string Uri; + public string MetadataUri; + public string Alias; + public Reference[] References; + public string DefaultEntityContainerName; + public EntitySetV4[] EntitySets; + public EntityTypeV4[] EntityTypes; + public SingletonType[] SingletonTypes; + public EntityTypeV4[] ComplexTypes; + public EntityTypeV4[] TypeDefinitions; + public EnumType[] EnumTypes; + public ActionV4[] Actions; + public FunctionV4[] Functions; + } + + public class ReferencedMetadata + { + public System.Collections.ArrayList References; + } + + public class ODataEndpointProxyParameters + { + public String Uri; + public String MetadataUri; + public System.Management.Automation.PSCredential Credential; + public String OutputModule; + + public bool Force; + public bool AllowClobber; + public bool AllowUnsecureConnection; + } + + public class EntityType : EntityTypeBase + { + public NavigationProperty[] NavigationProperties; + } + + public class Metadata : MetadataBase + { + public String DefaultEntityContainerName; + public EntitySet[] EntitySets; + public EntityType[] EntityTypes; + public EntityType[] ComplexTypes; + public AssociationSet[] Associations; + public Action[] Actions; + } +} +"@ + +######################################################### +# GetMetaData is a helper function used to fetch metadata +# from the specified file or web URL. +######################################################### +function GetMetaData +{ + param + ( + [string] $metaDataUri, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet, + [PSCredential] $credential, + [Hashtable] $headers + ) + + # $metaDataUri is already validated at the cmdlet layer. + if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GetMetaData") } + Write-Verbose ($LocalizedData.VerboseReadingMetadata -f $metaDataUri) + + try + { + $uri = [System.Uri]::new($metadataUri) + + # By default, proxy generation is supported on secured Uri (i.e., https). + # However if the user trusts the unsecure http uri, then they can override + # the security check by specifying -AllowSecureConnection parameter during + # proxy generation. + if($uri.Scheme -eq "http" -and !$AllowUnsecureConnection.IsPresent) + { + $errorMessage = ($LocalizedData.AllowUnsecureConnectionMessage -f $callerPSCmdlet.MyInvocation.MyCommand.Name, $uri, "MetaDataUri") + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyUnSecureConnection" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $uri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + catch + { + $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadataUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + if($uri.IsFile) + { + if ($null -ne $credential) + { + $fileExists = Test-Path -Path $metaDataUri -PathType Leaf -Credential $credential -ErrorAction Stop + } + else + { + $fileExists = Test-Path -Path $metaDataUri -PathType Leaf -ErrorAction Stop + } + + if($fileExists) + { + $metaData = Get-Content -Path $metaDataUri -ErrorAction Stop + } + else + { + $errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataFileDoesNotExist" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + else + { + try + { + $cmdParams = @{'Uri'= $metaDataUri ; 'UseBasicParsing'=$true; 'ErrorAction'= 'Stop'} + + if ($null -ne $credential) + { + $cmdParams.Add('Credential', $credential) + } + + if ($null -ne $headers) + { + $cmdParams.Add('Headers', $headers) + } + + $webResponse = Invoke-WebRequest @cmdParams + } + catch + { + $errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataUriDoesNotExist" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + + if($null -ne $webResponse) + { + if ($webResponse.StatusCode -eq 200) + { + $metaData = $webResponse.Content + + if ($null -eq $metadata) + { + $errorMessage = ($LocalizedData.EmptyMetadata -f $MetadataUri) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataIsEmpty" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + else + { + $errorMessage = ($LocalizedData.InvalidEndpointAddress -f $MetadataUri, $webResponse.StatusCode) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidEndpointAddress" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + } + + if($null -ne $metaData) + { + try + { + [xml] $metadataXML = $metaData + } + catch + { + $errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri) + $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) + $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri + $callerPSCmdlet.ThrowTerminatingError($errorRecord) + } + } + + return $metadataXML +} + +######################################################### +# VerifyMetadataHelper is a helper function used to +# validate if Error/Warning message has to be displayed +# during command collision. +######################################################### +function VerifyMetadataHelper +{ + param + ( + [string] $localizedDataErrorString, + [string] $localizedDataWarningString, + [string] $entitySetName, + [string] $currentCommandName, + [string] $metaDataUri, + [boolean] $allowClobber, + [System.Management.Automation.PSCmdlet] $callerPSCmdlet + ) + + if($null -eq $localizedDataErrorString) { throw ($LocalizedData.ArguementNullError -f "localizedDataErrorString", "VerifyMetadataHelper") } + if($null -eq $localizedDataWarningString) { throw ($LocalizedData.ArguementNullError -f "localizedDataWarningString", "VerifyMetadataHelper") } + + if(!$allowClobber) + { + # Write Error message and skip current Entity Set. + $errorMessage = ($localizedDataErrorString -f $entitySetName, $currentCommandName) + $exception = [System.InvalidOperationException]::new($errorMessage) + $errorRecord = CreateErrorRecordHelper "ODataEndpointDefaultPropertyCollision" $null ([System.Management.Automation.ErrorCategory]::InvalidOperation) $exception $metaDataUri + $callerPSCmdlet.WriteError($errorRecord) + } + else + { + $warningMessage = ($localizedDataWarningString -f $entitySetName, $currentCommandName) + $callerPSCmdlet.WriteWarning($warningMessage) + } +} + +######################################################### +# CreateErrorRecordHelper is a helper function used to +# create an error record. +######################################################### +function CreateErrorRecordHelper +{ + param + ( + [string] $errorId, + [string] $errorMessage, + [System.Management.Automation.ErrorCategory] $errorCategory, + [Exception] $exception, + [object] $targetObject + ) + + if($null -eq $exception) + { + $exception = New-Object System.IO.IOException $errorMessage + } + + $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject + return $errorRecord +} + +######################################################### +# ProgressBarHelper is a helper function used to +# used to display progress message. +######################################################### +function ProgressBarHelper +{ + param + ( + [string] $cmdletName, + [string] $status, + [double] $previousSegmentWeight, + [double] $currentSegmentWeight, + [int] $totalNumberofEntries, + [int] $currentEntryCount + ) + + if($null -eq $cmdletName) { throw ($LocalizedData.ArguementNullError -f "CmdletName", "ProgressBarHelper") } + if($null -eq $status) { throw ($LocalizedData.ArguementNullError -f "Status", "ProgressBarHelper") } + + if($currentEntryCount -gt 0 -and + $totalNumberofEntries -gt 0 -and + $previousSegmentWeight -ge 0 -and + $currentSegmentWeight -gt 0) + { + $entryDefaultWeight = $currentSegmentWeight/[double]$totalNumberofEntries + $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount) + Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete + } +} + +######################################################### +# Convert-ODataTypeToCLRType is a helper function used to +# Convert OData type to its CLR equivalent. +######################################################### +function Convert-ODataTypeToCLRType +{ + param + ( + [string] $typeName, + [Hashtable] $complexTypeMapping + ) + + if($null -eq $typeName) { throw ($LocalizedData.ArguementNullError -f "TypeName", "Convert-ODataTypeToCLRType ") } + + switch ($typeName) + { + "Edm.Binary" {"Byte[]"} + "Edm.Boolean" {"Boolean"} + "Edm.Byte" {"Byte"} + "Edm.DateTime" {"DateTime"} + "Edm.Decimal" {"Decimal"} + "Edm.Double" {"Double"} + "Edm.Single" {"Single"} + "Edm.Guid" {"Guid"} + "Edm.Int16" {"Int16"} + "Edm.Int32" {"Int32"} + "Edm.Int64" {"Int64"} + "Edm.SByte" {"SByte"} + "Edm.String" {"String"} + "Edm.PropertyPath" {"String"} + "switch" {"switch"} + "Edm.DateTimeOffset" {"DateTimeOffset"} + default + { + if($null -ne $complexTypeMapping -and + $complexTypeMapping.Count -gt 0 -and + $complexTypeMapping.ContainsKey($typeName)) + { + $typeName + } + else + { + $regex = "Collection\((.+)\)" + if ($typeName -match $regex) + { + $insideTypeName = Convert-ODataTypeToCLRType $Matches[1] $complexTypeMapping + "$insideTypeName[]" + } + else + { + "PSObject" + } + } + } + } +} + +######################################################### +# SaveCDXMLHeader is a helper function used +# to save CDXML headers common to all +# PSODataUtils modules. +######################################################### +function SaveCDXMLHeader +{ + param + ( + [System.Xml.XmlWriter] $xmlWriter, + [string] $uri, + [string] $className, + [string] $defaultNoun, + [string] $cmdletAdapter + ) + + # $uri & $cmdletAdapter are already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLHeader") } + if($null -eq $defaultNoun) { throw ($LocalizedData.ArguementNullError -f "DefaultNoun", "SaveCDXMLHeader") } + + if ($className -eq 'ServiceActions' -Or $cmdletAdapter -eq "NetworkControllerAdapter") + { + $entityName = '' + } + else + { + $entityName = $className + } + + if ($uri[-1] -ne '/') + { + $fullName = "$uri/$entityName" + } + else + { + $fullName = "$uri$entityName" + } + + $xmlWriter.Formatting = 'Indented' + $xmlWriter.Indentation = 2 + $xmlWriter.IndentChar = ' ' + + $xmlWriter.WriteStartDocument() + + $today=Get-Date + $xmlWriter.WriteComment("This module was autogenerated by PSODataUtils on $today.") + + $xmlWriter.WriteStartElement('PowerShellMetadata') + $xmlWriter.WriteAttributeString('xmlns', 'http://schemas.microsoft.com/cmdlets-over-objects/2009/11') + + $xmlWriter.WriteStartElement('Class') + $xmlWriter.WriteAttributeString('ClassName', $fullName) + $xmlWriter.WriteAttributeString('ClassVersion', '1.0.0') + + $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataCmdletAdapter' + + if ($CmdletAdapter -eq "NetworkControllerAdapter") { + $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.NetworkControllerCmdletAdapter' + } + elseif ($CmdletAdapter -eq "ODataV4Adapter") { + $DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataV4CmdletAdapter' + } + + $xmlWriter.WriteAttributeString('CmdletAdapter', $DotNetAdapter + ', Microsoft.PowerShell.Cmdletization.OData, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35') + + $xmlWriter.WriteElementString('Version', '1.0') + $xmlWriter.WriteElementString('DefaultNoun', $defaultNoun) + + $xmlWriter +} + +######################################################### +# SaveCDXMLFooter is a helper function used +# to save CDXML closing attributes corresponding +# to SaveCDXMLHeader function. +######################################################### +function SaveCDXMLFooter +{ + param + ( + [System.Xml.XmlWriter] $xmlWriter + ) + + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFooter") } + + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndDocument() + + $xmlWriter.Flush() + $xmlWriter.Close() +} + +######################################################### +# AddParametersNode is a helper function used +# to add parameters to the generated proxy cmdlet, +# based on mandatoryProperties and otherProperties. +# PrefixForKeys is used by associations to append a +# prefix to PowerShell parameter name. +######################################################### +function AddParametersNode +{ + param + ( + [Parameter(Mandatory=$true)] + [System.Xml.XmlWriter] $xmlWriter, + [ODataUtils.TypeProperty[]] $keyProperties, + [ODataUtils.TypeProperty[]] $mandatoryProperties, + [ODataUtils.TypeProperty[]] $otherProperties, + [string] $prefixForKeys, + [boolean] $addForceParameter, + [boolean] $addParametersElement, + [Hashtable] $complexTypeMapping + ) + + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } + + if(($keyProperties.Length -gt 0) -or + ($mandatoryProperties.Length -gt 0) -or + ($otherProperties.Length -gt 0) -or + ($addForceParameter)) + { + if($addParametersElement) + { + $xmlWriter.WriteStartElement('Parameters') + } + + $pos = 0 + + if ($null -ne $keyProperties) + { + $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping + } + + if ($null -ne $mandatoryProperties) + { + $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping + } + + if ($null -ne $otherProperties) + { + $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping + } + + if($addForceParameter) + { + $forceParameter = [ODataUtils.TypeProperty] @{ + "Name" = "Force"; + "TypeName" = "switch"; + "IsNullable" = $false + } + + $pos = AddParametersCDXML $xmlWriter $forceParameter $pos $false $null $null $complexTypeMapping + } + + if($addParametersElement) + { + $xmlWriter.WriteEndElement() + } + } +} + +######################################################### +# AddParametersCDXML is a helper function used +# to add Parameter node to CDXML based on properties. +# Prefix is appended to PS parameter names, used for +# associations. Suffix is appended to all parameter +# names, for ex. to differentiate keys. returns new $pos +######################################################### +function AddParametersCDXML +{ + param + ( + [Parameter(Mandatory=$true)] + [System.Xml.XmlWriter] $xmlWriter, + [ODataUtils.TypeProperty[]] $properties, + [Parameter(Mandatory=$true)] + [int] $pos, + [bool] $isMandatory, + [string] $prefix, + [string] $suffix, + [Hashtable] $complexTypeMapping + ) + + $properties | Where-Object { $null -ne $_ } | ForEach-Object { + $xmlWriter.WriteStartElement('Parameter') + $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) + $xmlWriter.WriteStartElement('Type') + $PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping + $xmlWriter.WriteAttributeString('PSType', $PSTypeName) + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('CmdletParameterMetadata') + $xmlWriter.WriteAttributeString('PSName', $prefix + $_.Name) + $xmlWriter.WriteAttributeString('IsMandatory', ($isMandatory).ToString().ToLowerInvariant()) + $xmlWriter.WriteAttributeString('Position', $pos) + if($isMandatory) + { + $xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true') + } + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() + + $pos++ + } + + $pos +} + +######################################################### +# GenerateSetProxyCmdlet is a helper function used +# to generate Set-* proxy cmdlet. The proxy cmdlet is +# generated in the CDXML compliant format. +######################################################### +function GenerateSetProxyCmdlet +{ + param + ( + [System.XMl.XmlTextWriter] $xmlWriter, + [object[]] $keyProperties, + [object[]] $nonKeyProperties, + [Hashtable] $complexTypeMapping + ) + + # $cmdletAdapter is already validated at the cmdlet layer. + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateSetProxyCmdlet") } + + $xmlWriter.WriteStartElement('Cmdlet') + $xmlWriter.WriteStartElement('CmdletMetadata') + $xmlWriter.WriteAttributeString('Verb', 'Set') + $xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default') + $xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium') + $xmlWriter.WriteEndElement() + + $xmlWriter.WriteStartElement('Method') + $xmlWriter.WriteAttributeString('MethodName', 'Update') + $xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default') + + AddParametersNode $xmlWriter $keyProperties $null $nonKeyProperties $null $true $true $complexTypeMapping + $xmlWriter.WriteEndElement() + $xmlWriter.WriteEndElement() +} diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/en-US/Microsoft.PowerShell.ODataUtilsStrings.psd1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/en-US/Microsoft.PowerShell.ODataUtilsStrings.psd1 index 0c04b467060..971b8333595 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/en-US/Microsoft.PowerShell.ODataUtilsStrings.psd1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/en-US/Microsoft.PowerShell.ODataUtilsStrings.psd1 @@ -1,55 +1,55 @@ -# Localized PSODataUtils.psd1 - -ConvertFrom-StringData @' -###PSLOC -SelectedAdapter=Dot sourcing '{0}'. -ArchitectureNotSupported=This module is not supported on your processor architecture ({0}). -ArguementNullError=Failed to generate proxy as '{0}' is pointing to $null in '{1}'. -EmptyMetadata=Read metadata was empty. Url: {0}. -InvalidEndpointAddress=Invalid endpoint address ({0}). Web response with status code '{1}' was obtained while accessing this endpoint address. -NoEntitySets=Metadata from URI '{0}' does not contain Entity Sets. No output will be written. -NoEntityTypes=Metadata from URI '{0}' does not contain Entity Types. No output will be written. -MetadataUriDoesNotExist=Metadata specified at the URI '{0}' does not exist. No output will be written. -InValidIdentifierInMetadata=Metadata specified at URI '{0}' contains an invalid Identifier '{1}'. Only valid C# identifiers are supported in the generated complex types during the proxy creation. -InValidMetadata=Failed to process metadata specified at URI '{0}'. No output will be written. -InValidXmlInMetadata=Metadata specified at URI '{0}' contains an invalid XML. No output will be written. -ODataVersionNotFound=Metadata specified at URI '{0}' does not contain the OData Version. No output will be written. -ODataVersionNotSupported=The OData version '{0}' specified in the metadata located at the URI '{1}' is not supported. Only OData versions between '{2}' and '{3}' are supported by '{4}' during proxy generation. No output will be written. -InValidSchemaNamespace=Metadata specified at URI '{0}' is invalid. NULL or Empty values are not supported for Namespace attribute in the schema. -InValidSchemaNamespaceConflictWithClassName=Metadata specified at URI '{0}' contains invalid Namespace {1} name, which conflicts with another type name. To avoid compilation error {1} will be changed to {2}. -InValidSchemaNamespaceContainsInvalidChars=Metadata specified at URI '{0}' contains invalid Namespace name {1} with a combination of dots and numbers in it, which is not allowed in .Net. To avoid compilation error {1} will be changed to {2}. -InValidUri=URI '{0}' is invalid. No output will be written. -RedfishNotEnabled=This version of Microsoft.PowerShell.ODataUtils doesn’t support Redfish, please run: ‘update-module Microsoft.PowerShell.ODataUtils’ to get Redfish support. -EntitySetUndefinedType=Metadata from URI '{0}' does not contain the Type for Entity Set '{1}'. No output will be written. -XmlWriterInitializationError=There was an error initiating XmlWriter for writing the {0} CDXML module. -EmptySchema=Edmx.DataServices.Schema node should not be null. -VerboseReadingMetadata=Reading metadata from uri {0}. -VerboseParsingMetadata=Parsing metadata... -VerboseVerifyingMetadata=Verifying metadata... -VerboseSavingModule=Saving output module to path {0}. -VerboseSavedCDXML=Saved CDXML module for {0} to {1}. -VerboseSavedServiceActions=Saved Service Actions CDXML module for to {0}. -VerboseSavedModuleManifest=Saved module manifest at {0}. -AssociationNotFound=Association {0} not found in Metadata.Associations. -TooManyMatchingAssociationTypes=Found {0} {1} associations in Metadata.Associations. Expected only one. -ZeroMatchingAssociationTypes=Navigation property {0} not found on association {1}. -WrongCountEntitySet=Expected one EntitySet for EntityType {0}, but got {1}. -EntityNameConflictError=Proxy creation is not supported when multiple EntitySets are mapped to the same EntityType. The metadata located at the URI '{0}' contains EntitySets '{1}' and '{2}' that are mapped to the same EntityType '{3}'. -VerboseSavedTypeDefinationModule=Saved Type definition module '{0}' at '{1}'. -VerboseAddingTypeDefinationToGeneratedModule=Adding Type definition for '{0}' to '{1}' module. -OutputPathNotFound=Could not find a part of the path '{0}'. -ModuleAlreadyExistsAndForceParameterIsNotSpecified=The directory '{0}' already exists. Use the -Force parameter if you want to overwrite the directory and files within the directory. -InvalidOutputModulePath=Path '{0}' specified to -OutputModule parameter does not contain the module name. -OutputModulePathIsNotUnique=Path '{0}' specified to -OutputModule parameter resolves to multiple paths in the file system. Provide a unique file system path to -OutputModule parameter. -OutputModulePathIsNotFileSystemPath=Path '{0}' specified to -OutputModule parameter is not a file system. Provide a unique file system path to -OutputModule parameter. -SkipEntitySetProxyCreation=CDXML module creation has been skipped for the Entity Set '{0}' because its Entity Type '{1}' contains a property '{2}' that collides with one of the default properties of the generated cmdlets. -EntitySetProxyCreationWithWarning=CDXML module creation for the Entity Set '{0}' succeeded but contains a property '{1}' in the Entity Type '{2}' that collides with one of the default properties of the generated cmdlets. -SkipEntitySetConflictCommandCreation=CDXML module creation has been skipped for the Entity Set '{0}' because the exported command '{1}' conflicts with the inbox command. -EntitySetConflictCommandCreationWithWarning=CDXML module creation for the Entity Set '{0}' succeeded but contains a command '{1}' that collides with the inbox command. -SkipConflictServiceActionCommandCreation=CDXML module creation has been skipped for the Service Action '{0}' because the exported command '{1}' conflicts with the inbox command. -ConflictServiceActionCommandCreationWithWarning=CDXML module creation for the Service Action '{0}' succeeded but contains a command '{1}' that collides with the inbox command. -AllowUnsecureConnectionMessage=The cmdlet '{0}' is trying to establish an Unsecure connection with the OData endpoint through the URI '{1}'. Either supply a secure URI to the -{2} parameter or use -AllowUnsecureConnection switch parameter if you intend to use the current URI. -ProgressBarMessage=Creating proxy for the OData endpoint at the URI '{0}'. -###PSLOC - +# Localized PSODataUtils.psd1 + +ConvertFrom-StringData @' +###PSLOC +SelectedAdapter=Dot sourcing '{0}'. +ArchitectureNotSupported=This module is not supported on your processor architecture ({0}). +ArguementNullError=Failed to generate proxy as '{0}' is pointing to $null in '{1}'. +EmptyMetadata=Read metadata was empty. Url: {0}. +InvalidEndpointAddress=Invalid endpoint address ({0}). Web response with status code '{1}' was obtained while accessing this endpoint address. +NoEntitySets=Metadata from URI '{0}' does not contain Entity Sets. No output will be written. +NoEntityTypes=Metadata from URI '{0}' does not contain Entity Types. No output will be written. +MetadataUriDoesNotExist=Metadata specified at the URI '{0}' does not exist. No output will be written. +InValidIdentifierInMetadata=Metadata specified at URI '{0}' contains an invalid Identifier '{1}'. Only valid C# identifiers are supported in the generated complex types during the proxy creation. +InValidMetadata=Failed to process metadata specified at URI '{0}'. No output will be written. +InValidXmlInMetadata=Metadata specified at URI '{0}' contains an invalid XML. No output will be written. +ODataVersionNotFound=Metadata specified at URI '{0}' does not contain the OData Version. No output will be written. +ODataVersionNotSupported=The OData version '{0}' specified in the metadata located at the URI '{1}' is not supported. Only OData versions between '{2}' and '{3}' are supported by '{4}' during proxy generation. No output will be written. +InValidSchemaNamespace=Metadata specified at URI '{0}' is invalid. NULL or Empty values are not supported for Namespace attribute in the schema. +InValidSchemaNamespaceConflictWithClassName=Metadata specified at URI '{0}' contains invalid Namespace {1} name, which conflicts with another type name. To avoid compilation error {1} will be changed to {2}. +InValidSchemaNamespaceContainsInvalidChars=Metadata specified at URI '{0}' contains invalid Namespace name {1} with a combination of dots and numbers in it, which is not allowed in .Net. To avoid compilation error {1} will be changed to {2}. +InValidUri=URI '{0}' is invalid. No output will be written. +RedfishNotEnabled=This version of Microsoft.PowerShell.ODataUtils doesn’t support Redfish, please run: ‘update-module Microsoft.PowerShell.ODataUtils’ to get Redfish support. +EntitySetUndefinedType=Metadata from URI '{0}' does not contain the Type for Entity Set '{1}'. No output will be written. +XmlWriterInitializationError=There was an error initiating XmlWriter for writing the {0} CDXML module. +EmptySchema=Edmx.DataServices.Schema node should not be null. +VerboseReadingMetadata=Reading metadata from uri {0}. +VerboseParsingMetadata=Parsing metadata... +VerboseVerifyingMetadata=Verifying metadata... +VerboseSavingModule=Saving output module to path {0}. +VerboseSavedCDXML=Saved CDXML module for {0} to {1}. +VerboseSavedServiceActions=Saved Service Actions CDXML module for to {0}. +VerboseSavedModuleManifest=Saved module manifest at {0}. +AssociationNotFound=Association {0} not found in Metadata.Associations. +TooManyMatchingAssociationTypes=Found {0} {1} associations in Metadata.Associations. Expected only one. +ZeroMatchingAssociationTypes=Navigation property {0} not found on association {1}. +WrongCountEntitySet=Expected one EntitySet for EntityType {0}, but got {1}. +EntityNameConflictError=Proxy creation is not supported when multiple EntitySets are mapped to the same EntityType. The metadata located at the URI '{0}' contains EntitySets '{1}' and '{2}' that are mapped to the same EntityType '{3}'. +VerboseSavedTypeDefinationModule=Saved Type definition module '{0}' at '{1}'. +VerboseAddingTypeDefinationToGeneratedModule=Adding Type definition for '{0}' to '{1}' module. +OutputPathNotFound=Could not find a part of the path '{0}'. +ModuleAlreadyExistsAndForceParameterIsNotSpecified=The directory '{0}' already exists. Use the -Force parameter if you want to overwrite the directory and files within the directory. +InvalidOutputModulePath=Path '{0}' specified to -OutputModule parameter does not contain the module name. +OutputModulePathIsNotUnique=Path '{0}' specified to -OutputModule parameter resolves to multiple paths in the file system. Provide a unique file system path to -OutputModule parameter. +OutputModulePathIsNotFileSystemPath=Path '{0}' specified to -OutputModule parameter is not a file system. Provide a unique file system path to -OutputModule parameter. +SkipEntitySetProxyCreation=CDXML module creation has been skipped for the Entity Set '{0}' because its Entity Type '{1}' contains a property '{2}' that collides with one of the default properties of the generated cmdlets. +EntitySetProxyCreationWithWarning=CDXML module creation for the Entity Set '{0}' succeeded but contains a property '{1}' in the Entity Type '{2}' that collides with one of the default properties of the generated cmdlets. +SkipEntitySetConflictCommandCreation=CDXML module creation has been skipped for the Entity Set '{0}' because the exported command '{1}' conflicts with the inbox command. +EntitySetConflictCommandCreationWithWarning=CDXML module creation for the Entity Set '{0}' succeeded but contains a command '{1}' that collides with the inbox command. +SkipConflictServiceActionCommandCreation=CDXML module creation has been skipped for the Service Action '{0}' because the exported command '{1}' conflicts with the inbox command. +ConflictServiceActionCommandCreationWithWarning=CDXML module creation for the Service Action '{0}' succeeded but contains a command '{1}' that collides with the inbox command. +AllowUnsecureConnectionMessage=The cmdlet '{0}' is trying to establish an Unsecure connection with the OData endpoint through the URI '{1}'. Either supply a secure URI to the -{2} parameter or use -AllowUnsecureConnection switch parameter if you intend to use the current URI. +ProgressBarMessage=Creating proxy for the OData endpoint at the URI '{0}'. +###PSLOC + '@ \ No newline at end of file diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows-Full/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 25008e2703a..86eccf288f3 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -1,32 +1,32 @@ -@{ -GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" -Author="Microsoft Corporation" -CompanyName="Microsoft Corporation" -Copyright="© Microsoft Corporation. All rights reserved." -ModuleVersion="3.1.0.0" -PowerShellVersion="3.0" -CLRVersion="4.0" -CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", - "Out-File", "Out-Printer", "Out-String", - "Out-GridView", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", - "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", - "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", - "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", - "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", - "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", - "Start-Sleep", "Tee-Object", "Measure-Command", "Update-List", "Update-TypeData", "Update-FormatData", - "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", - "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", - "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug", - "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", "Get-PSBreakpoint", - "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", - "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Show-Command", "Unblock-File", "Get-FileHash", - "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", "Get-RunspaceDebug", "Wait-Debugger", - "ConvertFrom-String", "Convert-String" , "Get-Uptime", "New-TemporaryFile", "Get-Verb", "Format-Hex" -FunctionsToExport= "ConvertFrom-SddlString" -AliasesToExport= "CFS", "fhx" -NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' -} +@{ +GUID="1DA87E53-152B-403E-98DC-74D7B4D63D59" +Author="Microsoft Corporation" +CompanyName="Microsoft Corporation" +Copyright="© Microsoft Corporation. All rights reserved." +ModuleVersion="3.1.0.0" +PowerShellVersion="3.0" +CLRVersion="4.0" +CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide", + "Out-File", "Out-Printer", "Out-String", + "Out-GridView", "Get-FormatData", "Export-FormatData", "ConvertFrom-Json", "ConvertTo-Json", + "Invoke-RestMethod", "Invoke-WebRequest", "Register-ObjectEvent", "Register-EngineEvent", + "Wait-Event", "Get-Event", "Remove-Event", "Get-EventSubscriber", "Unregister-Event", "New-Guid", + "New-Event", "Add-Member", "Add-Type", "Compare-Object", "ConvertTo-Html", "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", "Get-UICulture", + "Get-Unique", "Export-PSSession", "Import-PSSession", "Import-Alias", "Import-LocalizedData", + "Select-String", "Measure-Object", "New-Alias", "New-TimeSpan", "Read-Host", "Set-Alias", "Set-Date", + "Start-Sleep", "Tee-Object", "Measure-Command", "Update-List", "Update-TypeData", "Update-FormatData", + "Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object", + "Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable", + "Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug", + "Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", "Get-PSBreakpoint", + "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack", + "Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Show-Command", "Unblock-File", "Get-FileHash", + "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", "Get-RunspaceDebug", "Wait-Debugger", + "ConvertFrom-String", "Convert-String" , "Get-Uptime", "New-TemporaryFile", "Get-Verb", "Format-Hex" +FunctionsToExport= "ConvertFrom-SddlString" +AliasesToExport= "CFS", "fhx" +NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1" +HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787' +} diff --git a/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.Format.ps1xml b/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.Format.ps1xml index be7f28d740a..09820341fbe 100644 --- a/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.Format.ps1xml +++ b/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.Format.ps1xml @@ -1,117 +1,117 @@ - - - - - ScheduledJobTrigger - - Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger - - - - - - 10 - left - - - - 15 - left - - - - 22 - left - - - - 23 - left - - - - 10 - left - - - - - - - Id - - - Frequency - - - At - - - DaysOfWeek - - - Enabled - - - - - - - - ScheduledJobDefinition - - Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition - - - - - - 10 - left - - - - 15 - left - - - - 15 - left - - - - 40 - left - - - - 10 - left - - - - - - - Id - - - Name - - - $_.JobTriggers.Count - - - Command - - - Enabled - - - - - - - - + + + + + ScheduledJobTrigger + + Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger + + + + + + 10 + left + + + + 15 + left + + + + 22 + left + + + + 23 + left + + + + 10 + left + + + + + + + Id + + + Frequency + + + At + + + DaysOfWeek + + + Enabled + + + + + + + + ScheduledJobDefinition + + Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition + + + + + + 10 + left + + + + 15 + left + + + + 15 + left + + + + 40 + left + + + + 10 + left + + + + + + + Id + + + Name + + + $_.JobTriggers.Count + + + Command + + + Enabled + + + + + + + + diff --git a/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.types.ps1xml b/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.types.ps1xml index 1bba20b14b1..699af0c99d3 100644 --- a/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.types.ps1xml +++ b/src/Modules/Windows-Full/PSScheduledJob/PSScheduledJob.types.ps1xml @@ -1,24 +1,24 @@ - - - - - Microsoft.Management.Infrastructure.CimInstance - - Microsoft.PowerShell.ScheduledJob.JobTriggerToCimInstanceConverter, Microsoft.PowerShell.ScheduledJob, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 - - - + + + + + Microsoft.Management.Infrastructure.CimInstance + + Microsoft.PowerShell.ScheduledJob.JobTriggerToCimInstanceConverter, Microsoft.PowerShell.ScheduledJob, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 + + + diff --git a/src/Schemas/PSMaml/Maml.tbr b/src/Schemas/PSMaml/Maml.tbr index 559196257bd..dd8d9c30222 100644 --- a/src/Schemas/PSMaml/Maml.tbr +++ b/src/Schemas/PSMaml/Maml.tbr @@ -1,1427 +1,1426 @@ - - - -0X00020004 - - - - - - - - 0X00004FC1 - 0X00000005 - 0X0000000C - 0X0000001A - 0X0000009D - - 0X00004FC1 - - - - - - - - - - - - - - - 0X00005162 - 0X00000005 - 0X00000025 - 0X0000001A - 0X00000103 - - 0X00005162 - - - - - - - - - - - - 0X80000001 - - 0X80000001 - - - 0X00004E22 - - 0X00004E22 - - - 0X0000E101 - - 0X0000E101 - - - 0X0000E102 - - 0X0000E102 - - - 0X000080F6 - - 0X000080F6 - - - 0X0000E103 - - 0X0000E103 - - - 0X0000E104 - - 0X0000E104 - - - 0X000080F4 - - 0X000080F4 - - - 0X00004E20 - - 0X00004E20 - - - - 0XFFFEFFA4 - - - 0X0000A800 - - 0X0000A800 - - - 0X0000A817 - - 0X0000A817 - - - - - 0X0000E107 - - 0X0000E107 - - - 0X0000E110 - - 0X0000E110 - - - 0X0000E141 - - 0X0000E141 - - - - - 0X80000002 - - 0X80000002 - - - 0X0000E12B - - 0X0000E12B - - - 0X0000E12C - - 0X0000E12C - - - 0X0000E123 - - 0X0000E123 - - - 0X0000E122 - - 0X0000E122 - - - 0X0000E125 - - 0X0000E125 - - - 0X00004E8B - - 0X00004E8B - - - 0X0000E120 - - 0X0000E120 - - - 0X00004E84 - - 0X00004E84 - - - 0X00004E8A - - 0X00004E8A - - - 0X00004E89 - - 0X00004E89 - - - 0X00004E8C - - 0X00004E8C - - - 0X00004E87 - - 0X00004E87 - - - 0X00004E86 - - 0X00004E86 - - - - - 0X80000003 - - 0X80000003 - - - 0X00004EEC - - 0X00004EEC - - - 0X00004EEE - - 0X00004EEE - - - 0X00004EEF - - 0X00004EEF - - - 0X00004EEA - - 0X00004EEA - - - 0X00004EEB - - 0X00004EEB - - - 0X000050F4 - - 0X000050F4 - - - 0X00004EF0 - - 0X00004EF0 - - - 0X00004EF3 - - 0X00004EF3 - - - 0X00004EF1 - - 0X00004EF1 - - - 0X00004EF5 - - 0X00004EF5 - - - 0X0000E800 - - 0X0000E800 - - - 0X0000E801 - - 0X0000E801 - - - 0X00007541 - - 0X00007541 - - - 0X000080EB - - 0X000080EB - - - 0X00007531 - - 0X00007531 - - - - - 0X80000004 - - 0X80000004 - - - 0X00004F50 - - 0X00004F50 - - - 0X00004F5A - - 0X00004F5A - - - 0X00004F59 - - 0X00004F59 - - - 0X00004F56 - - 0X00004F56 - - - 0X00004F58 - - 0X00004F58 - - - 0X000059D6 - - 0X000059D6 - - - 0X000059D7 - - 0X000059D7 - - - 0X00004F52 - - 0X00004F52 - - - - - 0X80000005 - - 0X80000005 - - - 0X00005152 - - 0X00005152 - - - 0X00005154 - - 0X00005154 - - - 0X0000514F - - 0X0000514F - - - 0X00005151 - - 0X00005151 - - - 0X00005170 - - 0X00005170 - - - 0X00005177 - - 0X00005177 - - - 0X00005178 - - 0X00005178 - - - 0X00005078 - - 0X00005078 - - - 0X00005079 - - 0X00005079 - - - 0X0000507A - - 0X0000507A - - - 0X00005141 - - 0X00005141 - - - 0X00005160 - - 0X00005160 - - - 0X00008051 - - 0X00008051 - - - - - 0X80000006 - - 0X80000006 - - - 0X000050E3 - - 0X000050E3 - - - 0X000050DE - - 0X000050DE - - - 0X000050F3 - - 0X000050F3 - - - 0X000050DD - - 0X000050DD - - - 0X000050DC - - 0X000050DC - - - 0X000050EC - - 0X000050EC - - - 0X000050E4 - - 0X000050E4 - - - 0X000050EE - - 0X000050EE - - - 0X000050EF - - 0X000050EF - - - 0X000050F2 - - 0X000050F2 - - - - - 0X80000007 - - 0X80000007 - - - 0X0000515B - - 0X0000515B - - - 0X0000515A - - 0X0000515A - - - 0X0000E132 - - 0X0000E132 - - - 0X0000E133 - - 0X0000E133 - - - 0X0000E134 - - 0X0000E134 - - - 0X0000E131 - - 0X0000E131 - - - - - 0X80000008 - - 0X80000008 - - - 0X00007556 - - 0X00007556 - - - 0X00007559 - - 0X00007559 - - - 0X00007557 - - 0X00007557 - - - 0X0000755D - - 0X0000755D - - - 0X0000755A - - 0X0000755A - - - 0X0000E140 - - 0X0000E140 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + +0X00020004 + + + + + + + + 0X00004FC1 + 0X00000005 + 0X0000000C + 0X0000001A + 0X0000009D + + 0X00004FC1 + + + + + + + + + + + + + + + 0X00005162 + 0X00000005 + 0X00000025 + 0X0000001A + 0X00000103 + + 0X00005162 + + + + + + + + + + + + 0X80000001 + + 0X80000001 + + + 0X00004E22 + + 0X00004E22 + + + 0X0000E101 + + 0X0000E101 + + + 0X0000E102 + + 0X0000E102 + + + 0X000080F6 + + 0X000080F6 + + + 0X0000E103 + + 0X0000E103 + + + 0X0000E104 + + 0X0000E104 + + + 0X000080F4 + + 0X000080F4 + + + 0X00004E20 + + 0X00004E20 + + + + 0XFFFEFFA4 + + + 0X0000A800 + + 0X0000A800 + + + 0X0000A817 + + 0X0000A817 + + + + + 0X0000E107 + + 0X0000E107 + + + 0X0000E110 + + 0X0000E110 + + + 0X0000E141 + + 0X0000E141 + + + + + 0X80000002 + + 0X80000002 + + + 0X0000E12B + + 0X0000E12B + + + 0X0000E12C + + 0X0000E12C + + + 0X0000E123 + + 0X0000E123 + + + 0X0000E122 + + 0X0000E122 + + + 0X0000E125 + + 0X0000E125 + + + 0X00004E8B + + 0X00004E8B + + + 0X0000E120 + + 0X0000E120 + + + 0X00004E84 + + 0X00004E84 + + + 0X00004E8A + + 0X00004E8A + + + 0X00004E89 + + 0X00004E89 + + + 0X00004E8C + + 0X00004E8C + + + 0X00004E87 + + 0X00004E87 + + + 0X00004E86 + + 0X00004E86 + + + + + 0X80000003 + + 0X80000003 + + + 0X00004EEC + + 0X00004EEC + + + 0X00004EEE + + 0X00004EEE + + + 0X00004EEF + + 0X00004EEF + + + 0X00004EEA + + 0X00004EEA + + + 0X00004EEB + + 0X00004EEB + + + 0X000050F4 + + 0X000050F4 + + + 0X00004EF0 + + 0X00004EF0 + + + 0X00004EF3 + + 0X00004EF3 + + + 0X00004EF1 + + 0X00004EF1 + + + 0X00004EF5 + + 0X00004EF5 + + + 0X0000E800 + + 0X0000E800 + + + 0X0000E801 + + 0X0000E801 + + + 0X00007541 + + 0X00007541 + + + 0X000080EB + + 0X000080EB + + + 0X00007531 + + 0X00007531 + + + + + 0X80000004 + + 0X80000004 + + + 0X00004F50 + + 0X00004F50 + + + 0X00004F5A + + 0X00004F5A + + + 0X00004F59 + + 0X00004F59 + + + 0X00004F56 + + 0X00004F56 + + + 0X00004F58 + + 0X00004F58 + + + 0X000059D6 + + 0X000059D6 + + + 0X000059D7 + + 0X000059D7 + + + 0X00004F52 + + 0X00004F52 + + + + + 0X80000005 + + 0X80000005 + + + 0X00005152 + + 0X00005152 + + + 0X00005154 + + 0X00005154 + + + 0X0000514F + + 0X0000514F + + + 0X00005151 + + 0X00005151 + + + 0X00005170 + + 0X00005170 + + + 0X00005177 + + 0X00005177 + + + 0X00005178 + + 0X00005178 + + + 0X00005078 + + 0X00005078 + + + 0X00005079 + + 0X00005079 + + + 0X0000507A + + 0X0000507A + + + 0X00005141 + + 0X00005141 + + + 0X00005160 + + 0X00005160 + + + 0X00008051 + + 0X00008051 + + + + + 0X80000006 + + 0X80000006 + + + 0X000050E3 + + 0X000050E3 + + + 0X000050DE + + 0X000050DE + + + 0X000050F3 + + 0X000050F3 + + + 0X000050DD + + 0X000050DD + + + 0X000050DC + + 0X000050DC + + + 0X000050EC + + 0X000050EC + + + 0X000050E4 + + 0X000050E4 + + + 0X000050EE + + 0X000050EE + + + 0X000050EF + + 0X000050EF + + + 0X000050F2 + + 0X000050F2 + + + + + 0X80000007 + + 0X80000007 + + + 0X0000515B + + 0X0000515B + + + 0X0000515A + + 0X0000515A + + + 0X0000E132 + + 0X0000E132 + + + 0X0000E133 + + 0X0000E133 + + + 0X0000E134 + + 0X0000E134 + + + 0X0000E131 + + 0X0000E131 + + + + + 0X80000008 + + 0X80000008 + + + 0X00007556 + + 0X00007556 + + + 0X00007559 + + 0X00007559 + + + 0X00007557 + + 0X00007557 + + + 0X0000755D + + 0X0000755D + + + 0X0000755A + + 0X0000755A + + + 0X0000E140 + + 0X0000E140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Schemas/PSMaml/Maml_HTML.xsl b/src/Schemas/PSMaml/Maml_HTML.xsl index e3c0c990cbe..accd69b884d 100644 --- a/src/Schemas/PSMaml/Maml_HTML.xsl +++ b/src/Schemas/PSMaml/Maml_HTML.xsl @@ -1,7 +1,7 @@ - - - - - + + + + + diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 84dac06266c..6d258a6d1b7 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -77,9 +77,9 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo result = LoadingResult.AssemblyNotFound; return null; } - else - { - resourceReference.assemblyLocation = loadResult.a.Location; + else + { + resourceReference.assemblyLocation = loadResult.a.Location; }; // load now the resource from the resource manager cache diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 87135c2e2bf..67064d645fc 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -534,16 +534,16 @@ protected override void EndProcessing() /// /// protected override void StopProcessing() - { - var remoteRunspace = _tempRunspace; - if (remoteRunspace != null) - { - try - { - remoteRunspace.CloseAsync(); - } - catch (InvalidRunspaceStateException) { } - return; + { + var remoteRunspace = _tempRunspace; + if (remoteRunspace != null) + { + try + { + remoteRunspace.CloseAsync(); + } + catch (InvalidRunspaceStateException) { } + return; } IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; diff --git a/src/System.Management.Automation/resources/CmdletizationCoreResources.resx b/src/System.Management.Automation/resources/CmdletizationCoreResources.resx index 820720dd126..5035b072328 100644 --- a/src/System.Management.Automation/resources/CmdletizationCoreResources.resx +++ b/src/System.Management.Automation/resources/CmdletizationCoreResources.resx @@ -1,203 +1,203 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Cmdlets over '{0}' class - {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" - - - - ..\..\..\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - {Locked} - - - Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. - {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} -{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> -{1} is a placeholder for a cmdlet parameter name. Example: Name - - - Cannot process Cmdlet Definition XML for the following file: {0}. {1} - {0} is a placeholder for a file name. -{1} is an exception message copied from an XmlException or XmlSchemaException - - - The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. - {StrContains="CmdletParameterSet"} -{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' -{1} is a placeholder for a parameter set name. Example: 'foo' - - - Cannot process the ObjectModelWrapper attribute. The {0} type defines multiple parameter sets. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. - {StrContains="ObjectModelWrapper"} -{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress - - - Cannot process the ObjectModelWrapper attribute. The {0} type is an open generic type. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. - {StrContains="ObjectModelWrapper"} -{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress - - - Cannot process the ObjectModelWrapper attribute. The {0} type is not derived from the following class: {1}. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. - {StrContains="ObjectModelWrapper"} -{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress -{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper - - - Cannot process the ObjectModelWrapper attribute. The {0} type defines the {1} cmdlet parameter with a {2} attribute parameter that is ignored. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. - {StrContains="ObjectModelWrapper"} -{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress -{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' -{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName - - - Cannot define the {0} parameter for the {1} cmdlet. The parameter name is already defined by the {2} class. Change the name of the parameter in Cmdlet Definition XML and retry. - {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' -{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' -{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' - - - Cannot define the {0} parameter for the {1} cmdlet. The parameter name is already defined within the {2} XML element. Change the name of the parameter in the Cmdlet Definition XML, and then try again. - {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' -{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' -{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> - - - {0} {1} - This is a resource string, to support locales where the order of placeholders might need to be reversed. -{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") -{1} is a placeholder for a secondary exception message (i.e. "") - - - The value of the EnumName attribute doesn't translate to a valid C# identifier: {0}. Verify the EnumName attribute in the Cmdlet Definition XML, and then try again. - {StrContains="EnumName"} - - - The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. - {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} - - - Cannot process the <Enum EnumName="{0}" ...> element. {1} - {StrContains="Enum"} {StrContains="EnumName"} - - - The remote computer returned a CDXML file that is not valid. The following cmdlet adapter is not supported for importing a CDXML module from a remote computer: {0} - {0} is a placeholder for a fully qualified type name - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Cmdlets over '{0}' class + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + ..\..\..\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + {Locked} + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Cannot process Cmdlet Definition XML for the following file: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Cannot process the ObjectModelWrapper attribute. The {0} type defines multiple parameter sets. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Cannot process the ObjectModelWrapper attribute. The {0} type is an open generic type. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Cannot process the ObjectModelWrapper attribute. The {0} type is not derived from the following class: {1}. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Cannot process the ObjectModelWrapper attribute. The {0} type defines the {1} cmdlet parameter with a {2} attribute parameter that is ignored. Verify that the Cmdlet Definition XML specifies a valid type in the ObjectModelWrapper attribute and retry. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Cannot define the {0} parameter for the {1} cmdlet. The parameter name is already defined by the {2} class. Change the name of the parameter in Cmdlet Definition XML and retry. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Cannot define the {0} parameter for the {1} cmdlet. The parameter name is already defined within the {2} XML element. Change the name of the parameter in the Cmdlet Definition XML, and then try again. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + The value of the EnumName attribute doesn't translate to a valid C# identifier: {0}. Verify the EnumName attribute in the Cmdlet Definition XML, and then try again. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Cannot process the <Enum EnumName="{0}" ...> element. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + The remote computer returned a CDXML file that is not valid. The following cmdlet adapter is not supported for importing a CDXML module from a remote computer: {0} + {0} is a placeholder for a fully qualified type name + + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/TestData/CatalogTestData/CatalogTestFile1.mof b/test/powershell/Modules/Microsoft.PowerShell.Security/TestData/CatalogTestData/CatalogTestFile1.mof index 741cbf56c35..d954303218b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/TestData/CatalogTestData/CatalogTestFile1.mof +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/TestData/CatalogTestData/CatalogTestFile1.mof @@ -1,42 +1,42 @@ -/* -@TargetNode='localhost' -@GeneratedBy=Duser1 -@GenerationDate=09/22/2015 15:25:48 -@GenerationHost=DEV-10545-246 -*/ - -instance of MyPSClassFileData as $MyPSClassFileData1ref -{ -SomeData = "testing"; - AnInt = 50; - -}; - -instance of MyPSClassFileWithClass as $MyPSClassFileWithClass1ref -{ -ResourceID = "[MyPSClassFileWithClass]myfile"; - SourceInfo = "C:\\CITests_0\\DSC\\Tests\\LCM\\ConfigurationScripts\\RunAsUserMandatorywithPowershellClasses.ps1::22::7::MyPSClassFileWithClass"; - FileData = $MyPSClassFileData1ref; - ModuleName = "ClassPropertyResource1"; - Path = "C:\\Users\\Duser1\\AppData\\Local\\Temp\\testclassesObject.txt"; - ModuleVersion = "1.0"; - ConfigurationName = "RunAsUserMandatorywithPowershellClasses"; -}; -instance of OMI_ConfigurationDocument - - { - Version="2.0.0"; - - MinimumCompatibleVersion = "2.0.0"; - - CompatibleVersionAdditionalProperties= {"Omi_BaseResource:ConfigurationName"}; - - Author="Duser1"; - - GenerationDate="09/22/2015 15:25:48"; - - GenerationHost="DEV-10545-246"; - - Name="RunAsUserMandatorywithPowershellClasses"; - - }; +/* +@TargetNode='localhost' +@GeneratedBy=Duser1 +@GenerationDate=09/22/2015 15:25:48 +@GenerationHost=DEV-10545-246 +*/ + +instance of MyPSClassFileData as $MyPSClassFileData1ref +{ +SomeData = "testing"; + AnInt = 50; + +}; + +instance of MyPSClassFileWithClass as $MyPSClassFileWithClass1ref +{ +ResourceID = "[MyPSClassFileWithClass]myfile"; + SourceInfo = "C:\\CITests_0\\DSC\\Tests\\LCM\\ConfigurationScripts\\RunAsUserMandatorywithPowershellClasses.ps1::22::7::MyPSClassFileWithClass"; + FileData = $MyPSClassFileData1ref; + ModuleName = "ClassPropertyResource1"; + Path = "C:\\Users\\Duser1\\AppData\\Local\\Temp\\testclassesObject.txt"; + ModuleVersion = "1.0"; + ConfigurationName = "RunAsUserMandatorywithPowershellClasses"; +}; +instance of OMI_ConfigurationDocument + + { + Version="2.0.0"; + + MinimumCompatibleVersion = "2.0.0"; + + CompatibleVersionAdditionalProperties= {"Omi_BaseResource:ConfigurationName"}; + + Author="Duser1"; + + GenerationDate="09/22/2015 15:25:48"; + + GenerationHost="DEV-10545-246"; + + Name="RunAsUserMandatorywithPowershellClasses"; + + };