├── .gitattributes ├── .gitignore ├── .gitmodules ├── Design.jpg ├── Generating_the_PowerShell_Binary_Module.jpg ├── Graph Schemas ├── v1.0 - 20181126.csdl └── v1.0 - 20190629.csdl ├── Intune-PowerShell-SDK-Code-Generator.yml ├── PowerShellGraphSDKGenerator.sln ├── README.md ├── SECURITY.md ├── Scripts ├── build-full.ps1 ├── build-portable.ps1 ├── dotnet-install.ps1 ├── init.ps1 ├── msbuild-install.ps1 ├── run.ps1 └── test.ps1 ├── Test Graph Schemas ├── beta-20180209 - Intune.csdl ├── beta-20180209.csdl ├── beta-20180604 - Intune.csdl ├── beta-20180604.csdl ├── v1.0-20180222 - Intune.csdl ├── v1.0-20180222.csdl ├── v1.0-20180406 - Intune.csdl ├── v1.0-20180406.csdl ├── v1.0-20180628 - Intune.csdl ├── v1.0-20180628.csdl ├── v1.0-20180813 - Intune.csdl ├── v1.0-20180813.csdl ├── v1.0-20180917 - Intune.csdl ├── v1.0-20180917.csdl ├── v1.0-20190629 - Intune.csdl └── v1.0-20190629.csdl ├── Tests ├── AppProtectionPolicyTests.ps1 ├── CompliancePolicyTests.ps1 ├── ConfigurationPolicyTests.ps1 ├── DeviceAppManagement │ ├── AppProtectionPolicies.ps1 │ └── MobileApps.ps1 ├── DeviceManagement │ ├── DeviceCompliancePolicies.ps1 │ └── DeviceManagement.ps1 ├── GetDeviceAppMgmtTests.ps1 ├── GetDeviceMgmtTests.ps1 ├── LobApps │ └── UploadIOSLobApp.ps1 ├── Misc │ ├── POC_AllOS_Create_Cmdlets.ps1 │ └── POC_AllOS_Reset_Cmdlets.ps1 └── Set-IntuneContext.psm1 ├── init.cmd └── src ├── GraphODataPowerShellWriter ├── Generator │ ├── Behaviors │ │ ├── Object Factories │ │ │ ├── 1_OdcmModelToObjectFactoriesConversionBehavior.cs │ │ │ └── 2_ObjectFactoryToCSharpFileConversionBehavior.cs │ │ └── SDK Operations │ │ │ ├── 1_OdcmModelToNodesConversionBehavior.cs │ │ │ ├── 2_NodeToResourceConversionBehavior.cs │ │ │ ├── 3_ResourceToCSharpFileConversionBehavior.cs │ │ │ └── 4_CSharpFileToTextFileConversionBehavior.cs │ └── Models │ │ ├── CSharpAbstractions │ │ ├── CSharpAccessModifier.cs │ │ ├── CSharpArgument.cs │ │ ├── CSharpAttribute.cs │ │ ├── CSharpClass.cs │ │ ├── CSharpDocumentationComment.cs │ │ ├── CSharpFile.cs │ │ ├── CSharpMethod.cs │ │ └── CSharpProperty.cs │ │ ├── ODataRoute.cs │ │ ├── OdcmNode.cs │ │ └── PowerShellAbstractions │ │ ├── Cmdlet.cs │ │ ├── CmdletDocumentation.cs │ │ ├── CmdletDocumentationLink.cs │ │ ├── CmdletName.cs │ │ ├── CmdletOperationTypes.cs │ │ ├── CmdletParameter.cs │ │ ├── CmdletParameterDocumentation.cs │ │ ├── CmdletParameterSet.cs │ │ ├── CmdletParameterSets.cs │ │ ├── ObjectFactoryCmdlet.cs │ │ ├── OperationCmdlet.cs │ │ └── Resource.cs ├── GraphODataPowerShellSDKWriter.csproj ├── ListCmdlets.ps1 ├── PowerShellSDKWriter.cs └── Utils │ ├── CSharpAccessModifierUtils.cs │ ├── CSharpClassAttributeHelper.cs │ ├── CSharpFileHelper.cs │ ├── CSharpMethodHelper.cs │ ├── CSharpNamingUtils.cs │ ├── CSharpPropertyAttributeHelper.cs │ ├── CSharpTypeUtils.cs │ ├── CmdletOperationTypeUtils.cs │ ├── CmdletParameterUtils.cs │ ├── DocumentationUtils.cs │ ├── EnumerableUtils.cs │ ├── OdcmUtils.cs │ └── StringUtils.cs └── PowerShellGraphSDK ├── .gitignore ├── Common ├── Attributes │ ├── DerivedTypeAttribute.cs │ ├── ExpandableAttribute.cs │ ├── IdParameter.cs │ ├── ODataTypeAttribute.cs │ ├── ParameterSetSelectorAttribute.cs │ ├── ResourceIdParameterAttribute.cs │ ├── ResourceReferenceAttribute.cs │ ├── ResourceTypePropertyNameAttribute.cs │ ├── SelectableAttribute.cs │ ├── SortableAttribute.cs │ ├── TypeCastParameterAttribute.cs │ ├── ValidateTypeAttribute.cs │ └── ValidateUrlAttribute.cs ├── Constants │ ├── AnnotationTerms.cs │ ├── EdmTypeNames.cs │ ├── QueryParameters.cs │ ├── RequestProperties.cs │ └── SearchResultProperties.cs ├── EnvironmentParameters.cs ├── Exceptions │ ├── AdalAuthException.cs │ ├── AuthException.cs │ ├── MsiAuthException.cs │ └── PSGraphSDKException.cs ├── PSAuthenticationError.cs └── Utils │ ├── AuthUtils.cs │ ├── AuthUtils_NetFramework.cs │ ├── AuthUtils_NetStandard.cs │ ├── CmdletUtils.cs │ ├── ExceptionUtils.cs │ ├── JsonUtils.cs │ ├── ODataTypeUtils.cs │ ├── PSObjectUtils.cs │ ├── ReferencePathGenerator.cs │ └── SdkAuthResult.cs ├── LICENSE ├── PowerShellCmdlets ├── ActionCmdlet.cs ├── DeleteCmdlet.cs ├── FunctionReturningCollectionCmdlet.cs ├── FunctionReturningEntityCmdlet.cs ├── GetCmdlet.cs ├── GetOrSearchCmdlet.cs ├── GetStreamCmdlet.cs ├── ODataCmdletBase.cs ├── ODataCmdletBase_Helpers.cs ├── ODataCmdletBase_Overridable.cs ├── ODataCmdletBase_Private.cs ├── ObjectFactoryCmdletBase.cs ├── PatchCmdlet.cs ├── PostCmdlet.cs ├── PostOrPatchCmdlet.cs ├── PostReferenceToCollectionCmdlet.cs ├── PutReferenceToEntityCmdlet.cs ├── UpdateStreamCmdlet.cs └── Utils │ ├── ModuleInitializer.cs │ └── UtilCmdlets.cs ├── PowerShellGraphSDK.csproj ├── PowerShellGraphSDK.sln ├── PowerShellModuleAdditions ├── CustomModules │ ├── AliasCmdlets.psm1 │ └── UtilCmdlets.psm1 ├── LICENSE.txt ├── README.md └── Third Party Notices.txt ├── Properties └── AssemblyInfo.cs ├── README.md ├── Samples ├── Apps │ ├── Apps.psm1 │ ├── Microsoft.Graph.Intune.Apps.psd1 │ ├── UploadIOSLobApp.ps1 │ ├── UploadLobApp.psm1 │ ├── VisualizeData.ps1 │ ├── test.apk │ └── test.ipa └── README.md └── Scripts ├── ListCmdlets.ps1 └── generateModuleManifest.ps1 /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "submodules/vipr"] 2 | path = submodules/vipr 3 | url = https://github.com/Microsoft/Vipr.git 4 | ignore = dirty 5 | 6 | [submodule "submodules/Intune-PowerShell-SDK"] 7 | path = submodules/Intune-PowerShell-SDK 8 | url = https://github.com/Microsoft/Intune-PowerShell-SDK.git 9 | ignore = dirty 10 | -------------------------------------------------------------------------------- /Design.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/1a774764c77e87313f5ff97a3c493811dbad1482/Design.jpg -------------------------------------------------------------------------------- /Generating_the_PowerShell_Binary_Module.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/1a774764c77e87313f5ff97a3c493811dbad1482/Generating_the_PowerShell_Binary_Module.jpg -------------------------------------------------------------------------------- /Intune-PowerShell-SDK-Code-Generator.yml: -------------------------------------------------------------------------------- 1 | page_type: sample 2 | products: 3 | - ms-graph 4 | languages: 5 | - csharp 6 | extensions: 7 | contentType: tools 8 | technologies: 9 | - Microsoft Graph 10 | services: 11 | - Intune 12 | createdDate: '6/15/2018 9:32:53 AM' 13 | title: Intune-PowerShell-SDK-Code-Generator 14 | description: Custom ODCM Writer built atop Vipr to auto-generate PowerShell cmdlets corresponding to CRUD operations for Microsoft Intune Graph Api. 15 | -------------------------------------------------------------------------------- /PowerShellGraphSDKGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2015 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PowerShellGraphSDK", "src\PowerShellGraphSDK\PowerShellGraphSDK.csproj", "{831E21CA-9580-4B96-A239-2F85190B5E6C}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphODataPowerShellSDKWriter", "src\GraphODataPowerShellWriter\GraphODataPowerShellSDKWriter.csproj", "{3B8C0953-5E14-4D77-98F3-411CA0A3CE78}" 9 | ProjectSection(ProjectDependencies) = postProject 10 | {831E21CA-9580-4B96-A239-2F85190B5E6C} = {831E21CA-9580-4B96-A239-2F85190B5E6C} 11 | EndProjectSection 12 | EndProject 13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{9F6E2D2F-5688-4624-BB99-0FE1E0DC1313}" 14 | ProjectSection(SolutionItems) = preProject 15 | Tests\DeviceAppManagement\AppProtectionPolicies.ps1 = Tests\DeviceAppManagement\AppProtectionPolicies.ps1 16 | Tests\LobApps\Apps.psm1 = Tests\LobApps\Apps.psm1 17 | Tests\DeviceManagement\DeviceCompliancePolicies.ps1 = Tests\DeviceManagement\DeviceCompliancePolicies.ps1 18 | Tests\DeviceManagement.ps1 = Tests\DeviceManagement.ps1 19 | Tests\LobApps\Microsoft.Graph.Intune.Apps.psd1 = Tests\LobApps\Microsoft.Graph.Intune.Apps.psd1 20 | Tests\DeviceAppManagement\MobileApps.ps1 = Tests\DeviceAppManagement\MobileApps.ps1 21 | Tests\LobApps\Module Presentation.md = Tests\LobApps\Module Presentation.md 22 | Tests\LobApps\POC_AllOS_Create_Cmdlets.ps1 = Tests\LobApps\POC_AllOS_Create_Cmdlets.ps1 23 | Tests\LobApps\POC_AllOS_Reset_Cmdlets.ps1 = Tests\LobApps\POC_AllOS_Reset_Cmdlets.ps1 24 | Tests\Run-AppProtectionPolicyTests.ps1 = Tests\Run-AppProtectionPolicyTests.ps1 25 | Tests\Run-CompliancePolicyTests.ps1 = Tests\Run-CompliancePolicyTests.ps1 26 | Tests\Run-ConfigurationPolicyTests.ps1 = Tests\Run-ConfigurationPolicyTests.ps1 27 | Tests\Run-GetDeviceAppMgmtTests.ps1 = Tests\Run-GetDeviceAppMgmtTests.ps1 28 | Tests\Run-GetDeviceMgmtTests.ps1 = Tests\Run-GetDeviceMgmtTests.ps1 29 | Tests\Set-IntuneContext.psm1 = Tests\Set-IntuneContext.psm1 30 | Tests\LobApps\UploadIOSLobApp.ps1 = Tests\LobApps\UploadIOSLobApp.ps1 31 | Tests\LobApps\UploadLobApp.psm1 = Tests\LobApps\UploadLobApp.psm1 32 | Tests\LobApps\VisualizeData.ps1 = Tests\LobApps\VisualizeData.ps1 33 | EndProjectSection 34 | EndProject 35 | Global 36 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 37 | Debug|Any CPU = Debug|Any CPU 38 | Release|Any CPU = Release|Any CPU 39 | EndGlobalSection 40 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 41 | {831E21CA-9580-4B96-A239-2F85190B5E6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {831E21CA-9580-4B96-A239-2F85190B5E6C}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {831E21CA-9580-4B96-A239-2F85190B5E6C}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {831E21CA-9580-4B96-A239-2F85190B5E6C}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {3B8C0953-5E14-4D77-98F3-411CA0A3CE78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {3B8C0953-5E14-4D77-98F3-411CA0A3CE78}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {3B8C0953-5E14-4D77-98F3-411CA0A3CE78}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {3B8C0953-5E14-4D77-98F3-411CA0A3CE78}.Release|Any CPU.Build.0 = Release|Any CPU 49 | EndGlobalSection 50 | GlobalSection(SolutionProperties) = preSolution 51 | HideSolutionNode = FALSE 52 | EndGlobalSection 53 | GlobalSection(ExtensibilityGlobals) = postSolution 54 | SolutionGuid = {E45802D0-583B-4A6F-B149-467F7DDBF338} 55 | EndGlobalSection 56 | EndGlobal 57 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /Scripts/build-full.ps1: -------------------------------------------------------------------------------- 1 | param ( 2 | [string]$BuildTargets = 'Restore;Rebuild', 3 | [string]$WorkingDirectory = "$(Get-Location)", 4 | [string]$OutputPath, 5 | [string]$MSBuildExe32 = '%ProgramFiles(x86)%\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe', 6 | [string]$MSBuildExe64 = '%ProgramFiles%\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe', 7 | [string]$Verbosity = 'minimal', 8 | [string]$AssemblyName, 9 | [string]$GraphSchema 10 | ) 11 | 12 | # Expand environment variables 13 | $WorkingDirectory = ([System.Environment]::ExpandEnvironmentVariables($WorkingDirectory)) 14 | $OutputPath = ([System.Environment]::ExpandEnvironmentVariables($OutputPath)) 15 | $MSBuildExe32 = ([System.Environment]::ExpandEnvironmentVariables($MSBuildExe32)) 16 | $MSBuildExe64 = ([System.Environment]::ExpandEnvironmentVariables($MSBuildExe64)) 17 | $GraphSchema = ([System.Environment]::ExpandEnvironmentVariables($GraphSchema)) 18 | 19 | # Get the MSBuild.exe path 20 | $msBuildExe = $MSBuildExe32 21 | if (-Not (Test-Path $msBuildExe)) { 22 | $msBuildExe = $MSBuildExe64 23 | } 24 | 25 | # Install MSBuild.exe if it doesn't exist 26 | if (-Not (Test-Path $msBuildExe)) { 27 | Write-Host "VS Build Tools 2017 could not be found. If the following installation fails, you can install it from 'https://visualstudio.microsoft.com/downloads/'" -ForegroundColor Yellow 28 | Invoke-Expression "$env:msbuildInstallScript" 29 | 30 | # Double check that MSBuild.exe now exists 31 | $msBuildExe = $MSBuildExe32 32 | if (-Not (Test-Path $msBuildExe)) { 33 | $msBuildExe = $MSBuildExe64 34 | } 35 | if (-Not (Test-Path $msBuildExe)) { 36 | Write-Host "MSBuild was not found at '$msBuildExe'" -ForegroundColor Red 37 | throw "Installation of VS Build Tools 2017 failed - please try to install it manually" 38 | } 39 | } 40 | 41 | # Compile the MSBuild arguments 42 | $MSBuildArguments = @( 43 | "/p:Configuration=$($env:buildConfiguration)", 44 | "/t:$BuildTargets", 45 | "/p:UseSharedCompilation=false", 46 | "/nr:false", 47 | "/v:$Verbosity", 48 | "/ignore:.sln" 49 | ) 50 | 51 | # Set the output path if required 52 | if (-Not [string]::IsNullOrWhiteSpace($OutputPath)) 53 | { 54 | $MSBuildArguments += "/p:OutputPath=`"$OutputPath`"" 55 | } 56 | 57 | # Set the assembly name if required 58 | if (-Not [string]::IsNullOrWhiteSpace($AssemblyName)) 59 | { 60 | $MSBuildArguments += "/p:AssemblyName=$AssemblyName" 61 | } 62 | 63 | # Select the default graph schema if one was not provided 64 | if ($GraphSchema) 65 | { 66 | # Add the schema path to the MSBuild arguments if it is a valid path 67 | if (Test-Path $GraphSchema) 68 | { 69 | $MSBuildArguments += "/p:GraphSchemaPath=`"$GraphSchema`"" 70 | Write-Host "MSBuild arguments: " -f Magenta 71 | $MSBuildArguments | ForEach-Object { 72 | Write-Host $_ -f Magenta 73 | } 74 | } else { 75 | throw "Unable to find Graph schema at '$GraphSchema' - provide a valid path to a schema file" 76 | } 77 | } 78 | 79 | # Run MSBuild in the given working directory 80 | Push-Location $WorkingDirectory 81 | try { 82 | $command = "`"$msBuildExe`" $MSBuildArguments" 83 | Write-Host $command -f DarkCyan 84 | & $msBuildExe $MSBuildArguments 85 | if (-Not $?) 86 | { 87 | throw "MSBuild exited with error code '$LastExitCode'" 88 | } 89 | } finally { 90 | Pop-Location 91 | } -------------------------------------------------------------------------------- /Scripts/build-portable.ps1: -------------------------------------------------------------------------------- 1 | param ( 2 | [string]$WorkingDirectory = "$(Get-Location)", 3 | [string]$OutputPath, 4 | [string]$Verbosity = 'minimal', 5 | [string]$AssemblyName 6 | ) 7 | 8 | # Expand environment variables 9 | $WorkingDirectory = ([System.Environment]::ExpandEnvironmentVariables($WorkingDirectory)) 10 | $OutputPath = ([System.Environment]::ExpandEnvironmentVariables($OutputPath)) 11 | 12 | # Make sure the dotnet command is installed 13 | $dotnetCliVersion = Invoke-Expression 'dotnet --version' 14 | 15 | # If dotnet is not installed, attempt to install it 16 | if ($dotnetCliVersion.Contains('\n') -or [string]::IsNullOrWhitespace($dotnetCliVersion)) { 17 | & $env:dotnetInstallScript 18 | } 19 | 20 | # Compile the MSBuild arguments 21 | $BuildArguments = @( 22 | "--configuration $($env:buildConfiguration)", 23 | "--verbosity $Verbosity" 24 | ) 25 | 26 | # Set the output path if required 27 | if (-Not [string]::IsNullOrWhiteSpace($OutputPath)) 28 | { 29 | $MSBuildArguments += "--output `"$OutputPath`"" 30 | } 31 | 32 | # Set the assembly name if required 33 | if (-Not [string]::IsNullOrWhiteSpace($AssemblyName)) 34 | { 35 | $BuildArguments += "/p:AssemblyName=$AssemblyName" 36 | } 37 | 38 | # Run MSBuild in the given working directory 39 | Push-Location $WorkingDirectory 40 | try { 41 | $command = "dotnet build $BuildArguments" 42 | Write-Host $command -f DarkCyan 43 | Invoke-Expression $command 44 | if (-Not $?) 45 | { 46 | throw "MSBuild exited with error code '$LastExitCode'" 47 | } 48 | } finally { 49 | Pop-Location 50 | } 51 | -------------------------------------------------------------------------------- /Scripts/msbuild-install.ps1: -------------------------------------------------------------------------------- 1 | $msBuildInstaller = ([System.Environment]::ExpandEnvironmentVariables("%TEMP%\vs_BuildTools.exe")) 2 | Invoke-WebRequest -OutFile "$msBuildInstaller" "https://aka.ms/vs/15/release/vs_buildtools.exe" 3 | $process = Start-Process -FilePath "$msBuildInstaller" -Verb RunAs -Wait -PassThru -ArgumentList "--add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Workload.NetCoreBuildTools --add Microsoft.VisualStudio.Workload.ManagedDesktopBuildTools --add Microsoft.VisualStudio.Workload.WebBuildTools --add Microsoft.Net.Component.4.7.1.SDK --add Microsoft.Net.Component.4.7.1.TargetingPack --norestart --quiet --force" 4 | if ($process.ExitCode -eq 0) { 5 | Write-Host "Done installing VS Build Tools" -ForegroundColor Green 6 | Write-Host "Installation may require a restart - please check by opening the 'Visual Studio Installer' application" -f Yellow 7 | } else { 8 | # Failed to install - print an error on the command line 9 | throw "Failed to install VS Build Tools. Exit code: $($process.ExitCode)" 10 | } -------------------------------------------------------------------------------- /Scripts/run.ps1: -------------------------------------------------------------------------------- 1 | # Start the new PowerShell context 2 | [CmdletBinding()] 3 | param( 4 | [Parameter(Mandatory=$true)] 5 | [ValidateNotNullOrEmpty()] 6 | [string]$SdkDirectory 7 | ) 8 | 9 | $moduleLocation = "$SdkDirectory\$($env:moduleName).$($env:moduleExtension)" 10 | 11 | # Check that a build of the SDK exists 12 | if (-Not (Test-Path "$moduleLocation" -PathType Leaf)) 13 | { 14 | throw "Cannot find '$moduleLocation'. Run the 'build' command before running the module." 15 | } 16 | 17 | try { 18 | Write-Host 'Importing module in a new PowerShell context...' 19 | Write-Host 'NOTE: Type ''exit'' to return to the current context.' -f Yellow 20 | 21 | powershell -NoExit -Command { 22 | param( 23 | $module 24 | ) 25 | 26 | try { 27 | (Get-Host).UI.RawUI.WindowTitle = "$module" 28 | (Get-Host).UI.RawUI.ForegroundColor = 'Cyan' 29 | (Get-Host).UI.RawUI.BackgroundColor = 'Black' 30 | 31 | Import-Module "$module" 32 | Connect-MSGraph 33 | } catch { 34 | Write-Error "Failed to initialize new PowerShell context: '$_'" 35 | exit 36 | } 37 | } -args $moduleLocation 38 | 39 | # Check that the special PowerShell context exited successfully 40 | if (-Not $?) 41 | { 42 | Write-Host "Child PowerShell context exited with error code '$LastExitCode'" -f Red 43 | Write-Host 44 | } 45 | } catch { 46 | Write-Host "Failed to run child PowerShell context" -f Red 47 | Write-Host 48 | } finally { 49 | # Restore the old settings 50 | (Get-Host).UI.RawUI.WindowTitle = $env:standardWindowTitle 51 | (Get-Host).UI.RawUI.ForegroundColor = $env:standardForegroundColor 52 | (Get-Host).UI.RawUI.BackgroundColor = $env:standardBackgroundColor 53 | } 54 | -------------------------------------------------------------------------------- /Scripts/test.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param( 3 | [Parameter(Mandatory=$true)] 4 | [ValidateNotNullOrEmpty()] 5 | [string]$SdkDirectory, 6 | 7 | [Parameter(Mandatory = $false)] 8 | [ValidateNotNullOrEmpty()] 9 | [string]$AdminUPN="$env:adminUPN" 10 | ) 11 | 12 | $moduleLocation = "$SdkDirectory\$($env:moduleName).$($env:moduleExtension)" 13 | $installFromPSGallery = $false 14 | 15 | # Check that a build of the SDK exists 16 | if (-Not (Test-Path "$moduleLocation" -PathType Leaf)) 17 | { 18 | Write-Host "Cannot find '$moduleLocation'. Installing Module from PowerShell Gallery" 19 | $installFromPSGallery = $true 20 | } 21 | 22 | # Run the tests 23 | try { 24 | (Get-Host).UI.RawUI.WindowTitle = "$module" 25 | (Get-Host).UI.RawUI.ForegroundColor = 'Cyan' 26 | (Get-Host).UI.RawUI.BackgroundColor = 'Black' 27 | $testScripts = Get-ChildItem -Path "$env:testDir" -Recurse -Filter '*.ps1' 28 | 29 | # 30 | # Import the Intune PowerShell SDK Module 31 | # 32 | Write-Host "Import-Module from $moduleLocation" 33 | Import-Module $moduleLocation 34 | 35 | # 36 | # Setup the test context 37 | # 38 | Import-Module $env:testDir\Set-IntuneContext.psm1 39 | Set-IntuneContext 40 | 41 | # 42 | # Run the Tests 43 | # 44 | $testScripts | ForEach-Object { 45 | Write-Host -f Yellow "RUNNING: $($_.BaseName)" 46 | try { 47 | Invoke-Expression "$($_.FullName)" 48 | } catch { 49 | throw "Error: $_" 50 | } 51 | Write-Host -f Magenta "COMPLETED: $($_.BaseName)" 52 | Write-Host 53 | } 54 | 55 | if (-Not $?) 56 | { 57 | throw "Tests failed with error code '$LastExitCode'" 58 | } 59 | } catch { 60 | Write-Error "Error: $_" 61 | } finally { 62 | # Restore the old settings 63 | (Get-Host).UI.RawUI.WindowTitle = $env:standardWindowTitle 64 | (Get-Host).UI.RawUI.ForegroundColor = $env:standardForegroundColor 65 | (Get-Host).UI.RawUI.BackgroundColor = $env:standardBackgroundColor 66 | 67 | exit 68 | } -------------------------------------------------------------------------------- /Tests/AppProtectionPolicyTests.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory = $false)] 3 | [ValidateNotNullOrEmpty()] 4 | [string]$ModuleName="$env:moduleName", 5 | 6 | [Parameter(Mandatory = $false)] 7 | [ValidateNotNullOrEmpty()] 8 | [string]$OutputDirectory="$env:sdkDir", 9 | 10 | [Parameter(Mandatory = $false)] 11 | [ValidateNotNullOrEmpty()] 12 | [string]$AdminUPN="$env:adminUPN" 13 | ) 14 | 15 | # 16 | # Setup the test context 17 | # 18 | Import-Module $env:testDir\Set-IntuneContext.psm1 19 | Write-Output "Setting IntuneContext..." 20 | Set-IntuneContext -AdminUPN $AdminUPN 21 | 22 | # 23 | # Create iosManagedAppProtection 24 | # 25 | Write-Output "Creating iOS MAM / APP Policy ..." 26 | $iosManagedAppProtection = New-IntuneAppProtectionPolicy -iosManagedAppProtection -displayName "iOS MAM / APP Policy" ` 27 | -periodOfflineBeforeAccessCheck (New-TimeSpan -Hours 12) ` 28 | -periodOnlineBeforeAccessCheck (New-TimeSpan -Minutes 30)` 29 | -allowedInboundDataTransferSources managedApps -allowedOutboundDataTransferDestinations managedApps ` 30 | -allowedOutboundClipboardSharingLevel managedAppsWithPasteIn -organizationalCredentialsRequired $false ` 31 | -dataBackupBlocked $true -managedBrowserToOpenLinksRequired $false -deviceComplianceRequired $false ` 32 | -saveAsBlocked $true -periodOfflineBeforeWipeIsEnforced (New-TimeSpan -Days 30) ` 33 | -pinRequired $true -maximumPinRetries 5 -simplePinBlocked $false -minimumPinLength 4 ` 34 | -pinCharacterSet numeric -periodBeforePinReset (New-TimeSpan -Days 30) -allowedDataStorageLocations @("oneDriveForBusiness","sharePoint") ` 35 | -contactSyncBlocked $false -printBlocked $true -fingerprintBlocked $false ` 36 | -disableAppPinIfDevicePinIsSet $false 37 | 38 | # 39 | # Assign iosManagedAppProtection to 'Intune POC Users' group 40 | # 41 | $IPU_Id = (Get-AADGroup -Filter "displayName eq 'Intune POC Users'").id 42 | Write-Output "Assigning $iosGeneralDeviceConfiguration to 'Intune POC Users' group..." 43 | Invoke-IntuneAppProtectionPolicyIosAssign -iosManagedAppProtectionId $iosManagedAppProtection.id ` 44 | -assignments (New-TargetedManagedAppPolicyAssignmentObject ` 45 | -target (New-DeviceAndAppManagementAssignmentTargetObject ` 46 | -groupAssignmentTarget -groupId "$IPU_Id")) 47 | 48 | Write-Output "Test complete." -------------------------------------------------------------------------------- /Tests/CompliancePolicyTests.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory = $false)] 3 | [ValidateNotNullOrEmpty()] 4 | [string]$ModuleName="$env:moduleName", 5 | 6 | [Parameter(Mandatory = $false)] 7 | [ValidateNotNullOrEmpty()] 8 | [string]$OutputDirectory="$env:sdkDir", 9 | 10 | [Parameter(Mandatory = $false)] 11 | [ValidateNotNullOrEmpty()] 12 | [string]$AdminUPN="$env:adminUPN" 13 | ) 14 | 15 | # 16 | # Setup the test context 17 | # 18 | Import-Module $env:testDir\Set-IntuneContext.psm1 19 | Write-Output "Setting IntuneContext..." 20 | Set-IntuneContext -AdminUPN $AdminUPN 21 | 22 | # 23 | # Create iosCompliancePolicy 24 | # 25 | Write-Output "Creating iOS Compliance Policy ..." 26 | $iosCompliancePolicy = New-IntuneDeviceCompliancePolicy -iosCompliancePolicy ` 27 | -displayName "iOS Compliance Policy" -passcodeRequired $true -passcodeMinimumLength 6 ` 28 | -passcodeMinutesOfInactivityBeforeLock 15 -securityBlockJailbrokenDevices $true ` 29 | -scheduledActionsForRule (New-DeviceComplianceScheduledActionForRuleObject -ruleName PasswordRequired ` 30 | -scheduledActionConfigurations (New-DeviceComplianceActionItemObject -gracePeriodHours 0 -actionType block -notificationTemplateId "")) 31 | 32 | # 33 | # Assign iosCompliancePolicy to 'Intune POC Users' group 34 | # 35 | $IPU_Id = (Get-AADGroup -Filter "displayName eq 'Intune POC Users'").id 36 | Write-Output "Assigning $iosCompliancePolicy to 'Intune POC Users' group..." 37 | Invoke-IntuneDeviceCompliancePolicyAssign -deviceCompliancePolicyId $iosCompliancePolicy.id ` 38 | -assignments (New-DeviceCompliancePolicyAssignmentObject ` 39 | -target (New-DeviceAndAppManagementAssignmentTargetObject ` 40 | -groupAssignmentTarget -groupId "$IPU_Id")) 41 | 42 | Write-Output "Test complete." -------------------------------------------------------------------------------- /Tests/ConfigurationPolicyTests.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory = $false)] 3 | [ValidateNotNullOrEmpty()] 4 | [string]$ModuleName="$env:moduleName", 5 | 6 | [Parameter(Mandatory = $false)] 7 | [ValidateNotNullOrEmpty()] 8 | [string]$OutputDirectory="$env:sdkDir", 9 | 10 | [Parameter(Mandatory = $false)] 11 | [ValidateNotNullOrEmpty()] 12 | [string]$AdminUPN="$env:adminUPN" 13 | ) 14 | 15 | # 16 | # Setup the test context 17 | # 18 | Import-Module $env:testDir\Set-IntuneContext.psm1 19 | Write-Output "Setting IntuneContext..." 20 | Set-IntuneContext -AdminUPN $AdminUPN 21 | 22 | # 23 | # Create iosGeneralDeviceConfiguration 24 | # 25 | Write-Output "Creating iOS Compliance Policy ..." 26 | $iosGeneralDeviceConfiguration = New-IntuneDeviceConfigurationPolicy -iosGeneralDeviceConfiguration ` 27 | -displayName "Chicago - iOS Device Restriction Policy" ` 28 | -iCloudBlockBackup $true -iCloudBlockDocumentSync $true -iCloudBlockPhotoStreamSync $true 29 | 30 | # 31 | # Assign iosGeneralDeviceConfiguration to 'Intune POC Users' group 32 | # 33 | $IPU_Id = (Get-AADGroup -Filter "displayName eq 'Intune POC Users'").id 34 | Write-Output "Assigning $iosGeneralDeviceConfiguration to 'Intune POC Users' group..." 35 | Invoke-IntuneDeviceConfigurationPolicyAssign -deviceConfigurationId $iosGeneralDeviceConfiguration.id ` 36 | -assignments (New-DeviceConfigurationAssignmentObject ` 37 | -target (New-DeviceAndAppManagementAssignmentTargetObject ` 38 | -groupAssignmentTarget -groupId "$IPU_Id")) 39 | 40 | 41 | Write-Output "Test complete." -------------------------------------------------------------------------------- /Tests/DeviceAppManagement/AppProtectionPolicies.ps1: -------------------------------------------------------------------------------- 1 | # Create a policy 2 | Write-Host "Creating an iOS app protection policy..." 3 | $policy = New-IntuneAppProtectionPolicy ` 4 | -iosManagedAppProtection ` 5 | -displayName "iOS MAM / APP Policy" ` 6 | -periodOfflineBeforeAccessCheck (New-TimeSpan -Hours 12) ` 7 | -periodOnlineBeforeAccessCheck (New-TimeSpan -Minutes 30) ` 8 | -allowedInboundDataTransferSources managedApps ` 9 | -allowedOutboundDataTransferDestinations managedApps ` 10 | -allowedOutboundClipboardSharingLevel managedAppsWithPasteIn ` 11 | -organizationalCredentialsRequired $false ` 12 | -dataBackupBlocked $true ` 13 | -managedBrowserToOpenLinksRequired $false ` 14 | -deviceComplianceRequired $false ` 15 | -saveAsBlocked $true ` 16 | -periodOfflineBeforeWipeIsEnforced (New-TimeSpan -Days 30) ` 17 | -pinRequired $true ` 18 | -maximumPinRetries 5 ` 19 | -simplePinBlocked $false ` 20 | -minimumPinLength 4 ` 21 | -pinCharacterSet numeric ` 22 | -periodBeforePinReset (New-TimeSpan -Days 30) ` 23 | -allowedDataStorageLocations @("oneDriveForBusiness","sharePoint") ` 24 | -contactSyncBlocked $false ` 25 | -printBlocked $true ` 26 | -fingerprintBlocked $false ` 27 | -disableAppPinIfDevicePinIsSet $false 28 | 29 | # Get managed apps 30 | Write-Host "Getting managed apps..." 31 | $apps = Get-IntuneMobileApp -Expand assignments, categories | Where-Object { $_.'@odata.type' -like '#microsoft.graph.managed*' } 32 | 33 | # Get app identifiers 34 | Write-Host "Creating ManagedMobileApp objects from the retrieved iOS apps..." 35 | $appIdentifiers = $apps | ForEach-Object { 36 | if (-not [string]::IsNullOrEmpty($_.bundleId)) { 37 | New-ManagedMobileAppObject -mobileAppIdentifier (New-MobileAppIdentifierObject -iosMobileAppIdentifier -bundleId $_.bundleId) 38 | } 39 | } 40 | 41 | # Target apps 42 | Write-Host "Targeting the policy to the apps..." 43 | Invoke-IntuneAppProtectionPolicyIosTargetApp -iosManagedAppProtectionId $policy.id -apps $appIdentifiers 44 | 45 | # Get an AAD group 46 | Write-Host "Get security groups..." 47 | $groups = Get-AADGroup | Where-Object { $_.securityEnabled -eq $true } 48 | 49 | # Assign policy to groups 50 | Write-Host "Assign the policy to the groups..." 51 | $groups | ForEach-Object { 52 | Invoke-IntuneAppProtectionPolicyIosAssign -iosManagedAppProtectionId $policy.id -assignments @( 53 | New-TargetedManagedAppPolicyAssignmentObject ` 54 | -target (New-DeviceAndAppManagementAssignmentTargetObject -groupAssignmentTarget -groupId $_.id) 55 | ) 56 | } 57 | 58 | # Remove policy 59 | Write-Host "Deleting the policy..." 60 | $policy | Remove-IntuneAppProtectionPolicy -------------------------------------------------------------------------------- /Tests/DeviceAppManagement/MobileApps.ps1: -------------------------------------------------------------------------------- 1 | # POST some apps 2 | $numApps = 5 3 | Write-Host "Creating $numApps web apps..." 4 | $newApps = (1..$numApps | ForEach-Object { 5 | New-IntuneMobileApp -webApp -displayName 'My new app' -publisher 'Test web app' -appUrl 'https://www.bing.com' 6 | }) 7 | Start-Sleep 5 # Wait for 5 seconds for objects to be created in Intune 8 | 9 | # SEARCH all web apps and make sure these all exist 10 | Write-Host "Searching for all web apps and validating that the ones we created exist..." 11 | $searchedApps = Get-IntuneMobileApp -Filter "isof('microsoft.graph.webApp')" 12 | $ids = $newApps.id 13 | $filteredApps = $searchedApps | Where-Object { $ids -Contains $_.id } 14 | if ($filteredApps.Count -ne $newApps.Count) 15 | { 16 | throw "Failed to create some web apps" 17 | } 18 | 19 | # PATCH all apps 20 | $newAppName = 'Bing' 21 | Write-Host "Updating the name of the created web apps to '$newAppName'..." 22 | $newApps | Update-IntuneMobileApp -displayName $newAppName 23 | 24 | # Batch GET apps (with PowerShell pipeline) 25 | Write-Host "Retrieving the updated apps with the PowerShell pipeline..." 26 | $updatedApps = $newApps | Get-IntuneMobileApp -Select id, displayName 27 | $updatedApps | ForEach-Object { 28 | if ($_.displayName -ne $newAppName) { 29 | throw "Failed to update some web apps" 30 | } 31 | } 32 | 33 | # Batch DELETE apps (with PowerShell pipeline) 34 | Write-Host "Deleting the updated apps with the PowerShell pipeline..." 35 | $updatedApps | Remove-IntuneMobileApp 36 | 37 | # SEARCH all app categories 38 | Write-Host "Getting all app categories..." 39 | Get-IntuneMobileAppCategory | Out-Null 40 | 41 | # Create a custom category 42 | Write-Host "Creating a new app category..." 43 | $appCategory = New-IntuneMobileAppCategory -displayName 'Test Category' 44 | 45 | # SEARCH all apps 46 | Write-Host "Getting all apps..." 47 | $allApps = Get-IntuneMobileApp 48 | 49 | # Create a reference between an app and the custom category 50 | Write-Host "Creating a reference between an app and the new category..." 51 | $app = $allApps[0] 52 | $appCategory | New-IntuneMobileAppCategorySetReferenceSet -mobileAppId $app.id 53 | 54 | # Get the referenced categories on this app 55 | Write-Host "Getting the app with categories and assignments expanded..." 56 | $app = $app | Get-IntuneMobileApp -Expand assignments, categories 57 | 58 | # DELETE the reference 59 | Write-Host "Removing the reference between the app and the category" 60 | $appCategory | Remove-IntuneMobileAppCategorySetReferenceSet -mobileAppId $app.id 61 | 62 | # DELETE the category 63 | Write-Host "Deleting the category" 64 | $appCategory | Remove-IntuneMobileAppCategory 65 | 66 | # Run some paging commands 67 | Write-Host "Testing paging..." 68 | $firstPage = Get-IntuneMobileApp -Top ($allApps.Count / 3) 69 | $firstPage | Get-MSGraphNextPage | Out-Null 70 | $allPagedApps = $firstPage | Get-MSGraphAllPages 71 | if ($allPagedApps.Count -eq 0) { 72 | throw "Paging returned no apps" 73 | } 74 | Write-Host "Found $($allPagedApps.Count) apps" 75 | 76 | Write-Host "Testing the pipeline..." -NoNewline 77 | $success = $false 78 | try { 79 | Get-IntuneMobileApp | Select-Object -First 1 | Out-Null 80 | 81 | # The script won't reach this line if the pipeline is not ended gracefully 82 | $success = $true 83 | } finally { 84 | if ($success) { 85 | Write-Host "Done" 86 | } else { 87 | Write-Host "Failed" -ForegroundColor Red 88 | throw "Pipeline did not end gracefully" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Tests/DeviceManagement/DeviceCompliancePolicies.ps1: -------------------------------------------------------------------------------- 1 | # Create a compliance policy 2 | Write-Host 'Creating a compliance policy' 3 | $compliancePolicy = New-IntuneDeviceCompliancePolicy ` 4 | -iosCompliancePolicy ` 5 | -displayName "Chicago" ` 6 | -scheduledActionsForRule (New-DeviceComplianceScheduledActionForRuleObject ` 7 | -ruleName test ` 8 | -scheduledActionConfigurations (New-DeviceComplianceActionItemObject ` 9 | -gracePeriodHours 0 ` 10 | -actionType block ` 11 | -notificationTemplateId ""` 12 | )` 13 | ) 14 | 15 | # Remove the compliance policy 16 | Write-Host 'Deleting compliance policy' 17 | $compliancePolicy | Remove-IntuneDeviceCompliancePolicy -------------------------------------------------------------------------------- /Tests/DeviceManagement/DeviceManagement.ps1: -------------------------------------------------------------------------------- 1 | # IntuneGetEffectivePermission 2 | Write-Host "Testing IntuneGetEffectivePermission..." 3 | $permissions = Invoke-IntuneGetEffectivePermission -Scope * 4 | if ($permissions.resourceActions.allowedResourceActions[0] -ne '*') 5 | { 6 | throw "Expected to have admin permissions, but found '$permissions'" 7 | } -------------------------------------------------------------------------------- /Tests/GetDeviceAppMgmtTests.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory = $false)] 3 | [ValidateNotNullOrEmpty()] 4 | [string]$ModuleName="$env:moduleName", 5 | 6 | [Parameter(Mandatory = $false)] 7 | [ValidateNotNullOrEmpty()] 8 | [string]$OutputDirectory="$env:sdkDir", 9 | 10 | [Parameter(Mandatory = $false)] 11 | [ValidateNotNullOrEmpty()] 12 | [string]$AdminUPN="$env:adminUPN" 13 | ) 14 | 15 | # 16 | # Setup the test context 17 | # 18 | Import-Module $env:testDir\Set-IntuneContext.psm1 19 | Write-Output "Setting IntuneContext..." 20 | Set-IntuneContext -AdminUPN $AdminUPN 21 | 22 | # 23 | # Declare the cmdlets the test along with their inputs 24 | # TODO: Data drive the inputs 25 | # TODO: Auto-generate the list of cmdlets to test 26 | # 27 | $tests = @( 28 | # 29 | # DeviceAppManagement Singleton 30 | # 31 | {Get-IntuneDeviceAppManagement} 32 | # 33 | # AndroidManagedAppProtectionApps 34 | # 35 | {(Get-IntuneAppProtectionPolicyAndroid | Get-MSGraphAllPages) | Get-IntuneAppProtectionPolicyAndroidApp} 36 | # 37 | # DefaultManagedAppProtections 38 | # 39 | {Get-IntuneAppProtectionPolicyDefault} 40 | # 41 | # IodManagedAppProtections 42 | # 43 | {(Get-IntuneAppProtectionPolicyIos | Get-MSGraphAllPages)[0] | Get-IntuneAppProtectionPolicyIosApp} 44 | # 45 | # AmManagedEBooks 46 | # 47 | {(Get-IntuneManagedEBook| Get-MSGraphAllPages)[0] | Get-IntuneManagedEBookAssignment} 48 | {(Get-IntuneManagedEBook| Get-MSGraphAllPages)[0] | Get-IntuneManagedEBookDeviceState} 49 | {(Get-IntuneManagedEBook| Get-MSGraphAllPages)[0] | Get-IntuneManagedEBookInstallSummary} 50 | {$env:managedEBooksUserState = (Get-IntuneManagedEBook| Get-MSGraphAllPages)[0] | Get-IntuneManagedEBookUserStateSummary} 51 | {if ($env:managedEBooksUserState -ne $env:null) {(Get-IntuneManagedEBook| Get-MSGraphAllPages)[0] | Get-IntuneManagedEBookUserStateSummaryDeviceState}} 52 | # 53 | # mdmWindowsInformationProtectionPolicy 54 | # 55 | {$env:mdmWindowsInfoProtPolicy = (Get-IntuneMdmWindowsInformationProtectionPolicy | Get-MSGraphAllPages)} 56 | # 57 | # managedAppPolicies 58 | # 59 | {(Get-IntuneAppProtectionPolicy | Get-MSGraphAllPages)[0]} 60 | # 61 | # managedAppRegistrations 62 | # 63 | {(Get-IntuneManagedAppRegistration | Get-MSGraphAllPages)} 64 | # 65 | # AmIntuneManagedAppStatus 66 | # 67 | {(Get-IntuneManagedAppStatus | Get-MSGraphAllPages)[0]} 68 | # 69 | # AmIntuneMobileAppCategory 70 | # 71 | {Get-IntuneMobileAppCategory} 72 | # 73 | # AmIntuneMobileAppConfigurationPolicy 74 | # 75 | {$env:mobileAppConfig = (Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0]} 76 | {(Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0] | Get-IntuneMobileAppConfigurationPolicyAssignment} 77 | {(Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0] | Get-IntuneMobileAppConfigurationPolicyDeviceStatus} 78 | {(Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0] | Get-IntuneMobileAppConfigurationPolicyDeviceStatusSummary} 79 | {(Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0] | Get-IntuneMobileAppConfigurationPolicyUserStatus} 80 | {(Get-IntuneMobileAppConfigurationPolicy | Get-MSGraphAllPages)[0] | Get-IntuneMobileAppConfigurationPolicyUserStatusSummary} 81 | # 82 | # AmMobileApps 83 | # 84 | {(Get-IntuneMobileApp | Get-MSGraphAllPages).Where({$_.displayName -Match 'Intune Managed Browser'}) | Get-IntuneMobileAppAssignment} 85 | {(Get-IntuneMobileApp | Get-MSGraphAllPages).Where({$_.displayName -Match 'Intune Managed Browser'}) | Get-IntuneMobileAppCategorySet} 86 | # 87 | # AmTargetedAppConfigs 88 | # 89 | 90 | {(Get-IntuneAppConfigurationPolicyTargeted | Get-MSGraphAllPages) | Get-IntuneAppConfigurationPolicyTargetedApp} 91 | {(Get-IntuneAppConfigurationPolicyTargeted | Get-MSGraphAllPages) | Get-IntuneAppConfigurationPolicyTargetedAssignment} 92 | {(Get-IntuneAppConfigurationPolicyTargeted | Get-MSGraphAllPages) | Get-IntuneAppConfigurationPolicyTargetedDeploymentSummary} 93 | # 94 | # AmVppTokens 95 | # 96 | {(Get-IntuneVppToken | Get-MSGraphAllPages)} 97 | # 98 | # AmIntuneWindowsInformationProtectionPolicy 99 | # 100 | {$env:WinPP = (Get-IntuneWindowsInformationProtectionPolicy | Get-MSGraphAllPages)} 101 | #BUGBUG: Missing Route {if ($env:WinPP -ne $null) {(Get-IntuneWindowsInformationProtectionPolicy | Get-MSGraphAllPages) | Get-IntuneWindowsInformationProtectionPolicyAssignment}} 102 | #BUGBUG: Missing Route {if ($env:WinPP -ne $null) {(Get-IntuneWindowsInformationProtectionPolicy | Get-MSGraphAllPages) | Get-IntuneWindowsInformationProtectionPolicyExemptAppLockerFile}} 103 | #BUGBUG: Missing Route {if ($env:WinPP -ne $null) {(Get-IntuneWindowsInformationProtectionPolicy | Get-MSGraphAllPages) | Get-IntuneWindowsInformationProtectionPolicyProtectedAppLockerFile}} 104 | ) 105 | 106 | # 107 | # Run the tests 108 | # 109 | foreach ($test in $tests) 110 | { 111 | try 112 | { 113 | $output = Invoke-Command -scriptblock $test 114 | Write-Output "$test, $output" 115 | } 116 | catch 117 | { 118 | Throw "$test,$_" 119 | } 120 | } -------------------------------------------------------------------------------- /Tests/LobApps/UploadIOSLobApp.ps1: -------------------------------------------------------------------------------- 1 | $uploadedApp = (& $env:samplesDir\Apps\UploadIOSLobApp.ps1) 2 | $uploadedApp | Remove-IntuneMobileApp -------------------------------------------------------------------------------- /Tests/Misc/POC_AllOS_Reset_Cmdlets.ps1: -------------------------------------------------------------------------------- 1 |  2 | <# 3 | 4 | .COPYRIGHT 5 | Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. 6 | 7 | #> 8 | 9 | #################################################### 10 | 11 | #region PowerShell Module 12 | 13 | if(!(Get-Module Intune)){ 14 | 15 | $modulePath = "$env:sdkDir\$env:moduleName.psd1" 16 | if (-Not (Test-Path "$modulePath" -PathType Leaf)) 17 | { 18 | Write-Host "Install-Module $env:moduleName from PSGallery" 19 | Install-Module $env:moduleName -Force 20 | } 21 | else 22 | { 23 | Write-Host "Import-Module from $modulePath" 24 | Import-Module $modulePath 25 | } 26 | 27 | } 28 | 29 | #endregion 30 | 31 | #################################################### 32 | 33 | #region Authentication 34 | 35 | if(!(Connect-MSGraph)){ 36 | 37 | Connect-MSGraph 38 | 39 | } 40 | 41 | Write-Host 42 | 43 | #endregion 44 | 45 | #################################################### 46 | 47 | #region Script Output 48 | 49 | $Date = Get-Date 50 | $Project = "Intune" 51 | 52 | write-host 53 | write-host "------------------------------------------------------------------" -f yellow 54 | write-host "[$Project] Intune POC Windows 10 Modern Management Creation" -f yellow 55 | write-host "------------------------------------------------------------------" -f yellow 56 | write-host "[$Project] Script Started on $Date" 57 | write-host 58 | write-host "This script will reset the Intune Tenant to default configurations," 59 | write-host "with no policies, Intune Roles or Applications." 60 | write-host 61 | write-host "------------------------------------------------------------------" 62 | Write-Host 63 | 64 | #endregion 65 | 66 | #region Compliance Policies 67 | 68 | write-host "------------------------------------------------------------------" 69 | Write-Host 70 | 71 | Write-Host "Removing all Compliance Policies..." -f Cyan 72 | Write-Host 73 | 74 | $CPs = Get-IntuneDeviceCompliancePolicy 75 | 76 | foreach($CP in $CPs){ 77 | 78 | write-host "Removing Compliance Policy..." -f Yellow 79 | $CP.displayname 80 | 81 | Remove-IntuneDeviceCompliancePolicy -deviceCompliancePolicyId $CP.id 82 | Write-Host 83 | 84 | } 85 | 86 | #endregion 87 | 88 | #################################################### 89 | 90 | #region Configuration Policies 91 | 92 | write-host "------------------------------------------------------------------" 93 | Write-Host 94 | 95 | Write-Host "Removing all Configuration Policies..." -f Cyan 96 | 97 | Write-Host 98 | 99 | $IntuneDeviceConfigurationPolicyPs = Get-IntuneDeviceConfigurationPolicy 100 | 101 | foreach($IntuneDeviceConfigurationPolicyP in $IntuneDeviceConfigurationPolicyPs){ 102 | 103 | write-host "Removing Configuration Policy..." -f Yellow 104 | $IntuneDeviceConfigurationPolicyP.displayname 105 | 106 | Remove-IntuneDeviceConfigurationPolicy -deviceConfigurationId $IntuneDeviceConfigurationPolicyP.id 107 | Write-Host 108 | 109 | } 110 | 111 | #endregion 112 | 113 | #################################################### 114 | 115 | #region App Protection Policies 116 | 117 | write-host "------------------------------------------------------------------" 118 | Write-Host 119 | 120 | Write-Host "Removing all App Protection Policies..." -f Cyan 121 | 122 | Write-Host 123 | 124 | $MAMs = Get-IntuneAppProtectionPolicy 125 | 126 | foreach($MAM in $MAMs){ 127 | 128 | write-host "Removing Managed App Policy..." -f Yellow 129 | $MAM.displayname + ": " + $MAM.'@odata.type' 130 | $MAM.id 131 | 132 | Remove-IntuneAppProtectionPolicy -managedAppPolicyId $MAM.id 133 | Write-Host 134 | 135 | } 136 | 137 | #endregion 138 | 139 | #################################################### -------------------------------------------------------------------------------- /Tests/Set-IntuneContext.psm1: -------------------------------------------------------------------------------- 1 | # 2 | # Set-IntuneContext: Sets up the context for running the tests 3 | # 4 | function Set-IntuneContext 5 | { 6 | [CmdletBinding()] 7 | param( 8 | [Parameter(Mandatory = $false)] 9 | [ValidateNotNullOrEmpty()] 10 | [string]$ModuleName="$env:moduleName", 11 | 12 | [Parameter(Mandatory = $false)] 13 | [ValidateNotNullOrEmpty()] 14 | [string]$OutputDirectory="$env:sdkDir", 15 | 16 | [Parameter(Mandatory = $false)] 17 | [ValidateNotNullOrEmpty()] 18 | [string]$AdminUPN="$env:adminUPN" 19 | ) 20 | 21 | # 22 | # Import the Intune PowerShell SDK Module if necessary 23 | # 24 | if (!(Get-Module $ModuleName)) 25 | { 26 | Write-Host "Import-Module from $modulePath" 27 | Import-Module $modulePath 28 | } 29 | 30 | # 31 | # Connect to MSGraph if necessary 32 | # 33 | try 34 | { 35 | $msGraphMetaData = Get-MSGraphMetadata 36 | } 37 | catch 38 | { 39 | Write-Output "Connect with MSGraph first." 40 | $adminPwd=Read-Host -AsSecureString -Prompt "Enter pwd for $env:adminUPN" 41 | $creds = New-Object System.Management.Automation.PSCredential ($AdminUPN, $adminPwd) 42 | $connection = Connect-MSGraph -PSCredential $creds 43 | } 44 | } 45 | Export-ModuleMember -Function Set-IntuneContext -------------------------------------------------------------------------------- /init.cmd: -------------------------------------------------------------------------------- 1 | @echo OFF 2 | setlocal enableDelayedExpansion 3 | 4 | echo Initializing repository in a new PowerShell context (type 'exit' to return to this context) 5 | echo. 6 | 7 | powershell -NoExit ./Scripts/init.ps1 -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Behaviors/Object Factories/1_OdcmModelToObjectFactoriesConversionBehavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Behaviors 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Management.Automation; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 10 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 11 | using Vipr.Core.CodeModel; 12 | 13 | public static class OdcmModelToObjectFactoriesConversionBehavior 14 | { 15 | public static IEnumerable CreateObjectFactories(this OdcmModel model, string pathPrefix = "") 16 | { 17 | if (model == null) 18 | { 19 | throw new ArgumentNullException(nameof(model)); 20 | } 21 | if (pathPrefix == null) 22 | { 23 | throw new ArgumentNullException(nameof(pathPrefix)); 24 | } 25 | 26 | // Iterate over each namespace in the model except for the "Edm" namespace 27 | foreach (OdcmNamespace @namespace in model.Namespaces.Where(n => n.Name != "Edm")) 28 | { 29 | // Iterate over each type in the namespace 30 | foreach (OdcmClass @class in @namespace.Classes.Where(c => 31 | // Make sure we ignore the "Service" entity (i.e. the root) 32 | c.Kind != OdcmClassKind.Service 33 | // Ignore any types that inherit from other custom types 34 | && (c.Base == null || c.Base.Namespace.Name == "Edm" || c.Base.FullName.Equals("microsoft.graph.entity", StringComparison.OrdinalIgnoreCase)))) 35 | { 36 | // Convert the ODCM class into an ObjectFactoryCmdlet (each derived type will be represented by a parameter set) 37 | ObjectFactoryCmdlet objectFactory = @class.ToObjectFactory(pathPrefix); 38 | 39 | yield return objectFactory; 40 | } 41 | } 42 | } 43 | 44 | private static ObjectFactoryCmdlet ToObjectFactory(this OdcmClass @class, string pathPrefix) 45 | { 46 | if (@class == null) 47 | { 48 | throw new ArgumentNullException(nameof(@class)); 49 | } 50 | if (pathPrefix == null) 51 | { 52 | throw new ArgumentNullException(nameof(pathPrefix)); 53 | } 54 | 55 | // Create the cmdlet 56 | ObjectFactoryCmdlet cmdlet = new ObjectFactoryCmdlet(@class.GetObjectFactoryCmdletName()) 57 | { 58 | RelativeFilePath = $"{pathPrefix.TrimEnd('\\')}\\{@class.GetObjectFactoryCmdletName().Noun}", 59 | ResourceTypeFullName = @class.FullName, 60 | ImpactLevel = ConfirmImpact.None, 61 | Documentation = new CmdletDocumentation() 62 | { 63 | Synopsis = $"Creates a new object which represents a \"{@class.FullName}\" (or one of its derived types).", 64 | Descriptions = new string[] 65 | { 66 | $"Creates a new object which represents a \"{@class.FullName}\" (or one of its derived types).", 67 | @class.Description, 68 | @class.LongDescription, 69 | }, 70 | }, 71 | }; 72 | 73 | // Add the parameters for the entity's properties - there should be 1 parameter set per derived type 74 | cmdlet.AddParametersForEntityProperties( 75 | @class, 76 | property => property.IsComputed() || property.IsImmutable(), 77 | sharedParameterSetName: null, 78 | addSwitchParameters: true, 79 | markAsPowerShellParameter: true, 80 | allowPipelineInputByName: false, 81 | setBaseTypeParameterSetAsDefault: true); 82 | 83 | return cmdlet; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Behaviors/Object Factories/2_ObjectFactoryToCSharpFileConversionBehavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Behaviors 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 8 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 9 | using Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets; 10 | 11 | public static class ObjectFactoryToCSharpFileConversionBehavior 12 | { 13 | /// 14 | /// Converts an ObjectFactoryCmdlet into a CSharpFile. 15 | /// 16 | /// The object factory cmdlet 17 | /// The converted CSharpFile. 18 | public static CSharpFile ToCSharpFile(this ObjectFactoryCmdlet cmdlet) 19 | { 20 | if (cmdlet == null) 21 | { 22 | throw new ArgumentNullException(nameof(cmdlet)); 23 | } 24 | 25 | // Get the C# file details 26 | CSharpFile cSharpFile = new CSharpFile(cmdlet.RelativeFilePath + ".cs") 27 | { 28 | Usings = CSharpFileHelper.GetDefaultUsings(), 29 | Classes = cmdlet.ToCSharpClass().SingleObjectAsEnumerable(), 30 | }; 31 | 32 | return cSharpFile; 33 | } 34 | 35 | #region Helpers 36 | 37 | private static CSharpClass ToCSharpClass(this ObjectFactoryCmdlet cmdlet) 38 | { 39 | if (cmdlet == null) 40 | { 41 | throw new ArgumentNullException(nameof(cmdlet)); 42 | } 43 | 44 | // Create the result object 45 | CSharpClass result = new CSharpClass($"{cmdlet.Name.Verb}_{cmdlet.Name.Noun}") 46 | { 47 | DocumentationComment = cmdlet.Documentation.ToCSharpDocumentationComment(), 48 | AccessModifier = CSharpAccessModifier.Public, 49 | BaseType = nameof(ObjectFactoryCmdletBase), 50 | Attributes = cmdlet.CreateAttributes(), 51 | Properties = cmdlet.CreateProperties(), 52 | }; 53 | 54 | return result; 55 | } 56 | 57 | private static IEnumerable CreateAttributes(this ObjectFactoryCmdlet cmdlet) 58 | { 59 | if (cmdlet == null) 60 | { 61 | throw new ArgumentNullException(nameof(cmdlet)); 62 | } 63 | 64 | // Cmdlet attribute 65 | yield return CSharpClassAttributeHelper.CreateCmdletAttribute(cmdlet.Name, cmdlet.ImpactLevel, cmdlet.DefaultParameterSetName); 66 | 67 | // ODataType attribute 68 | yield return CSharpClassAttributeHelper.CreateODataTypeAttribute(cmdlet.ResourceTypeFullName); 69 | } 70 | 71 | #endregion Helpers 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Behaviors/SDK Operations/3_ResourceToCSharpFileConversionBehavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Behaviors 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 10 | 11 | /// 12 | /// The behavior to convert a Resource into a TextFile. 13 | /// 14 | public static class ResourceToCSharpFileConversionBehavior 15 | { 16 | /// 17 | /// Converts a Resource into a CSharpFile. 18 | /// 19 | /// The resource 20 | /// The converted CSharpFile. 21 | public static CSharpFile ToCSharpFile(this Resource resource) 22 | { 23 | if (resource == null) 24 | { 25 | throw new ArgumentNullException(nameof(resource)); 26 | } 27 | 28 | // Get the C# file details 29 | CSharpFile cSharpFile = new CSharpFile(resource.RelativeFilePath + ".cs") 30 | { 31 | Usings = CSharpFileHelper.GetDefaultUsings(), 32 | Classes = resource.CreateClasses(), 33 | }; 34 | 35 | return cSharpFile; 36 | } 37 | 38 | private static IEnumerable CreateClasses(this Resource resource) 39 | { 40 | if (resource == null) 41 | { 42 | throw new ArgumentNullException(nameof(resource)); 43 | } 44 | 45 | // Convert each cmdlet to a C# class 46 | foreach (OperationCmdlet cmdlet in resource.Cmdlets) 47 | { 48 | yield return cmdlet.ToCSharpClass(); 49 | } 50 | } 51 | 52 | private static CSharpClass ToCSharpClass(this OperationCmdlet cmdlet) 53 | { 54 | if (cmdlet == null) 55 | { 56 | throw new ArgumentNullException(nameof(cmdlet)); 57 | } 58 | 59 | // Create the result object 60 | CSharpClass result = new CSharpClass($"{cmdlet.Name.Verb}_{cmdlet.Name.Noun}") 61 | { 62 | DocumentationComment = cmdlet.Documentation.ToCSharpDocumentationComment(), 63 | AccessModifier = CSharpAccessModifier.Public, 64 | BaseType = cmdlet.OperationType.ToCSharpString(), 65 | Attributes = cmdlet.CreateAttributes(), 66 | Properties = cmdlet.CreateProperties(), 67 | Methods = cmdlet.CreateMethods(), 68 | }; 69 | 70 | return result; 71 | } 72 | 73 | private static IEnumerable CreateAttributes(this OperationCmdlet cmdlet) 74 | { 75 | if (cmdlet == null) 76 | { 77 | throw new ArgumentNullException(nameof(cmdlet)); 78 | } 79 | 80 | // Cmdlet attribute 81 | yield return CSharpClassAttributeHelper.CreateCmdletAttribute(cmdlet.Name, cmdlet.ImpactLevel, cmdlet.DefaultParameterSetName); 82 | 83 | // ODataType attribute 84 | yield return CSharpClassAttributeHelper.CreateODataTypeAttribute(cmdlet.ResourceTypeFullName, cmdlet.ResourceSubTypeFullNames); 85 | 86 | // ResourceTypePropertyName attribute 87 | yield return CSharpClassAttributeHelper.CreateResourceTypePropertyNameAttribute(cmdlet.ResourceTypePropertyName); 88 | 89 | // ResourceReference attribute 90 | if (cmdlet.IsReferenceable) 91 | { 92 | yield return CSharpClassAttributeHelper.CreateResourceReferenceAttribute(); 93 | } 94 | 95 | // Alias attribute 96 | if (cmdlet.Aliases != null && cmdlet.Aliases.Any()) 97 | { 98 | yield return CSharpClassAttributeHelper.CreateAliasAttribute(cmdlet.Aliases); 99 | } 100 | } 101 | 102 | private static IEnumerable CreateMethods(this OperationCmdlet cmdlet) 103 | { 104 | if (cmdlet == null) 105 | { 106 | throw new ArgumentNullException(nameof(cmdlet)); 107 | } 108 | 109 | // "GetHttpMethod()" method override 110 | if (cmdlet.HttpMethod != null) 111 | { 112 | yield return CSharpMethodHelper.CreateGetHttpMethodMethod(cmdlet.HttpMethod); 113 | } 114 | 115 | // Determine whether this cmdlet calls a function 116 | bool isFunction = 117 | cmdlet.OperationType == CmdletOperationType.FunctionReturningCollection 118 | || cmdlet.OperationType == CmdletOperationType.FunctionReturningEntity; 119 | 120 | // "GetResourcePath()" method override 121 | yield return CSharpMethodHelper.CreateGetResourcePathMethod(cmdlet.CallUrl, isFunction); 122 | 123 | // Determine whether this cmdlet creates a reference (i.e. is a POST/PUT "$ref" call) 124 | if (cmdlet.OperationType == CmdletOperationType.PostRefToCollection) 125 | { 126 | // "GetContent()" method override 127 | yield return CSharpMethodHelper.CreateGetContentMethodForCreatingReference(cmdlet.IdParameter.Name); 128 | } 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Behaviors/SDK Operations/4_CSharpFileToTextFileConversionBehavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Behaviors 4 | { 5 | using System; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 7 | using Vipr.Core; 8 | 9 | /// 10 | /// The behavior to convert a C# file into a TextFile. 11 | /// 12 | public static class CSharpFileToTextFileConversionBehavior 13 | { 14 | /// 15 | /// Converts a CSharpFile into a TextFile. 16 | /// 17 | /// The CSharpFile 18 | /// The generated TextFile. 19 | public static TextFile ToTextFile(this CSharpFile cSharpFile) 20 | { 21 | if (cSharpFile == null) 22 | { 23 | throw new ArgumentNullException(nameof(cSharpFile)); 24 | } 25 | 26 | // Generate the output 27 | string fileContents = cSharpFile.ToString(); 28 | 29 | // Create the TextFile object which will be sent back to Vipr 30 | TextFile textFile = new TextFile(cSharpFile.RelativeFilePath, fileContents); 31 | 32 | return textFile; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpAccessModifier.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | public enum CSharpAccessModifier 6 | { 7 | Public, 8 | Protected, 9 | Internal, 10 | Private, 11 | } 12 | } -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpArgument.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | 7 | public class CSharpArgument 8 | { 9 | public string Name { get; } 10 | public Type Type { get; } 11 | 12 | public CSharpArgument(string name, Type type) 13 | { 14 | if (string.IsNullOrWhiteSpace(name)) 15 | { 16 | throw new ArgumentNullException(nameof(name)); 17 | } 18 | 19 | this.Name = name; 20 | this.Type = type ?? throw new ArgumentNullException(nameof(type)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 10 | 11 | public class CSharpAttribute 12 | { 13 | public string Name { get; } 14 | 15 | public bool MultiLineArguments { get; set; } = false; 16 | 17 | private IEnumerable _arguments = new HashSet(); 18 | public IEnumerable Arguments 19 | { 20 | get => this._arguments; 21 | set => this._arguments = new HashSet(value ?? throw new ArgumentNullException(nameof(value))); 22 | } 23 | 24 | public CSharpAttribute(string name, params string[] arguments) : this(name, arguments.AsEnumerable()) { } 25 | 26 | public CSharpAttribute(string name, IEnumerable arguments) 27 | { 28 | if (string.IsNullOrWhiteSpace(name)) 29 | { 30 | throw new ArgumentException("C# Property name cannot be null or whitespace", nameof(name)); 31 | } 32 | 33 | this.Name = name; 34 | this.Arguments = arguments ?? throw new ArgumentNullException(nameof(arguments)); 35 | } 36 | 37 | public override string ToString() 38 | { 39 | string attributeName = this.Name.EndsWith("Attribute") 40 | ? this.Name.Substring(0, this.Name.LastIndexOf("Attribute")) 41 | : this.Name; 42 | 43 | string argumentString; 44 | if (this.Arguments.Any()) 45 | { 46 | if (this.MultiLineArguments) 47 | { 48 | StringBuilder stringBuilder = new StringBuilder(); 49 | stringBuilder.AppendLine(); 50 | string lastArgument = this.Arguments.Last(); 51 | foreach (string argument in this.Arguments) 52 | { 53 | if (argument != lastArgument) 54 | { 55 | stringBuilder.AppendLine($"{argument},".Indent()); 56 | } 57 | else 58 | { 59 | stringBuilder.AppendLine(argument.Indent()); 60 | } 61 | } 62 | 63 | argumentString = $"({stringBuilder.ToString()})"; 64 | } 65 | else 66 | { 67 | argumentString = $"({string.Join(", ", this.Arguments)})"; 68 | } 69 | } 70 | else 71 | { 72 | argumentString = string.Empty; 73 | } 74 | 75 | return $"[{attributeName}{argumentString}]"; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpDocumentationComment.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System.Text; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 7 | 8 | /// 9 | /// Represents a comment in C#. 10 | /// 11 | public class CSharpDocumentationComment 12 | { 13 | private const string LinePrefix = @"/// "; 14 | 15 | /// 16 | /// The summary section. 17 | /// 18 | public string Summary { get; set; } 19 | 20 | /// 21 | /// The notes. 22 | /// 23 | public string RawNotes { get; set; } 24 | 25 | public override string ToString() 26 | { 27 | StringBuilder resultBuilder = new StringBuilder(); 28 | 29 | // Summary 30 | if (this.Summary != null) 31 | { 32 | resultBuilder.AppendLine(LinePrefix + @""); 33 | resultBuilder.AppendLine(CSharpDocumentationComment.MakeCommentString(this.Summary.Indent())); 34 | resultBuilder.AppendLine(LinePrefix + @""); 35 | } 36 | 37 | // Misc 38 | if (this.RawNotes != null) 39 | { 40 | resultBuilder.AppendLine(CSharpDocumentationComment.MakeCommentString(this.RawNotes)); 41 | } 42 | 43 | return resultBuilder.ToString().Trim(); 44 | } 45 | 46 | private static string MakeCommentString(string str) 47 | { 48 | return str.Indent(indentToken: LinePrefix); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpFile.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 10 | 11 | public class CSharpFile 12 | { 13 | public string RelativeFilePath { get; } 14 | 15 | private string _namespace = CSharpFileHelper.GetDefaultNamespace(); 16 | public string Namespace 17 | { 18 | get => this._namespace; 19 | set 20 | { 21 | if (string.IsNullOrWhiteSpace(value)) 22 | { 23 | throw new ArgumentException("Namespace name cannot be null or whitespace", nameof(value)); 24 | } 25 | 26 | this._namespace = value; 27 | } 28 | } 29 | 30 | private IEnumerable _usings = new HashSet(); 31 | public IEnumerable Usings 32 | { 33 | get => this._usings; 34 | set => this._usings = new HashSet(value ?? throw new ArgumentNullException(nameof(value))); 35 | } 36 | 37 | //TODO: Create a special type for IEnumerable so validation can be enforced 38 | private IEnumerable _classes = new List(); 39 | public IEnumerable Classes 40 | { 41 | get => this._classes; 42 | set => this._classes = value ?? throw new ArgumentNullException(nameof(value)); 43 | } 44 | 45 | public CSharpFile(string relativeFilePath) 46 | { 47 | if (string.IsNullOrWhiteSpace(relativeFilePath)) 48 | { 49 | throw new ArgumentException("Relative file path cannot be null or whitespace", nameof(relativeFilePath)); 50 | } 51 | 52 | this.RelativeFilePath = relativeFilePath; 53 | } 54 | 55 | public override string ToString() 56 | { 57 | StringBuilder resultBuilder = new StringBuilder(); 58 | 59 | // License header 60 | resultBuilder.AppendLine(CSharpFileHelper.GetLicenseHeader()); 61 | resultBuilder.AppendLine(); 62 | 63 | // Namespace 64 | resultBuilder.AppendLine($"namespace {this.Namespace}"); 65 | 66 | // Start body 67 | resultBuilder.AppendLine("{"); 68 | 69 | // Usings 70 | foreach (string @using in this.Usings) 71 | { 72 | resultBuilder.AppendLine($"using {@using};".Indent()); 73 | } 74 | 75 | if (this.Usings.Any() && this.Classes.Any()) 76 | { 77 | resultBuilder.AppendLine(); 78 | } 79 | 80 | // Classes 81 | bool isFirst = true; 82 | foreach (CSharpClass @class in this.Classes) 83 | { 84 | if (isFirst) 85 | { 86 | isFirst = false; 87 | } 88 | else 89 | { 90 | resultBuilder.AppendLine(); 91 | } 92 | 93 | resultBuilder.AppendLine(@class.ToString().Indent()); 94 | } 95 | 96 | // End body 97 | resultBuilder.AppendLine("}"); 98 | 99 | // Compile and return result 100 | string result = resultBuilder.ToString().Trim(); 101 | return result; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpMethod.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 10 | 11 | public class CSharpMethod 12 | { 13 | public string Name { get; } 14 | 15 | public CSharpAccessModifier AccessModifier { get; set; } = CSharpAccessModifier.Public; 16 | 17 | public bool Override { get; set; } = false; 18 | 19 | public Type ReturnType { get; } 20 | 21 | //TODO: Create a special type for IEnumerable so validation can be enforced 22 | private IEnumerable _arguments = new List(); 23 | public IEnumerable Arguments 24 | { 25 | get => this._arguments; 26 | set => this._arguments = value ?? throw new ArgumentNullException(nameof(value)); 27 | } 28 | 29 | public string Body { get; } 30 | 31 | public CSharpMethod(string name, Type returnType, string body) 32 | { 33 | if (string.IsNullOrWhiteSpace(name)) 34 | { 35 | throw new ArgumentNullException(nameof(name)); 36 | } 37 | 38 | this.ReturnType = returnType ?? throw new ArgumentNullException(nameof(returnType)); 39 | this.Body = body ?? throw new ArgumentNullException(nameof(body)); 40 | this.Name = name; 41 | } 42 | 43 | public string GetMethodSignature() 44 | { 45 | string beforeName = $"{this.AccessModifier.ToCSharpString()} {(this.Override ? "override " : string.Empty)}{this.ReturnType.FullName}"; 46 | string arguments = string.Join(", ", this.Arguments.Select(arg => arg.ToString())); 47 | string result = $"{beforeName} {this.Name}({arguments})"; 48 | 49 | return result; 50 | } 51 | 52 | public override string ToString() 53 | { 54 | StringBuilder resultBuilder = new StringBuilder(); 55 | 56 | // Method signature (access modifiers, 57 | resultBuilder.AppendLine(this.GetMethodSignature()); 58 | resultBuilder.AppendLine("{"); 59 | resultBuilder.AppendLine(this.Body.Indent()); 60 | resultBuilder.AppendLine("}"); 61 | 62 | string result = resultBuilder.ToString().Trim(); 63 | 64 | return result; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/CSharpAbstractions/CSharpProperty.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Text; 8 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils; 9 | 10 | public class CSharpProperty 11 | { 12 | public string Name { get; } 13 | 14 | public Type Type { get; } 15 | 16 | public CSharpAccessModifier AccessModifier { get; set; } = CSharpAccessModifier.Public; 17 | 18 | private IEnumerable _attributes = new List(); 19 | public IEnumerable Attributes 20 | { 21 | get => this._attributes; 22 | set => this._attributes = value ?? throw new ArgumentNullException(nameof(value)); 23 | } 24 | 25 | public CSharpDocumentationComment DocumentationComment { get; set; } 26 | 27 | public CSharpProperty(string name, Type type) 28 | { 29 | if (string.IsNullOrWhiteSpace(name)) 30 | { 31 | throw new ArgumentException("C# Property name cannot be null or whitespace", nameof(name)); 32 | } 33 | 34 | this.Type = type ?? throw new ArgumentNullException(nameof(type)); 35 | this.Name = name; 36 | } 37 | 38 | public override string ToString() 39 | { 40 | // Create a string builder 41 | StringBuilder resultBuilder = new StringBuilder(); 42 | 43 | // Add the documentation comment 44 | if (this.DocumentationComment != null) 45 | { 46 | resultBuilder.AppendLine(this.DocumentationComment.ToString()); 47 | } 48 | 49 | // Loop through attributes 50 | foreach (CSharpAttribute attribute in this.Attributes) 51 | { 52 | resultBuilder.AppendLine(attribute.ToString()); 53 | } 54 | 55 | // Add the property definition itself 56 | resultBuilder.AppendLine($"{this.AccessModifier.ToCSharpString()} {this.Type.FullName} {this.Name.SanitizeIdentifier()} {{ get; set; }}"); 57 | 58 | // Compile the string 59 | string result = resultBuilder.ToString().Trim(); 60 | 61 | return result; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/OdcmNode.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using Vipr.Core.CodeModel; 7 | 8 | /// 9 | /// Represents the final segment of the path to an ODCM property from the entity container. 10 | /// Use the property to access the previous segment. 11 | /// 12 | public class OdcmNode 13 | { 14 | /// 15 | /// The parent node. 16 | /// 17 | public OdcmNode Parent { get; } 18 | 19 | /// 20 | /// The ODCM property that this node represents. 21 | /// 22 | public OdcmProperty OdcmProperty { get; } 23 | 24 | /// 25 | /// Creates an ODCM node with no parent. 26 | /// 27 | /// The ODCM property that this node represents 28 | public OdcmNode(OdcmProperty property) 29 | { 30 | this.OdcmProperty = property ?? throw new ArgumentNullException(nameof(property)); 31 | } 32 | 33 | /// 34 | /// Creates an OdcmNode. 35 | /// 36 | /// The parent node 37 | /// The ODCM object which this node represents 38 | private OdcmNode(OdcmNode parent, OdcmProperty odcmProperty) 39 | { 40 | this.Parent = parent ?? throw new ArgumentNullException(nameof(parent)); 41 | this.OdcmProperty = odcmProperty ?? throw new ArgumentNullException(nameof(odcmProperty)); 42 | } 43 | 44 | /// 45 | /// Creates a child for this node. 46 | /// 47 | /// The ODCM object to be used as the child 48 | /// The created child node. 49 | public OdcmNode CreateChildNode(OdcmProperty childData) 50 | { 51 | if (childData == null) 52 | { 53 | throw new ArgumentNullException(nameof(childData)); 54 | } 55 | 56 | OdcmNode childNode = new OdcmNode(this, childData); 57 | 58 | return childNode; 59 | } 60 | 61 | /// 62 | /// Gets the hash code for the ODCM object in this node. 63 | /// 64 | /// The hash code for the ODCM object. 65 | public override int GetHashCode() 66 | { 67 | return OdcmProperty == null ? 0 : OdcmProperty.GetHashCode(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/Cmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using PS = System.Management.Automation; 8 | 9 | /// 10 | /// An abstract representation of a PowerShell cmdlet. 11 | /// 12 | public abstract class Cmdlet 13 | { 14 | /// 15 | /// The name of this cmdlet. 16 | /// 17 | public CmdletName Name { get; } 18 | 19 | /// 20 | /// Aliases for the cmdlet. 21 | /// 22 | public IList Aliases { get; } = new List(); 23 | 24 | /// 25 | /// The name of the default parameter set. If this is null, PowerShell's default will be used. 26 | /// 27 | public string DefaultParameterSetName { get; set; } 28 | 29 | /// 30 | /// The impact level of this cmdlet. 31 | /// This corresponds to the "ConfirmImpact" enum in the System.Management.Automation assembly. 32 | /// 33 | public PS.ConfirmImpact ImpactLevel { get; set; } 34 | 35 | /// 36 | /// The information that will appear when retrieving the documentation for this cmdlet. 37 | /// 38 | public CmdletDocumentation Documentation { get; set; } 39 | 40 | /// 41 | /// This cmdlet's parameter sets (including the default parameter set). 42 | /// 43 | public CmdletParameterSets ParameterSets { get; } = new CmdletParameterSets(); 44 | 45 | /// 46 | /// Convenience property for getting the default parameter set. 47 | /// 48 | public CmdletParameterSet DefaultParameterSet => ParameterSets.DefaultParameterSet; 49 | 50 | /// 51 | /// Creates a new representation of a Graph SDK cmdlet. 52 | /// 53 | /// The name of the cmdlet 54 | public Cmdlet(CmdletName cmdletName) 55 | { 56 | this.Name = cmdletName ?? throw new ArgumentNullException(nameof(cmdletName)); 57 | } 58 | 59 | /// 60 | /// Creates a new representation of a Graph SDK cmdlet. 61 | /// 62 | /// The verb part of the cmdlet's name 63 | /// The noun part of the cmdlet's name 64 | public Cmdlet(string verb, string noun) 65 | { 66 | this.Name = new CmdletName(verb, noun); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/CmdletDocumentation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | 8 | public class CmdletDocumentation 9 | { 10 | /// 11 | /// The synopsis that will appear when looking at the help documentation for this cmdlet. 12 | /// 13 | public string Synopsis { get; set; } 14 | 15 | /// 16 | /// The descriptions that will appear when looking at the help documentation for this cmdlet. 17 | /// 18 | /// Each description will be in it's own paragraph. 19 | /// 20 | public IEnumerable Descriptions { get; set; } 21 | 22 | /// 23 | /// The URLs that will appear when looking at the help documentation for this cmdlet. 24 | /// 25 | public IEnumerable Links { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/CmdletDocumentationLink.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | 7 | public class CmdletDocumentationLink 8 | { 9 | /// 10 | /// A descriptive name for the link. 11 | /// 12 | public string Name { get; } 13 | 14 | /// 15 | /// The URL. 16 | /// 17 | public string Url { get; } 18 | 19 | public CmdletDocumentationLink(string name, string url) 20 | { 21 | this.Name = name ?? throw new ArgumentNullException(nameof(name)); 22 | this.Url = url ?? throw new ArgumentNullException(nameof(url)); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/CmdletName.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System; 6 | 7 | /// 8 | /// Represents a PowerShell cmdlet's name. 9 | /// 10 | public class CmdletName 11 | { 12 | public string Verb { get; } 13 | public string Noun { get; } 14 | 15 | private readonly string _compiledString; 16 | 17 | public CmdletName(string verb, string noun) 18 | { 19 | this.Verb = verb ?? throw new ArgumentNullException(nameof(verb)); 20 | this.Noun = noun ?? throw new ArgumentNullException(nameof(noun)); 21 | 22 | this._compiledString = $"{this.Verb}-{this.Noun}"; 23 | } 24 | 25 | /// 26 | /// Safely parses a string cmdlet name into a object. 27 | /// 28 | /// The string cmdlet name to parse 29 | /// The CmdletName object 30 | /// True if the string cmdlet name could be parsed, otherwise false. 31 | public static bool TryParse(string stringCmdletName, out CmdletName parsedName) 32 | { 33 | if (!string.IsNullOrWhiteSpace(stringCmdletName)) 34 | { 35 | string[] splitString = stringCmdletName.Split('-'); 36 | if (splitString.Length == 2) 37 | { 38 | string verb = splitString[0]; 39 | string noun = splitString[1]; 40 | 41 | if (!string.IsNullOrWhiteSpace(verb) && !string.IsNullOrWhiteSpace(noun)) 42 | { 43 | parsedName = new CmdletName(verb, noun); 44 | return true; 45 | } 46 | } 47 | } 48 | 49 | parsedName = null; 50 | return false; 51 | } 52 | 53 | /// 54 | /// Outputs the cmdlet name as a string in the format "VerbName-NounName". 55 | /// 56 | /// The string cmdlet name 57 | public override string ToString() 58 | { 59 | return this._compiledString; 60 | } 61 | 62 | public override bool Equals(object obj) 63 | { 64 | if (obj != null 65 | && obj is CmdletName other 66 | && other.ToString() == this.ToString()) 67 | { 68 | return true; 69 | } 70 | 71 | return false; 72 | } 73 | 74 | public override int GetHashCode() 75 | { 76 | return this.ToString().GetHashCode(); 77 | } 78 | 79 | public static bool operator ==(CmdletName name1, CmdletName name2) 80 | { 81 | if (name1 is null && name2 is null) 82 | { 83 | return true; 84 | } 85 | else if (!(name1 is null) && !(name2 is null) 86 | && name1.ToString() == name2.ToString()) 87 | { 88 | return true; 89 | } 90 | else 91 | { 92 | return false; 93 | } 94 | } 95 | 96 | public static bool operator !=(CmdletName name1, CmdletName name2) 97 | { 98 | return !(name1 == name2); 99 | } 100 | 101 | public static bool operator ==(CmdletName name1, string name2) 102 | { 103 | if (name1 is null && name2 is null) 104 | { 105 | return true; 106 | } 107 | else if (!(name1 is null) && !(name2 is null) 108 | && name1.ToString() == name2) 109 | { 110 | return true; 111 | } 112 | else 113 | { 114 | return false; 115 | } 116 | } 117 | 118 | public static bool operator !=(CmdletName name1, string name2) 119 | { 120 | return !(name1 == name2); 121 | } 122 | 123 | public static bool operator ==(string name1, CmdletName name2) 124 | { 125 | return name2 == name1; 126 | } 127 | 128 | public static bool operator !=(string name1, CmdletName name2) 129 | { 130 | return !(name1 == name2); 131 | } 132 | 133 | public static implicit operator string(CmdletName name) 134 | { 135 | if (name == null) 136 | { 137 | throw new ArgumentNullException(nameof(name)); 138 | } 139 | 140 | return name.ToString(); 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/CmdletOperationTypes.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | public enum CmdletOperationType 6 | { 7 | Get, 8 | GetOrSearch, 9 | GetStream, 10 | Post, 11 | PutRefToSingleEntity, 12 | PostRefToCollection, 13 | UpdateStream, 14 | Patch, 15 | Delete, 16 | FunctionReturningEntity, 17 | FunctionReturningCollection, 18 | Action, 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/CmdletParameterDocumentation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System.Collections.Generic; 6 | 7 | public class CmdletParameterDocumentation 8 | { 9 | /// 10 | /// The descriptions that appear when looking at the help documentation for this cmdlet. 11 | /// 12 | /// Each description will be in it's own paragraph. 13 | /// 14 | public IEnumerable Descriptions { get; set; } 15 | 16 | /// 17 | /// The set of valid values (e.g. for an enum). 18 | /// 19 | public IEnumerable ValidValues { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/ObjectFactoryCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | public class ObjectFactoryCmdlet : Cmdlet 6 | { 7 | public string RelativeFilePath { get; set; } 8 | 9 | public string ResourceTypeFullName { get; set; } 10 | 11 | public ObjectFactoryCmdlet(string verb, string noun) : base(verb, noun) { } 12 | 13 | public ObjectFactoryCmdlet(CmdletName cmdletName) : base(cmdletName) { } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Generator/Models/PowerShellAbstractions/OperationCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models 4 | { 5 | using System.Collections.Generic; 6 | 7 | public class OperationCmdlet : Cmdlet 8 | { 9 | /// 10 | /// A reference to the parameter that is used to represent the entity's ID. 11 | /// Leave this null if there is no ID parameter. 12 | /// 13 | public CmdletParameter IdParameter { get; set; } 14 | 15 | /// 16 | /// The name of the OData resource that this cmdlet operates on. 17 | /// 18 | public string ResourceTypeFullName { get; set; } 19 | 20 | /// 21 | /// The full names of the derived types of this resource's OData type. 22 | /// 23 | public IEnumerable ResourceSubTypeFullNames { get; set; } 24 | 25 | /// 26 | /// The name of the property on output objects whose value should be the object's type name. 27 | /// 28 | public string ResourceTypePropertyName { get; set; } 29 | 30 | /// 31 | /// Indicates that this cmdlet retrieves resources that can be referenced by "$ref" requests. 32 | /// 33 | public bool IsReferenceable { get; set; } 34 | 35 | /// 36 | /// The base type of this cmdlet in the generated output. 37 | /// 38 | public CmdletOperationType OperationType { get; set; } 39 | 40 | /// 41 | /// The HTTP method to be used when making the call. 42 | /// 43 | public string HttpMethod { get; set; } 44 | 45 | /// 46 | /// The absolute or relative url to be used when making the call. For relative URLs, the base 47 | /// URL will be the OData endpoint. To use values obtained from parameters, this string should 48 | /// be formatted like an interpolated string with the parameter name as the variable name. 49 | /// For example, if this cmdlet had a parameter with the name "id", the CallUrl might look like: 50 | /// 51 | /// /deviceAppManagement/mobileApps/{mobileAppId}/categories/{id} 52 | /// 53 | /// 54 | public string CallUrl { get; set; } 55 | 56 | public OperationCmdlet(string verb, string noun) : base(verb, noun) { } 57 | 58 | public OperationCmdlet(CmdletName cmdletName) : base(cmdletName) { } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/ListCmdlets.ps1: -------------------------------------------------------------------------------- 1 | pushd .\src\GraphODataPowerShellWriter\bin\Release\output\bin\Release\net471 2 | Import-Module .\Microsoft.Graph.Intune.psd1 3 | $sdkCmdlets = &{(Get-Command -Module Microsoft.Graph.Intune)} 4 | $sdkCmdlets.Name > .\DeviceAppMgmt.cmdlets.txt 5 | $sdkCmdlets.Count -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/PowerShellSDKWriter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace GraphODataPowerShellTemplateWriter 4 | { 5 | using System.Collections.Generic; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Behaviors; 7 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 8 | using Vipr.Core; 9 | using Vipr.Core.CodeModel; 10 | 11 | /// 12 | /// A writer module for Vipr which generates C# code that can be compiled into a PowerShell Graph SDK module. 13 | /// 14 | public class PowerShellSDKWriter : IOdcmWriter 15 | { 16 | public const string GeneratedSDKFilesLocation = @"PowerShellCmdlets\Generated\SDK"; 17 | public const string GeneratedObjectFactoryFilesLocation = @"PowerShellCmdlets\Generated\ObjectFactories"; 18 | 19 | /// 20 | /// Implementation which is provided to Vipr for transforming an ODCM model into the PowerShell SDK. 21 | /// 22 | /// The ODCM model provided by Vipr 23 | /// The TextFile objects representing the generated SDK. 24 | public IEnumerable GenerateProxy(OdcmModel model) 25 | { 26 | IEnumerable generatedSdk = GeneratePowerShellSDK(model, PowerShellSDKWriter.GeneratedSDKFilesLocation); 27 | foreach (TextFile file in generatedSdk) 28 | { 29 | yield return file; 30 | } 31 | 32 | IEnumerable generatedObjectFactories = GenerateObjectFactoryCmdlets(model, PowerShellSDKWriter.GeneratedObjectFactoryFilesLocation); 33 | foreach (TextFile file in generatedObjectFactories) 34 | { 35 | yield return file; 36 | } 37 | } 38 | 39 | /// 40 | /// Generates the PowerShell SDK from the given ODCM model. 41 | /// 42 | /// The ODCM model 43 | /// The TextFile objects representing the generated SDK. 44 | private static IEnumerable GeneratePowerShellSDK(OdcmModel model, string location) 45 | { 46 | // 1. Convert the ODCM model into nodes (i.e. routes) 47 | foreach (OdcmNode node in model.ConvertToOdcmNodes()) 48 | { 49 | // 2. Convert the route into an abstract representation of the PowerShell cmdlets 50 | Resource resource = node.ConvertToResource(location); 51 | 52 | // 3. Convert the resource into an abstract representation of the C# file 53 | CSharpFile cSharpFile = resource.ToCSharpFile(); 54 | 55 | // 4. Generate the text file by converting the abstract representation of the C# file into a string 56 | TextFile outputFile = cSharpFile.ToTextFile(); 57 | 58 | // Return the generated file 59 | yield return outputFile; 60 | } 61 | } 62 | 63 | /// 64 | /// Generates factory cmdlets for creating PowerShell objects that can be serialized as types defined 65 | /// in the given ODCM model. 66 | /// 67 | /// The ODCM model 68 | /// The filesystem location at which the generated files should be placed 69 | /// 70 | private static IEnumerable GenerateObjectFactoryCmdlets(OdcmModel model, string location) 71 | { 72 | // 1. Convert the types in the ODCM model into ObjectFactory objects 73 | foreach (ObjectFactoryCmdlet objectFactoryCmdlet in model.CreateObjectFactories(location)) 74 | { 75 | // 2. Convert the ObjectFactory into an abstract representation of the C# file 76 | CSharpFile cSharpFile = objectFactoryCmdlet.ToCSharpFile(); 77 | 78 | // 3. Generate the text file by converting the abstract representation of the C# file into a string 79 | TextFile outputFile = cSharpFile.ToTextFile(); 80 | 81 | // Return the generated file 82 | yield return outputFile; 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpAccessModifierUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 7 | 8 | public static class CSharpAccessModifierUtils 9 | { 10 | public static string ToCSharpString(this CSharpAccessModifier accessModifier) 11 | { 12 | switch (accessModifier) 13 | { 14 | case CSharpAccessModifier.Public: return "public"; 15 | case CSharpAccessModifier.Protected: return "protected"; 16 | case CSharpAccessModifier.Internal: return "internal"; 17 | case CSharpAccessModifier.Private: return "private"; 18 | default: throw new ArgumentException("Unknown access modifier", nameof(accessModifier)); 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpClassAttributeHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 9 | using Microsoft.Intune.PowerShellGraphSDK; 10 | using PS = System.Management.Automation; 11 | 12 | public static class CSharpClassAttributeHelper 13 | { 14 | public static CSharpAttribute CreateCmdletAttribute(CmdletName name, PS.ConfirmImpact impactLevel, string defaultParameterSetName = null) 15 | { 16 | if (name == null) 17 | { 18 | throw new ArgumentNullException(nameof(name)); 19 | } 20 | 21 | // Cmdlet name 22 | ICollection arguments = new List() 23 | { 24 | $"\"{name.Verb}\"", 25 | $"\"{name.Noun}\"", 26 | }; 27 | 28 | // Impact level 29 | if (impactLevel != PS.ConfirmImpact.None) 30 | { 31 | arguments.Add($"{nameof(PS.CmdletAttribute.ConfirmImpact)} = {nameof(PS.ConfirmImpact)}.{impactLevel.ToString()}"); 32 | } 33 | 34 | // Default parameter set 35 | if (defaultParameterSetName != null) 36 | { 37 | arguments.Add($"{nameof(PS.CmdletAttribute.DefaultParameterSetName)} = @\"{defaultParameterSetName}\""); 38 | } 39 | 40 | return new CSharpAttribute(nameof(PS.CmdletAttribute), arguments: arguments.ToArray()); 41 | } 42 | 43 | public static CSharpAttribute CreateODataTypeAttribute(string oDataTypeFullName, IEnumerable subTypeFullNames = null) 44 | { 45 | if (oDataTypeFullName == null) 46 | { 47 | throw new ArgumentNullException(nameof(oDataTypeFullName)); 48 | } 49 | 50 | return CSharpPropertyAttributeHelper.CreateODataTypeAttribute(oDataTypeFullName, subTypeFullNames ?? Array.Empty()); 51 | } 52 | 53 | public static CSharpAttribute CreateResourceReferenceAttribute() 54 | { 55 | return new CSharpAttribute(nameof(ResourceReferenceAttribute)); 56 | } 57 | 58 | public static CSharpAttribute CreateResourceTypePropertyNameAttribute(string resourceTypePropertyName) 59 | { 60 | if (resourceTypePropertyName == null) 61 | { 62 | throw new ArgumentNullException(nameof(resourceTypePropertyName)); 63 | } 64 | 65 | return new CSharpAttribute(nameof(ResourceTypePropertyNameAttribute), $"\"{resourceTypePropertyName}\""); 66 | } 67 | 68 | public static CSharpAttribute CreateAliasAttribute(IEnumerable aliases) 69 | { 70 | if (aliases == null) 71 | { 72 | throw new ArgumentNullException(nameof(aliases)); 73 | } 74 | if (!aliases.Any()) 75 | { 76 | throw new ArgumentException("There must be 1 or more aliases to create an [Alias()] class attribute", nameof(aliases)); 77 | } 78 | 79 | return new CSharpAttribute(nameof(PS.AliasAttribute), aliases.Select(alias => $"\"{alias}\"")); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpFileHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | public static class CSharpFileHelper 6 | { 7 | public static string GetLicenseHeader() => @"// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information."; 8 | 9 | public static string GetDefaultNamespace() => "Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets"; 10 | 11 | public static string[] GetDefaultUsings() => defaultUsings; 12 | private static readonly string[] defaultUsings = 13 | { 14 | "System.Management.Automation", 15 | }; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpMethodHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 7 | using Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets; 8 | 9 | public static class CSharpMethodHelper 10 | { 11 | public static CSharpMethod CreateGetResourcePathMethod(string url, bool isFunction = false) 12 | { 13 | if (url == null) 14 | { 15 | throw new ArgumentNullException(nameof(url)); 16 | } 17 | 18 | // Create the method definition 19 | string methodName = nameof(ODataCmdletBase.GetResourcePath); 20 | Type returnType = typeof(string); 21 | string methodBody = isFunction 22 | ? $"return $\"{url}({{this.{nameof(GetCmdlet.GetFunctionUrlSegment)}()}})\";" 23 | : $"return $\"{url}\";"; 24 | 25 | // Create the method object 26 | CSharpMethod result = new CSharpMethod(methodName, returnType, methodBody) 27 | { 28 | Override = true, 29 | AccessModifier = CSharpAccessModifier.Internal, 30 | }; 31 | 32 | return result; 33 | } 34 | 35 | public static CSharpMethod CreateGetHttpMethodMethod(string httpMethod) 36 | { 37 | if (httpMethod == null) 38 | { 39 | throw new ArgumentNullException(nameof(httpMethod)); 40 | } 41 | 42 | // Create the method definition 43 | string methodName = nameof(ODataCmdletBase.GetHttpMethod); 44 | Type returnType = typeof(string); 45 | string methodBody = $"return \"{httpMethod}\";"; 46 | 47 | // Create the method object 48 | CSharpMethod result = new CSharpMethod(methodName, returnType, methodBody) 49 | { 50 | Override = true, 51 | AccessModifier = CSharpAccessModifier.Internal, 52 | }; 53 | 54 | return result; 55 | } 56 | 57 | public static CSharpMethod CreateGetContentMethodForCreatingReference(string referenceUrlParameterName) 58 | { 59 | // Create the method definition 60 | string methodName = nameof(ODataCmdletBase.GetContent); 61 | Type returnType = typeof(object); 62 | string methodBody = $"return this.{nameof(ODataCmdletBase.GetReferenceRequestContent)}({referenceUrlParameterName});"; 63 | 64 | // Create the method object 65 | CSharpMethod result = new CSharpMethod(methodName, returnType, methodBody) 66 | { 67 | Override = true, 68 | AccessModifier = CSharpAccessModifier.Internal, 69 | }; 70 | 71 | return result; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpNamingUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using Microsoft.CSharp; 7 | 8 | public static class CSharpNamingUtils 9 | { 10 | /// 11 | /// C# code provider. 12 | /// 13 | private static CSharpCodeProvider CSharpCodeProvider = new CSharpCodeProvider(); 14 | 15 | /// 16 | /// Checks whether the provided string is a reserved C# keyword. 17 | /// 18 | /// The identifier to check 19 | /// True if the string is a reserved keyword, otherwise false. 20 | public static bool IsValidIdentifier(this string identifier) 21 | { 22 | if (identifier == null) 23 | { 24 | throw new ArgumentNullException(nameof(identifier)); 25 | } 26 | 27 | return CSharpCodeProvider.IsValidIdentifier(identifier); 28 | } 29 | 30 | /// 31 | /// Sanitizes a C# string if required, otherwise returns the original string. 32 | /// 33 | /// The identifier to sanitize 34 | /// The sanitized C# keyword which is safe to use as an identifier. 35 | public static string SanitizeIdentifier(this string identifier) 36 | { 37 | if (identifier == null) 38 | { 39 | throw new ArgumentNullException(nameof(identifier)); 40 | } 41 | 42 | if (identifier.IsValidIdentifier()) 43 | { 44 | return identifier; 45 | } 46 | else 47 | { 48 | // Add an "@" to escape keywords 49 | string result = $"@{identifier}"; 50 | 51 | // Make sure that it is now valid - if it isn't, it was never a C# keyword to begin with. 52 | // It was just an invalid identifier, probably with special characters or numbers. 53 | if (!result.IsValidIdentifier()) 54 | { 55 | throw new ArgumentException($"Invalid characters found in identifier '{identifier}'", nameof(identifier)); 56 | } 57 | 58 | return result; 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CSharpTypeUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | 9 | public static class CSharpTypeUtils 10 | { 11 | /// 12 | /// Gets the underlying type for an array type, and also returns the number of dimensions. 13 | /// 14 | /// The type that represents an array 15 | /// The number of dimensions - if the provided type is not an array type, this will be zero 16 | /// 17 | /// The underlying type (i.e. the type when all dimensions are removed and it is no longer an array). 18 | /// If the provided type is not an array type, this method will return the provided type. 19 | /// 20 | public static Type GetArrayUnderlyingType(this Type arrayType, out int dimensions) 21 | { 22 | if (arrayType == null) 23 | { 24 | throw new ArgumentNullException(nameof(arrayType)); 25 | } 26 | 27 | // Create a temporary type so we don't lose the reference to the passed-in type 28 | Type tempType = arrayType; 29 | 30 | // Unwrap the array 31 | int arrayDimensions = 0; 32 | while (tempType.IsArray) 33 | { 34 | tempType = tempType.GetElementType(); 35 | arrayDimensions++; 36 | } 37 | 38 | dimensions = arrayDimensions; 39 | return tempType; 40 | } 41 | 42 | /// 43 | /// Converts a type to a C# string that can be compiled in code. 44 | /// 45 | /// The type 46 | /// The C# string 47 | public static string ToCSharpString(this Type type) 48 | { 49 | if (type == null) 50 | { 51 | throw new ArgumentNullException(nameof(type)); 52 | } 53 | 54 | // Unwrap the array if required 55 | Type tempType = type.GetArrayUnderlyingType(out int arrayDimensions); 56 | 57 | // Get the C# type name 58 | string typeName; 59 | if (!tempType.IsGenericType) 60 | { 61 | typeName = tempType.Name; 62 | } 63 | else 64 | { 65 | // Get the full name of the type without it's generic arguments (i.e. everything before the backtick) 66 | string typeNameWithoutArguments = tempType.Name.Substring(0, tempType.Name.IndexOf('`')); 67 | 68 | // Get the type arguments 69 | IEnumerable typeArguments = tempType.GenericTypeArguments.Select(typeArgument => typeArgument.ToCSharpString()); 70 | string typeArgumentsString = string.Join(", ", typeArguments); 71 | 72 | // Create the full type name with arguments 73 | typeName = $"{typeNameWithoutArguments}<{typeArgumentsString}>"; 74 | } 75 | 76 | // Check if this type is nested inside another type 77 | if (tempType.DeclaringType != null) 78 | { 79 | // Prepend the declaring type 80 | typeName = $"{tempType.DeclaringType.ToCSharpString()}.{typeName}"; 81 | } 82 | else if (!string.IsNullOrEmpty(tempType.Namespace)) 83 | { 84 | // Add the namespace 85 | typeName = $"{tempType.Namespace}.{typeName}"; 86 | } 87 | 88 | // Add the array brackets back into the type name 89 | while (arrayDimensions > 0) 90 | { 91 | typeName += "[]"; 92 | arrayDimensions--; 93 | } 94 | 95 | return typeName; 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/CmdletOperationTypeUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 7 | using Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets; 8 | 9 | public static class CmdletOperationTypeUtils 10 | { 11 | public static string ToCSharpString(this CmdletOperationType operationType) 12 | { 13 | switch (operationType) 14 | { 15 | case CmdletOperationType.Get: return nameof(GetCmdlet); 16 | case CmdletOperationType.GetOrSearch: return nameof(GetOrSearchCmdlet); 17 | case CmdletOperationType.GetStream: return nameof(GetStreamCmdlet); 18 | case CmdletOperationType.Post: return nameof(PostCmdlet); 19 | case CmdletOperationType.PutRefToSingleEntity: return nameof(PutReferenceToEntityCmdlet); 20 | case CmdletOperationType.PostRefToCollection: return nameof(PostReferenceToCollectionCmdlet); 21 | case CmdletOperationType.UpdateStream: return nameof(UpdateStreamCmdlet); 22 | case CmdletOperationType.Patch: return nameof(PatchCmdlet); 23 | case CmdletOperationType.Delete: return nameof(DeleteCmdlet); 24 | case CmdletOperationType.FunctionReturningEntity: return nameof(FunctionReturningEntityCmdlet); 25 | case CmdletOperationType.FunctionReturningCollection: return nameof(FunctionReturningCollectionCmdlet); 26 | case CmdletOperationType.Action: return nameof(ActionCmdlet); 27 | default: throw new ArgumentException("Unknown operation type", nameof(operationType)); 28 | } 29 | } 30 | 31 | public static bool IsInsertOrDeleteOperation(this CmdletOperationType operationType) 32 | { 33 | return operationType == CmdletOperationType.Post || operationType == CmdletOperationType.Delete; 34 | } 35 | 36 | public static bool IsInsertUpdateOrDeleteOperation(this CmdletOperationType operationType) 37 | { 38 | return operationType.IsInsertOrDeleteOperation() || operationType == CmdletOperationType.Patch; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/DocumentationUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using System.Linq; 7 | using System.Security; 8 | using System.Text; 9 | using Microsoft.Graph.GraphODataPowerShellSDKWriter.Generator.Models; 10 | 11 | public static class DocumentationUtils 12 | { 13 | public static CSharpDocumentationComment ToCSharpDocumentationComment(this CmdletDocumentation cmdletDoc) 14 | { 15 | if (cmdletDoc == null) 16 | { 17 | throw new ArgumentNullException(nameof(cmdletDoc)); 18 | } 19 | 20 | StringBuilder summaryBuilder = new StringBuilder(); 21 | 22 | // Synopsis 23 | if (cmdletDoc.Synopsis != null) 24 | { 25 | summaryBuilder.AppendLine($"{cmdletDoc.Synopsis.EscapeForXml()}"); 26 | } 27 | 28 | // Descriptions 29 | if (cmdletDoc.Descriptions != null) 30 | { 31 | foreach (string description in cmdletDoc.Descriptions.Where(desc => !string.IsNullOrWhiteSpace(desc))) 32 | { 33 | summaryBuilder.AppendLine($"{description.EscapeForXml()}"); 34 | } 35 | } 36 | 37 | StringBuilder notesBuilder = new StringBuilder(); 38 | 39 | // URLs 40 | if (cmdletDoc.Links != null) 41 | { 42 | foreach (CmdletDocumentationLink link in cmdletDoc.Links) 43 | { 44 | notesBuilder.AppendLine($@"{link.Name.EscapeForXml()}"); 45 | } 46 | } 47 | 48 | // Compile the comments 49 | string summary = summaryBuilder.ToString().Trim(); 50 | string notes = notesBuilder.ToString().Trim(); 51 | 52 | // Create the result 53 | CSharpDocumentationComment result = new CSharpDocumentationComment() 54 | { 55 | Summary = string.IsNullOrWhiteSpace(summary) ? null : summary, 56 | RawNotes = string.IsNullOrWhiteSpace(notes) ? null : notes, 57 | }; 58 | 59 | return result; 60 | } 61 | 62 | public static CSharpDocumentationComment ToCSharpDocumentationComment(this CmdletParameterDocumentation paramDoc) 63 | { 64 | if (paramDoc == null) 65 | { 66 | throw new ArgumentNullException(nameof(paramDoc)); 67 | } 68 | 69 | StringBuilder summaryBuilder = new StringBuilder(); 70 | 71 | // Descriptions 72 | if (paramDoc.Descriptions != null) 73 | { 74 | foreach (string description in paramDoc.Descriptions.Where(desc => !string.IsNullOrWhiteSpace(desc))) 75 | { 76 | summaryBuilder.AppendLine($"{description.EscapeForXml()}"); 77 | } 78 | } 79 | 80 | // Valid values 81 | if (paramDoc.ValidValues != null && paramDoc.ValidValues.Any()) 82 | { 83 | string valueList = string.Join(", ", paramDoc.ValidValues.Select(val => $"'{val}'".EscapeForXml())); 84 | summaryBuilder.AppendLine(""); 85 | summaryBuilder.AppendLine($" Valid values: {valueList}".Indent()); 86 | summaryBuilder.AppendLine(""); 87 | } 88 | 89 | // Compile the comments 90 | string summary = summaryBuilder.ToString().Trim(); 91 | 92 | // Create the result 93 | CSharpDocumentationComment result = new CSharpDocumentationComment() 94 | { 95 | Summary = string.IsNullOrWhiteSpace(summary) ? null : summary, 96 | }; 97 | 98 | return result; 99 | } 100 | 101 | public static string EscapeForXml(this string unescaped) 102 | { 103 | return SecurityElement.Escape(unescaped); 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/GraphODataPowerShellWriter/Utils/EnumerableUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Graph.GraphODataPowerShellSDKWriter.Utils 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | 8 | /// 9 | /// A set of utility methods to simplify operations related to enumerables. 10 | /// 11 | public static class EnumerableUtils 12 | { 13 | /// 14 | /// Creates an IEnumerable which contains the given object. 15 | /// 16 | /// The type of the object 17 | /// The object 18 | /// The IEnumerable. 19 | public static IEnumerable SingleObjectAsEnumerable(this T obj) 20 | { 21 | yield return obj; 22 | } 23 | 24 | /// 25 | /// Creates a comparer for a type from a lambda expression. 26 | /// 27 | /// 28 | /// 29 | /// 30 | public static IEqualityComparer CreateEqualityComparer(Func equalsFunction, Func getHashCodeFunction = null) 31 | { 32 | return new GenericEqualityComparer(equalsFunction, getHashCodeFunction); 33 | } 34 | 35 | private class GenericEqualityComparer : IEqualityComparer 36 | { 37 | private readonly Func _equals; 38 | private readonly Func _getHashCode; 39 | 40 | public GenericEqualityComparer(Func equalsFunction, Func getHashCodeFunction = null) 41 | { 42 | this._equals = equalsFunction ?? throw new ArgumentNullException(nameof(equalsFunction)); 43 | this._getHashCode = getHashCodeFunction ?? (obj => obj.GetHashCode()); 44 | } 45 | 46 | public bool Equals(T x, T y) 47 | { 48 | return this._equals(x, y); 49 | } 50 | 51 | public int GetHashCode(T obj) 52 | { 53 | return this._getHashCode(obj); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/DerivedTypeAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the given property is defined on the specified type. 9 | /// 10 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 11 | internal class DerivedTypeAttribute : Attribute 12 | { 13 | /// 14 | /// The name of the type that this property is from. 15 | /// 16 | internal string FullName { get; } 17 | 18 | /// 19 | /// Creates a new . 20 | /// 21 | /// The name of the type that this property exists on. 22 | internal DerivedTypeAttribute(string derivedTypeFullName) 23 | { 24 | if (string.IsNullOrWhiteSpace(derivedTypeFullName)) 25 | { 26 | throw new ArgumentNullException(nameof(derivedTypeFullName)); 27 | } 28 | 29 | this.FullName = derivedTypeFullName; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ExpandableAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that this property is able to be included in the list of properties for the $expand 9 | /// query parameter when retrieving the entity from Graph. 10 | /// 11 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 12 | internal class ExpandableAttribute : Attribute { } 13 | } 14 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/IdParameter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the given property is used to specify an ID in the URL. 9 | /// 10 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 11 | internal class IdParameterAttribute : Attribute 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ODataTypeAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | 8 | /// 9 | /// Indicates that the parameter or cmdlet was generated from an OData property of the given type. 10 | /// 11 | [AttributeUsage( 12 | AttributeTargets.Property | AttributeTargets.Class, 13 | AllowMultiple = false, 14 | Inherited = true)] 15 | internal class ODataTypeAttribute : Attribute 16 | { 17 | /// 18 | /// The name of the OData type. 19 | /// 20 | internal string TypeFullName { get; } 21 | 22 | /// 23 | /// The names of all the subtypes of the given type. 24 | /// 25 | internal IEnumerable SubTypeFullNames { get; } 26 | 27 | /// 28 | /// Creates a new . 29 | /// 30 | /// The name of the OData type. 31 | /// The names of all the subtypes of the given type. 32 | internal ODataTypeAttribute(string oDataTypeFullName, params string[] oDataSubTypeFullNames) 33 | { 34 | this.TypeFullName = oDataTypeFullName ?? throw new ArgumentNullException(nameof(oDataTypeFullName)); 35 | this.SubTypeFullNames = oDataSubTypeFullNames != null 36 | ? new HashSet(oDataSubTypeFullNames) as IEnumerable 37 | : Array.Empty(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ParameterSetSelectorAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the switch parameter is used to select a particular parameter set. 9 | /// This attribute should only be included on properties. 10 | /// 11 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 12 | internal class ParameterSetSelectorAttribute : Attribute 13 | { 14 | /// 15 | /// The name of the parameter set that this selects. 16 | /// 17 | internal string ParameterSetName { get; } 18 | 19 | /// 20 | /// Creates a new . 21 | /// 22 | /// The name of the parameter set that the switch parameter would select. 23 | internal ParameterSetSelectorAttribute(string parameterSetName) 24 | { 25 | if (string.IsNullOrWhiteSpace(parameterSetName)) 26 | { 27 | throw new ArgumentException($"{nameof(parameterSetName)} cannot be null or whitespace", nameof(parameterSetName)); 28 | } 29 | 30 | this.ParameterSetName = parameterSetName; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ResourceIdParameterAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the given property is used to specify an entity's main ID in the URL. 9 | /// 10 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 11 | internal class ResourceIdParameterAttribute : Attribute 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ResourceReferenceAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the class represents a cmdlet that retrieves a resource that can be referenced in a "$ref" cmdlet. 9 | /// 10 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 11 | internal class ResourceReferenceAttribute : Attribute {} 12 | } 13 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ResourceTypePropertyNameAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Specifies the name of the property whose value can be used as an input to type cast parameters. 9 | /// 10 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] 11 | internal class ResourceTypePropertyNameAttribute : Attribute 12 | { 13 | internal string ResourceTypePropertyName { get; } 14 | 15 | internal ResourceTypePropertyNameAttribute(string propertyName) 16 | { 17 | if (propertyName == null) 18 | { 19 | throw new ArgumentNullException(nameof(propertyName)); 20 | } 21 | if (string.IsNullOrWhiteSpace(propertyName)) 22 | { 23 | throw new ArgumentException("Resource type property name cannot be empty or whitespace"); 24 | } 25 | 26 | this.ResourceTypePropertyName = propertyName; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/SelectableAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that this property is able to be included in the list of properties for the $select 9 | /// query parameter when retrieving the entity from Graph. 10 | /// 11 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 12 | internal class SelectableAttribute : Attribute { } 13 | } 14 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/SortableAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that this property is able to be included in the list of properties for the $orderBy 9 | /// query parameter when retrieving the entity from Graph. 10 | /// 11 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 12 | internal class SortableAttribute : Attribute { } 13 | } 14 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/TypeCastParameterAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | /// 8 | /// Indicates that the given property is used to specify a type cast in the URL. 9 | /// 10 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 11 | internal class TypeCastParameterAttribute : Attribute 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ValidateTypeAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Linq; 7 | using System.Management.Automation; 8 | 9 | /// 10 | /// Validates that the parameter is set to a value which is one of the specified types. 11 | /// 12 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 13 | internal class ValidateTypeAttribute : ValidateEnumeratedArgumentsAttribute 14 | { 15 | /// 16 | /// The list of valid types. 17 | /// 18 | private Type[] Types { get; } 19 | 20 | /// 21 | /// Creates a new . 22 | /// 23 | /// The list of valid types 24 | public ValidateTypeAttribute(params Type[] types) 25 | { 26 | if (types == null) 27 | { 28 | throw new ArgumentNullException(nameof(types)); 29 | } 30 | if (!types.Any()) 31 | { 32 | throw new ArgumentException("The list of types cannot empty", nameof(types)); 33 | } 34 | 35 | this.Types = types; 36 | } 37 | 38 | /// 39 | /// Ensures that the value provided is a valid type. 40 | /// 41 | /// 42 | protected override void ValidateElement(object param) 43 | { 44 | Type paramType = param.GetType(); 45 | if (!this.Types.Any(type => type.IsAssignableFrom(paramType))) 46 | { 47 | string typesString = string.Join(", ", this.Types.Select((t) => $"'{t.ToString()}'")); 48 | throw new ValidationMetadataException($"The provided parameter of type '{paramType}' is not a valid type. Accepted types are: [{typesString}]."); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Attributes/ValidateUrlAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Management.Automation; 7 | 8 | /// 9 | /// Checks that a given property's value represents a valid URL string. 10 | /// 11 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 12 | internal class ValidateUrlAttribute : ValidateEnumeratedArgumentsAttribute 13 | { 14 | /// 15 | /// The kind of URL (e.g. relative, absolute). 16 | /// 17 | private UriKind UriKind { get; set; } 18 | 19 | /// 20 | /// Creates a new . 21 | /// 22 | /// The kind or URL 23 | public ValidateUrlAttribute(UriKind uriKind = UriKind.Absolute) 24 | { 25 | this.UriKind = uriKind; 26 | } 27 | 28 | /// 29 | /// Validates that the given object represents a valid URL string. 30 | /// 31 | /// The URL to validate 32 | protected override void ValidateElement(object url) 33 | { 34 | if (url == null) 35 | { 36 | throw new ValidationMetadataException("The provided URL cannot be null"); 37 | } 38 | 39 | string stringUrl = url as string; 40 | if (stringUrl == null) 41 | { 42 | throw new ValidationMetadataException("The provided URL must be a string"); 43 | } 44 | 45 | if (!Uri.IsWellFormedUriString(stringUrl, UriKind)) 46 | { 47 | string errorMessage = "The provided URL is not valid"; 48 | if (UriKind == UriKind.Absolute) 49 | { 50 | errorMessage += " - the URL must be an absolute URL"; 51 | } 52 | else 53 | { 54 | errorMessage += " - the URL may be a relative URL"; 55 | } 56 | 57 | throw new ValidationMetadataException(errorMessage); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Constants/AnnotationTerms.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.ODataConstants 4 | { 5 | /// 6 | /// OData annotation term names. 7 | /// 8 | public static class AnnotationTerms 9 | { 10 | /// 11 | /// The "Computed" term. This annotation (if set to "true") identifies a 12 | /// property which cannot be written to with an insert, update or delete operation. 13 | /// 14 | public const string Computed = "Org.OData.Core.V1.Computed"; 15 | 16 | /// 17 | /// The "Immutable" term. This annotation (if set to "true") identifies a 18 | /// property which cannot be written to with an update or delete operation. 19 | /// 20 | public const string Immutable = "Org.OData.Core.V1.Immutable"; 21 | 22 | /// 23 | /// The "InsertRestrictions" term. This annotation (if the containing record's 24 | /// "Insertable" property is set to "true") identifies a resource which cannot be 25 | /// created through the given property. 26 | /// 27 | public const string InsertRestrictions = "Org.OData.Core.V1.InsertRestrictions"; 28 | 29 | /// 30 | /// Indicates that the given property does not support insert operations. 31 | /// 32 | public const string Insertable = "Insertable"; 33 | 34 | /// 35 | /// The "UpdateRestrictions" term. This annotation (if the containing record's 36 | /// "Updatable" property is set to "true") identifies a resource which cannot be 37 | /// updated through the given property. 38 | /// 39 | public const string UpdateRestrictions = "Org.OData.Core.V1.UpdateRestrictions"; 40 | 41 | /// 42 | /// Indicates that the given property does not support update operations. 43 | /// 44 | public const string Updatable = "Updatable"; 45 | 46 | /// 47 | /// The "DeleteRestrictions" term. This annotation (if the containing record's 48 | /// "Deletable" property is set to "true") identifies a resource which cannot be 49 | /// deleted through the given property. 50 | /// 51 | public const string DeleteRestrictions = "Org.OData.Core.V1.DeleteRestrictions"; 52 | 53 | /// 54 | /// Indicates that the given property does not support delete operations. 55 | /// 56 | public const string Deletable = "Deletable"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Constants/EdmTypeNames.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.ODataConstants 4 | { 5 | /// 6 | /// The full names of EDM types. 7 | /// 8 | public static class EdmTypeNames 9 | { 10 | /// 11 | /// Edm.Boolean 12 | /// 13 | public const string Boolean = "Edm.Boolean"; 14 | 15 | /// 16 | /// Edm.String 17 | /// 18 | public const string String = "Edm.String"; 19 | 20 | /// 21 | /// Edm.Byte 22 | /// 23 | public const string Byte = "Edm.Byte"; 24 | 25 | /// 26 | /// Edm.SByte 27 | /// 28 | public const string SByte = "Edm.SByte"; 29 | 30 | /// 31 | /// Edm.Stream 32 | /// 33 | public const string Stream = "Edm.Stream"; 34 | 35 | /// 36 | /// Edm.Binary 37 | /// 38 | public const string Binary = "Edm.Binary"; 39 | 40 | /// 41 | /// Edm.Int16 42 | /// 43 | public const string Int16 = "Edm.Int16"; 44 | 45 | /// 46 | /// Edm.UInt16 47 | /// 48 | public const string UInt16 = "Edm.UInt16"; 49 | 50 | /// 51 | /// Edm.Int32 52 | /// 53 | public const string Int32 = "Edm.Int32"; 54 | 55 | /// 56 | /// Edm.UInt32 57 | /// 58 | public const string UInt32 = "Edm.UInt32"; 59 | 60 | /// 61 | /// Edm.Int64 62 | /// 63 | public const string Int64 = "Edm.Int64"; 64 | 65 | /// 66 | /// Edm.UInt64 67 | /// 68 | public const string UInt64 = "Edm.UInt64"; 69 | 70 | /// 71 | /// Edm.Single 72 | /// 73 | public const string Single = "Edm.Single"; 74 | 75 | /// 76 | /// Edm.Double 77 | /// 78 | public const string Double = "Edm.Double"; 79 | 80 | /// 81 | /// Edm.Decimal 82 | /// 83 | public const string Decimal = "Edm.Decimal"; 84 | 85 | /// 86 | /// Edm.Guid 87 | /// 88 | public const string Guid = "Edm.Guid"; 89 | 90 | /// 91 | /// Edm.Date 92 | /// 93 | public const string Date = "Edm.Date"; 94 | 95 | /// 96 | /// Edm.DateTime 97 | /// 98 | public const string DateTime = "Edm.DateTime"; 99 | 100 | /// 101 | /// Edm.DateTimeOffset 102 | /// 103 | public const string DateTimeOffset = "Edm.DateTimeOffset"; 104 | 105 | /// 106 | /// Edm.TimeOfDay 107 | /// 108 | public const string TimeOfDay = "Edm.TimeOfDay"; 109 | 110 | /// 111 | /// Edm.Time 112 | /// 113 | public const string Time = "Edm.Time"; 114 | 115 | /// 116 | /// Edm.Duration 117 | /// 118 | public const string Duration = "Edm.Duration"; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Constants/QueryParameters.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.ODataConstants 4 | { 5 | /// 6 | /// The valid OData query parameter names. 7 | /// 8 | public static class QueryParameters 9 | { 10 | /// 11 | /// $select 12 | /// 13 | public const string Select = "$select"; 14 | 15 | /// 16 | /// $expand 17 | /// 18 | public const string Expand = "$expand"; 19 | 20 | /// 21 | /// $filter 22 | /// 23 | public const string Filter = "$filter"; 24 | 25 | /// 26 | /// $filter 27 | /// 28 | public const string Search = "$search"; 29 | 30 | /// 31 | /// $orderBy 32 | /// 33 | public const string OrderBy = "$orderBy"; 34 | 35 | /// 36 | /// $skip 37 | /// 38 | public const string Skip = "$skip"; 39 | 40 | /// 41 | /// $top 42 | /// 43 | public const string Top = "$top"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Constants/RequestProperties.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.ODataConstants 4 | { 5 | /// 6 | /// The properties that can be sent as part of a request body. 7 | /// 8 | public static class RequestProperties 9 | { 10 | /// 11 | /// @odata.type 12 | /// 13 | public const string ODataType = "@odata.type"; 14 | 15 | /// 16 | /// @odata.id 17 | /// 18 | public const string ODataId = "@odata.id"; 19 | 20 | /// 21 | /// id 22 | /// 23 | public const string Id = "id"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Constants/SearchResultProperties.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.ODataConstants 4 | { 5 | /// 6 | /// The properties that can be returned in a search result (i.e. GET on a collection). 7 | /// 8 | public static class SearchResultProperties 9 | { 10 | /// 11 | /// @odata.context 12 | /// 13 | public const string ODataContext = "@odata.context"; 14 | 15 | /// 16 | /// @odata.count 17 | /// 18 | public const string ODataCount = "@odata.count"; 19 | 20 | /// 21 | /// @odata.nextLink 22 | /// 23 | public const string ODataNextLink = "@odata.nextLink"; 24 | 25 | /// 26 | /// value 27 | /// 28 | public const string Value = "value"; 29 | 30 | /// 31 | /// @odata.type 32 | /// 33 | public const string ODataType = RequestProperties.ODataType; 34 | 35 | /// 36 | /// id 37 | /// 38 | public const string Id = RequestProperties.Id; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/EnvironmentParameters.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | /// 6 | /// Keeps track of the parameters used by an AAD environment. 7 | /// 8 | internal class EnvironmentParameters 9 | { 10 | private const string powerShellClientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547"; // PowerShell-Intune 11 | //private const string powerShellClientId = "ae9acab0-7171-4115-83d9-18b4d80969b8"; // PowerShell 12 | private const string applicationRedirectLink = "urn:ietf:wg:oauth:2.0:oob"; 13 | 14 | /// 15 | /// Location of the auth endpoint. 16 | /// 17 | internal string AuthUrl { get; set; } 18 | 19 | /// 20 | /// The ID of the resource. 21 | /// 22 | internal string ResourceId { get; set; } 23 | 24 | /// 25 | /// The location of the resource. 26 | /// 27 | internal string GraphBaseAddress { get; set; } 28 | 29 | /// 30 | /// The client ID to use when authenticating. 31 | /// 32 | internal string AppId { get; set; } 33 | 34 | /// 35 | /// The redirect link to use when authenticating. 36 | /// 37 | internal string RedirectLink { get; set; } 38 | 39 | /// 40 | /// The schema version to use when making a Graph call. 41 | /// 42 | internal string SchemaVersion { get; set; } 43 | 44 | /// 45 | /// Creates a new EnvironmentParameters object. 46 | /// 47 | internal EnvironmentParameters() { } 48 | 49 | /// 50 | /// Copies an existing EnvironmentParameters object. 51 | /// 52 | /// The EnvironmentParameters object to copy 53 | internal EnvironmentParameters(EnvironmentParameters toCopy) 54 | { 55 | this.AuthUrl = toCopy.AuthUrl; 56 | this.ResourceId = toCopy.ResourceId; 57 | this.GraphBaseAddress = toCopy.GraphBaseAddress; 58 | this.AppId = toCopy.AppId; 59 | this.RedirectLink = toCopy.RedirectLink; 60 | this.SchemaVersion = toCopy.SchemaVersion; 61 | } 62 | 63 | /// 64 | /// Creates a copy of this instance of . 65 | /// 66 | /// The copy of this instance. 67 | internal EnvironmentParameters Copy() 68 | { 69 | return new EnvironmentParameters(this); 70 | } 71 | 72 | internal static EnvironmentParameters Prod { get; } = new EnvironmentParameters() 73 | { 74 | AuthUrl = "https://login.microsoftonline.com/common", 75 | ResourceId = "https://graph.microsoft.com/", 76 | GraphBaseAddress = "https://graph.microsoft.com", 77 | AppId = powerShellClientId, 78 | RedirectLink = applicationRedirectLink, 79 | SchemaVersion = "v1.0", 80 | }; 81 | 82 | internal static EnvironmentParameters PPE { get; } = new EnvironmentParameters() 83 | { 84 | AuthUrl = "https://login.windows-ppe.net/common", 85 | ResourceId = "https://graph.microsoft-ppe.com/", 86 | GraphBaseAddress = "https://graph.microsoft-ppe.com", 87 | AppId = powerShellClientId, 88 | RedirectLink = applicationRedirectLink, 89 | SchemaVersion = "beta", 90 | }; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Exceptions/AdalAuthException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using Microsoft.IdentityModel.Clients.ActiveDirectory; 6 | 7 | internal class AdalAuthException : AuthException 8 | { 9 | internal AdalAuthException(string message, AdalException innerException) : base(message, innerException) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Exceptions/AuthException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | internal abstract class AuthException : Exception 8 | { 9 | internal AuthException(string message) : base(message) 10 | { 11 | } 12 | 13 | internal AuthException(string message, Exception innerException) : base(message, innerException) 14 | { 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Exceptions/MsiAuthException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | 7 | internal class MsiAuthException : AuthException 8 | { 9 | internal MsiAuthException(string message) : base(message) 10 | { 11 | } 12 | 13 | internal MsiAuthException(string message, Exception innerException) : base(message, innerException) 14 | { 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Exceptions/PSGraphSDKException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Management.Automation; 7 | 8 | /// 9 | /// The exception type that is thrown by cmdlets in the PowerShell Graph SDK. 10 | /// 11 | public class PSGraphSDKException : Exception, IContainsErrorRecord 12 | { 13 | /// 14 | /// The prefix for the error name. 15 | /// 16 | internal const string ErrorPrefix = "PowerShellGraphSDK_"; 17 | 18 | /// 19 | /// The PowerShell error record which contains the error details. 20 | /// 21 | public ErrorRecord ErrorRecord { get; private set; } 22 | 23 | /// 24 | /// Creates a . 25 | /// 26 | /// The inner exception 27 | /// The error ID which should be unique to this error type 28 | /// The error category 29 | /// An object that can provide more debugging information (e.g. the object that caused the error) 30 | internal PSGraphSDKException(Exception innerException, string specificErrorId, ErrorCategory errorCategory, object targetObject) 31 | : base(specificErrorId, innerException) 32 | { 33 | this.ErrorRecord = new ErrorRecord( 34 | innerException, 35 | ErrorPrefix + specificErrorId, 36 | errorCategory, 37 | targetObject); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/PSAuthenticationError.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Management.Automation; 7 | 8 | /// 9 | /// PowerShell authentication error. 10 | /// 11 | internal class PSAuthenticationError : PSGraphSDKException 12 | { 13 | /// 14 | /// Creates a new . 15 | /// 16 | /// The inner exception 17 | /// The error ID which should be unique to this error type 18 | /// The error category 19 | /// An object that can provide more debugging information (e.g. the object that caused the error) 20 | internal PSAuthenticationError(Exception innerException, string specificErrorId, ErrorCategory errorCategory, object targetObject) 21 | : base(innerException, specificErrorId, errorCategory, targetObject) { } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Utils/AuthUtils_NetStandard.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | #if !NETFRAMEWORK 4 | 5 | namespace Microsoft.Intune.PowerShellGraphSDK 6 | { 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using Microsoft.IdentityModel.Clients.ActiveDirectory; 11 | 12 | internal static partial class AuthUtils 13 | { 14 | /// 15 | /// Authenticates using the device code flow. See here for more information: 16 | /// https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-deviceprofile/. 17 | /// 18 | /// 19 | /// The action which displays the message from ADAL (containing the retrieved device code) to the user. 20 | /// The message will instruct the user to enter the device code by navigating to http://aka.ms/devicelogin/. 21 | /// 22 | /// 23 | /// Whether or not to trigger the admin consent flow for this app ID. 24 | /// 25 | /// The HTTP header to use when making calls. 26 | internal static SdkAuthResult AuthWithDeviceCode( 27 | Action displayDeviceCodeMessageToUser, 28 | bool useAdminConsentFlow = false) 29 | { 30 | if (displayDeviceCodeMessageToUser == null) 31 | { 32 | throw new ArgumentNullException(nameof(displayDeviceCodeMessageToUser)); 33 | } 34 | 35 | // Get the environment parameters 36 | EnvironmentParameters environmentParameters = AuthUtils.CurrentEnvironmentParameters; 37 | 38 | // Create auth context that we will use to connect to the AAD endpoint 39 | AuthenticationContext authContext = new AuthenticationContext(environmentParameters.AuthUrl); 40 | 41 | if (useAdminConsentFlow) 42 | { 43 | // Remove this user's token from the token cache so they have to log in again (we must use the "Auto" Prompt behavior to add query parameters) 44 | SdkAuthResult currentLogin = AuthUtils.LatestAdalAuthResult; 45 | if (currentLogin != null) 46 | { 47 | // Find all the items in the cache with the logged in user ID, client ID and resource ID 48 | IEnumerable toRemove = authContext.TokenCache.ReadItems() 49 | .Where( 50 | tokenCacheItem => tokenCacheItem.UniqueId == currentLogin.UserUniqueId 51 | && tokenCacheItem.ClientId == environmentParameters.AppId 52 | && tokenCacheItem.Resource == environmentParameters.ResourceId); 53 | 54 | // Remove the items 55 | foreach (TokenCacheItem tokenCacheItem in toRemove) 56 | { 57 | authContext.TokenCache.DeleteItem(tokenCacheItem); 58 | } 59 | } 60 | } 61 | 62 | // Get the device code 63 | DeviceCodeResult deviceCodeResult = authContext.AcquireDeviceCodeAsync( 64 | environmentParameters.ResourceId, 65 | environmentParameters.AppId, 66 | useAdminConsentFlow ? AuthUtils.AdminConsentQueryParameter : null) 67 | .GetAwaiter().GetResult(); 68 | 69 | // Display the device code 70 | displayDeviceCodeMessageToUser(deviceCodeResult.Message); 71 | 72 | // Get the auth token 73 | //TODO: Figure out why this call hangs and crashes the PowerShell session if the first login was cancelled and the second login times out 74 | AuthenticationResult authenticationResult = authContext.AcquireTokenByDeviceCodeAsync(deviceCodeResult) 75 | .GetAwaiter().GetResult(); 76 | 77 | // Convert the auth result into our own type 78 | SdkAuthResult authResult = authenticationResult.ToSdkAuthResult(); 79 | 80 | // Save the auth result 81 | AuthUtils.LatestAdalAuthResult = authResult; 82 | 83 | return authResult; 84 | } 85 | } 86 | } 87 | 88 | #endif 89 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Utils/CmdletUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Management.Automation; 9 | using System.Reflection; 10 | 11 | internal static class CmdletUtils 12 | { 13 | /// 14 | /// Gets the noun part of a cmdlet's name. 15 | /// 16 | /// The cmdlet 17 | /// The noun part of the cmdlet's name 18 | internal static string GetCmdletNoun(this Cmdlet cmdlet) 19 | { 20 | if (cmdlet == null) 21 | { 22 | throw new ArgumentNullException(nameof(cmdlet)); 23 | } 24 | 25 | return cmdlet.GetType().GetCustomAttribute()?.NounName; 26 | } 27 | 28 | /// 29 | /// Gets the properties that are bound (set by the user) in the current invocation of this cmdlet. 30 | /// 31 | /// The cmdlet to get the properties from 32 | /// Whether or not to include inherited properties 33 | /// The properties that are bound in the current invocation of this cmdlet. 34 | internal static IEnumerable GetBoundProperties(this PSCmdlet cmdlet, bool includeInherited = true) 35 | { 36 | // Get the cmdlet's properties 37 | IEnumerable cmdletProperties = cmdlet.GetProperties(includeInherited); 38 | 39 | // Get only the properties that were set from PowerShell 40 | IEnumerable boundParameterNames = cmdlet.MyInvocation.BoundParameters.Keys; 41 | IEnumerable boundProperties = cmdletProperties.Where(prop => 42 | boundParameterNames.Contains(prop.Name) || 43 | prop.GetCustomAttribute()?.AliasNames?.Intersect(boundParameterNames)?.Any() == true); 44 | 45 | return boundProperties; 46 | } 47 | 48 | /// 49 | /// Gets all the properties declared on this class. 50 | /// 51 | /// The cmdlet to get the properties from 52 | /// Whether or not to include inherited properties (defaults to true) 53 | /// The properties that are defined on this cmdlet. 54 | internal static IEnumerable GetProperties(this PSCmdlet cmdlet, bool includeInherited) 55 | { 56 | // Create the binding flags 57 | BindingFlags bindingFlags = 58 | BindingFlags.Instance | // ignore static/const properties 59 | BindingFlags.Public; // only include public properties 60 | if (!includeInherited) 61 | { 62 | bindingFlags |= BindingFlags.DeclaredOnly; // ignore inherited properties 63 | } 64 | 65 | // Get the properties on this cmdlet 66 | IEnumerable result = cmdlet.GetType().GetProperties(bindingFlags); 67 | 68 | return result; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Utils/ExceptionUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets.Utils 4 | { 5 | using System; 6 | using System.Management.Automation; 7 | 8 | internal static class ExceptionUtils 9 | { 10 | /// 11 | /// Writes an exception to the PowerShell console. If the exception does not represent a PowerShell error, 12 | /// it will be wrapped in a PowerShell error object before being written to the console. 13 | /// 14 | /// The cmdlet which is writing the error 15 | /// The exception to write to the console 16 | internal static void WriteError(this Cmdlet cmdlet, Exception ex) 17 | { 18 | ErrorRecord errorRecord; 19 | if (ex is IContainsErrorRecord powerShellError) 20 | { 21 | errorRecord = powerShellError.ErrorRecord; 22 | } 23 | else 24 | { 25 | errorRecord = new ErrorRecord( 26 | ex, 27 | PSGraphSDKException.ErrorPrefix + "UnknownError", 28 | ErrorCategory.OperationStopped, 29 | null); 30 | } 31 | 32 | cmdlet.WriteError(errorRecord); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Utils/ReferencePathGenerator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Reflection; 9 | using PowerShellGraphSDK.PowerShellCmdlets; 10 | 11 | internal class ReferencePathGenerator 12 | { 13 | /// 14 | /// The cache of cmdlet nouns to objects. 15 | /// 16 | private static IDictionary Cache { get; } = new Dictionary(); 17 | 18 | /// 19 | /// An instance of the cmdlet type that we should use to get the resource URL. 20 | /// 21 | private readonly ODataCmdletBase _cmdletInstance; 22 | 23 | /// 24 | /// The "id" property on the cmdlet instance that we need to set before getting the resource URL. 25 | /// 26 | private readonly PropertyInfo _idProperty; 27 | 28 | /// 29 | /// The URL placeholder properties on the cmdlet instance that we need to set before getting the resource URL. 30 | /// 31 | private readonly IEnumerable _placeholderProperties; 32 | 33 | internal ReferencePathGenerator(ODataCmdletBase cmdletInstance) 34 | { 35 | this._cmdletInstance = cmdletInstance ?? throw new ArgumentNullException(nameof(cmdletInstance)); 36 | 37 | // Get the type of this cmdlet 38 | Type cmdletType = this._cmdletInstance.GetType(); 39 | 40 | // Get the "id" property 41 | this._idProperty = cmdletType.GetProperties() 42 | .Where(prop => prop.GetCustomAttribute() != null) 43 | .FirstOrDefault(); 44 | 45 | // Get the placeholder properties 46 | this._placeholderProperties = cmdletType.GetProperties() 47 | .Where(prop => 48 | // ID properties (except the entity ID property that we just retrieved) 49 | (prop != this._idProperty && prop.GetCustomAttribute() != null) 50 | // Type cast properties 51 | || prop.GetCustomAttribute() != null); 52 | } 53 | 54 | internal static void AddToCache(string cmdletNoun, ReferencePathGenerator referencePathGenerator) 55 | { 56 | if (string.IsNullOrEmpty(cmdletNoun)) 57 | { 58 | throw new ArgumentException("Cmdlet noun cannot be null or empty", nameof(cmdletNoun)); 59 | } 60 | if (referencePathGenerator == null) 61 | { 62 | throw new ArgumentNullException(nameof(referencePathGenerator)); 63 | } 64 | 65 | Cache[cmdletNoun] = referencePathGenerator; 66 | } 67 | 68 | internal static bool TryGetFromCache(string cmdletNoun, out ReferencePathGenerator referencePathGenerator) 69 | { 70 | if (string.IsNullOrEmpty(cmdletNoun)) 71 | { 72 | throw new ArgumentException("Cmdlet noun cannot be null or empty", nameof(cmdletNoun)); 73 | } 74 | 75 | return Cache.TryGetValue(cmdletNoun, out referencePathGenerator); 76 | } 77 | 78 | /// 79 | /// Generates a resource path from the given object ID. 80 | /// 81 | /// The currently running cmdlet (which has the properties that represent URL placeholders) 82 | /// The ID of the object being referenced 83 | /// The generated URL. 84 | internal string GenerateResourcePath(ODataCmdletBase currentCmdlet, string id) 85 | { 86 | // Set the entity ID 87 | this._idProperty?.SetValue(this._cmdletInstance, id); 88 | 89 | // Set the placeholder properties 90 | foreach (PropertyInfo property in this._placeholderProperties) 91 | { 92 | // Get the equivalent property on the current cmdlet (if the type is different) 93 | PropertyInfo currentCmdletProperty = property; 94 | Type currentCmdletType = currentCmdlet.GetType(); 95 | if (currentCmdletType != this._cmdletInstance.GetType()) 96 | { 97 | // The property name and type must match 98 | currentCmdletProperty = currentCmdletType.GetProperty(property.Name, property.PropertyType); 99 | } 100 | 101 | // Get the value from the currently running cmdlet 102 | object propertyValue = currentCmdletProperty.GetValue(currentCmdlet); 103 | 104 | // Set the cached cmdlet instance's equivalent property to the same value 105 | property.SetValue(this._cmdletInstance, propertyValue); 106 | } 107 | 108 | // Create the relative resource path 109 | string path = this._cmdletInstance.GetResourcePath(); 110 | 111 | return path; 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Common/Utils/SdkAuthResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK 4 | { 5 | using System; 6 | using System.Net.Http.Headers; 7 | 8 | internal class SdkAuthResult 9 | { 10 | internal string AccessTokenType { get; } 11 | 12 | internal string AccessToken { get; } 13 | 14 | internal object PSUserDisplayableInformation { get; } 15 | 16 | internal AuthenticationHeaderValue AuthenticationHeaderValue { get; } 17 | 18 | internal string UserUniqueId { get; } 19 | 20 | private DateTimeOffset ExpiresOn { get; } 21 | 22 | internal bool IsExpired => (ExpiresOn <= DateTimeOffset.Now); 23 | 24 | internal SdkAuthResult(string accessTokenType, string accessToken, string userId, DateTimeOffset expiresOn, object psUserDisplayableInformation = null) 25 | { 26 | this.AccessTokenType = accessTokenType ?? throw new ArgumentNullException(nameof(accessTokenType)); 27 | this.AccessToken = accessToken ?? throw new ArgumentNullException(nameof(accessToken)); 28 | this.UserUniqueId = userId; 29 | this.AuthenticationHeaderValue = new AuthenticationHeaderValue(accessTokenType, accessToken); 30 | this.PSUserDisplayableInformation = psUserDisplayableInformation; 31 | this.ExpiresOn = expiresOn; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/ActionCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Net.Http; 8 | using System.Reflection; 9 | 10 | /// 11 | /// The common behavior between all OData PowerShell SDK cmdlets that call actions on OData resources. 12 | /// 13 | public abstract class ActionCmdlet : ODataCmdletBase 14 | { 15 | internal override string GetHttpMethod() 16 | { 17 | return "POST"; 18 | } 19 | 20 | internal override object GetContent() 21 | { 22 | // Get the properties that were set by the user in this invocation of the PowerShell cmdlet 23 | IEnumerable boundProperties = this.GetBoundProperties(includeInherited: false) 24 | // Make sure all the properties have an [ODataType] attribute 25 | .Where(prop => prop.GetCustomAttribute() != null); 26 | 27 | // Create the JSON string 28 | string jsonBody = this.WriteJsonFromProperties(boundProperties); 29 | 30 | return jsonBody; 31 | } 32 | 33 | internal override HttpContent WriteContent(object content) 34 | { 35 | // This should already be a serialized JSON string (provided by the GetContent() method) 36 | 37 | return content is string stringContent ? new StringContent(stringContent) : null; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/DeleteCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that remove OData resources. 7 | /// 8 | public abstract class DeleteCmdlet : ODataCmdletBase 9 | { 10 | internal override string GetHttpMethod() 11 | { 12 | return "DELETE"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/FunctionReturningCollectionCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that call OData functions that return a collection of entities. 7 | /// 8 | public abstract class FunctionReturningCollectionCmdlet : GetOrSearchCmdlet 9 | { 10 | // TODO: Allow dynamic parameters once the generator supports them 11 | /// 12 | /// Creates a new . 13 | /// 14 | public FunctionReturningCollectionCmdlet() 15 | { 16 | this.DynamicParameters = null; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/FunctionReturningEntityCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that call OData functions that return a single entity. 7 | /// 8 | public abstract class FunctionReturningEntityCmdlet : GetCmdlet 9 | { 10 | // TODO: Allow dynamic parameters once the generator supports them 11 | /// 12 | /// Creates a new . 13 | /// 14 | public FunctionReturningEntityCmdlet() 15 | { 16 | this.DynamicParameters = null; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/GetStreamCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that retrieve data streams. 7 | /// 8 | public abstract class GetStreamCmdlet : ODataCmdletBase 9 | { 10 | internal override object ReadResponse(string content) 11 | { 12 | return content; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/ODataCmdletBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Management.Automation; 8 | using System.Net.Http; 9 | using PowerShellGraphSDK.PowerShellCmdlets.Utils; 10 | 11 | /// 12 | /// The common behavior between all OData PowerShell SDK cmdlets. 13 | /// 14 | /// 15 | /// Overridable methods are executed in this order: 16 | /// 17 | /// 18 | /// Method 19 | /// Description 20 | /// 21 | /// 22 | /// 23 | /// Gets the HTTP method to use when making the call 24 | /// 25 | /// 26 | /// 27 | /// Gets the relative URL of the OData resource 28 | /// 29 | /// 30 | /// 31 | /// Gets the query options for the call 32 | /// 33 | /// 34 | /// 35 | /// Gets the MIME type for the content in the request body 36 | /// 37 | /// 38 | /// 39 | /// Gets the request body for the HTTP call 40 | /// 41 | /// 42 | /// 43 | /// Gets the request headers to be added to the HTTP call 44 | /// 45 | /// 46 | /// 47 | /// Determines whether or not to proceed with the call 48 | /// 49 | /// 50 | /// 51 | /// Creates an object from the result of 52 | /// 53 | /// 54 | /// 55 | /// Converts the HTTP response body into a native PowerShell object 56 | /// 57 | /// 58 | /// 59 | public abstract partial class ODataCmdletBase : PSCmdlet, IDynamicParameters 60 | { 61 | /// 62 | /// The name of this assembly. 63 | /// 64 | private readonly string AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; 65 | 66 | /// 67 | /// The version of this assembly. 68 | /// 69 | private readonly string AssemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); 70 | 71 | /// 72 | /// The defined dynamic parameters. 73 | /// 74 | protected RuntimeDefinedParameterDictionary DynamicParameters = new RuntimeDefinedParameterDictionary(); 75 | 76 | /// 77 | /// The method that the PowerShell runtime will call. This is the entry point for the cmdlet. 78 | /// 79 | protected override sealed void ProcessRecord() 80 | { 81 | this.Run(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/ObjectFactoryCmdletBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Management.Automation; 9 | using System.Reflection; 10 | using PowerShellGraphSDK; 11 | using PowerShellGraphSDK.PowerShellCmdlets.Utils; 12 | 13 | /// 14 | /// The common behavior between all cmdlets that are used to create PowerShell objects which represent entities in the OData schema. 15 | /// 16 | public abstract class ObjectFactoryCmdletBase : PSCmdlet 17 | { 18 | /// 19 | /// The method that the PowerShell runtime will call. This is the entry point for the cmdlet. 20 | /// 21 | protected override void ProcessRecord() 22 | { 23 | try 24 | { 25 | // Try to run the cmdlet behavior 26 | this.Run(); 27 | } 28 | catch (Exception ex) 29 | { 30 | // Write any errors to the console 31 | this.WriteError(ex); 32 | } 33 | } 34 | 35 | private void Run() 36 | { 37 | // Get the bound properties for this cmdlet 38 | IEnumerable boundProperties = this.GetBoundProperties(); 39 | 40 | // Iterate over each property 41 | IDictionary resultProperties = new Dictionary(); 42 | foreach (PropertyInfo property in boundProperties) 43 | { 44 | // Check if this is an OData type selector switch property 45 | if (IsODataTypeSelectorSwitch(property, out string selectedODataType)) 46 | { 47 | // Make sure that we don't allow more than 1 parameter set selector to be applied by the user 48 | if (resultProperties.ContainsKey(ODataConstants.RequestProperties.ODataType)) 49 | { 50 | // Throw an error if we found more than 1 type selector property provided by the user (the PowerShell runtime should never allow this to happen) 51 | IEnumerable oDataTypeProperties = boundProperties.Where(prop => IsODataTypeSelectorSwitch(prop, out string temp)); 52 | throw new PSArgumentException($"Only one type selector switch may be applied at a time. The following type selector switch parameters were applied: {string.Join(", ", oDataTypeProperties.Select(type => $"\"type\""))}"); 53 | } 54 | else 55 | { 56 | // This is the first time we've seen an OData type selector switch property, so add an "@odata.type" property to the result object 57 | resultProperties.Add(ODataConstants.RequestProperties.ODataType, selectedODataType); 58 | } 59 | } 60 | else 61 | { 62 | // Get the value of the property 63 | object value = property.GetValue(this); 64 | 65 | // TODO: Convert the property value into something that can be serialized as JSON 66 | // This currently only satisfies the case where the property is a byte array - it does not satisfy other cases such as nested objects 67 | if (value is byte[] bytes) 68 | { 69 | value = System.Convert.ToBase64String(bytes); 70 | } 71 | 72 | // Add the serializable value as a property in the result object 73 | resultProperties.Add(property.Name, value); 74 | } 75 | } 76 | 77 | // If there is no "@odata.type" property, add one based on the ODataType attribute applied to this class 78 | if (!resultProperties.ContainsKey(ODataConstants.RequestProperties.ODataType)) 79 | { 80 | string selectedODataType = this.GetType().GetCustomAttribute()?.TypeFullName; 81 | if (selectedODataType != null) 82 | { 83 | resultProperties.Add(ODataConstants.RequestProperties.ODataType, "#" + selectedODataType); 84 | } 85 | } 86 | 87 | // Convert to a PowerShell object 88 | object result = resultProperties.ToPowerShellObject(); 89 | 90 | // Send the object to the pipeline 91 | this.WriteObject(result); 92 | } 93 | 94 | /// 95 | /// Determines whether a given property is a parameter set switch which selects the OData type. 96 | /// 97 | /// The property 98 | /// The OData type that this switch would select 99 | /// True if the given property is a OData type selector switch, otherwise false. 100 | private bool IsODataTypeSelectorSwitch(PropertyInfo property, out string selectedParameterSet) 101 | { 102 | return 103 | // Prepend the type name with a "#" and set it as the result 104 | (selectedParameterSet = property.GetCustomAttribute()?.ParameterSetName?.Insert(0, "#")) != null && 105 | // If this property has the ParameterSetSelector attribute, make sure it is also a SwitchParameter 106 | property.PropertyType == typeof(SwitchParameter); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/PatchCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that update OData resources. 7 | /// 8 | public abstract class PatchCmdlet : PostOrPatchCmdlet 9 | { 10 | internal override string GetHttpMethod() 11 | { 12 | return "PATCH"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/PostCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System.Management.Automation; 6 | 7 | /// 8 | /// The common behavior between all OData PowerShell SDK cmdlets that create OData resources. 9 | /// 10 | public abstract class PostCmdlet : PostOrPatchCmdlet 11 | { 12 | internal override string GetHttpMethod() 13 | { 14 | return "POST"; 15 | } 16 | 17 | internal override object ReadResponse(string content) 18 | { 19 | // Convert the string content into a C# object 20 | object result = base.ReadResponse(content); 21 | 22 | // Check if this is a JSON response 23 | if (result is PSObject response) 24 | { 25 | // Process the result object 26 | this.ProcessResultObject(result); 27 | } 28 | 29 | return result; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/PostReferenceToCollectionCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that create references from an OData resource to a collection. 7 | /// 8 | public abstract class PostReferenceToCollectionCmdlet : ODataCmdletBase 9 | { 10 | internal override string GetHttpMethod() 11 | { 12 | return "POST"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/PutReferenceToEntityCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | /// 6 | /// The common behavior between all OData PowerShell SDK cmdlets that create references from an OData resource to a single entity. 7 | /// 8 | public abstract class PutReferenceToEntityCmdlet : ODataCmdletBase 9 | { 10 | internal override string GetHttpMethod() 11 | { 12 | return "PUT"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/UpdateStreamCmdlet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System.Management.Automation; 6 | 7 | /// 8 | /// The common behavior between all OData PowerShell SDK cmdlets that update a stream. 9 | /// 10 | public abstract class UpdateStreamCmdlet : ODataCmdletBase 11 | { 12 | /// 13 | /// The new data. 14 | /// 15 | [Parameter(Mandatory = true)] 16 | [ValidateNotNullOrEmpty] 17 | public string Data { get; set; } 18 | 19 | /// 20 | /// The MIME type (content type) of the data. See https://technet.microsoft.com/en-us/library/cc995276.aspx for a list of MIME types. 21 | /// 22 | [Parameter(Mandatory = true)] 23 | [ValidateNotNullOrEmpty] 24 | public string ContentType { get; set; } 25 | 26 | internal override string GetHttpMethod() 27 | { 28 | return "PUT"; 29 | } 30 | 31 | internal override object GetContent() 32 | { 33 | return this.Data; 34 | } 35 | 36 | internal override string GetContentType() 37 | { 38 | return this.ContentType; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellCmdlets/Utils/ModuleInitializer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. 2 | 3 | namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Management.Automation; 9 | using System.Reflection; 10 | 11 | /// 12 | /// This is a required hack. 13 | /// We have to set the output type of this project to "Exe", otherwise dependencies are not copied to the output folder. 14 | /// There is a target in the *.csproj to rename the exe to a dll in order to get the regular behavior back. 15 | /// 16 | static class MainClass 17 | { 18 | static void Main(string[] args) 19 | { 20 | throw new Exception("Do not call this as an executable"); 21 | } 22 | } 23 | 24 | /// 25 | /// Initializes this PowerShell module. 26 | /// 27 | public class ModuleInitializer : IModuleAssemblyInitializer 28 | { 29 | /// 30 | /// The initialization logic for this PowerShell module. 31 | /// 32 | public void OnImport() 33 | { 34 | InitReferenceUrlGeneratorCache(); 35 | } 36 | 37 | /// 38 | /// Creates the reference URL generator cache. 39 | /// 40 | private void InitReferenceUrlGeneratorCache() 41 | { 42 | // Get all the types in this assembly 43 | IEnumerable allTypes = Assembly.GetExecutingAssembly().GetExportedTypes(); 44 | 45 | // Get all the cmdlets that return resources (i.e. not "$ref", function or action cmdlets) 46 | IEnumerable referenceableCmdletTypes = allTypes 47 | // Select only the types that represent "$ref" cmdlets 48 | .Where(type => type.IsClass && !type.IsAbstract 49 | // Is a "GET" cmdlet that returns resources that can be referenced 50 | && typeof(GetCmdlet).IsAssignableFrom(type) && type.GetCustomAttribute() != null); 51 | 52 | // For each "GET" cmdlet, create a mapping to a ReferencePathGenerator 53 | foreach (Type cmdletType in referenceableCmdletTypes) 54 | { 55 | // Construct an instance of the cmdlet 56 | object constructedCmdlet = cmdletType 57 | .GetConstructor(Array.Empty())? 58 | .Invoke(Array.Empty()); 59 | 60 | // Make sure we were able to construct an instance of the cmdlet 61 | if (constructedCmdlet is ODataCmdletBase cmdlet) 62 | { 63 | // Get this cmdlet name's noun 64 | string cmdletNoun = cmdlet.GetCmdletNoun(); 65 | 66 | // Create the URL generator 67 | ReferencePathGenerator urlGenerator = new ReferencePathGenerator(cmdlet); 68 | 69 | // Add the mapping 70 | ReferencePathGenerator.AddToCache(cmdletNoun, urlGenerator); 71 | } 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellGraphSDK.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Library 5 | 6.1907.1.0 6 | Rajesh Soy, Rohit Ramu 7 | Microsoft Corporation 8 | Microsoft Intune Graph PowerShell Client SDK 9 | Copyright © Microsoft Corporation 2018 10 | Microsoft.Intune.PowerShellGraphSDK 11 | Microsoft.Intune.PowerShellGraphSDK 12 | true 13 | PackageReference 14 | true 15 | IDE0037;IDE1006 16 | true 17 | net471 18 | Release 19 | 20 | 21 | 22 | Microsoft.Graph.Intune 23 | powershell.exe 24 | $(MSBuildProjectDirectory)\Scripts\generateModuleManifest.ps1 25 | 26 | 27 | 28 | netstandard2.0 29 | 30 | 31 | $(WindowsTargetFramework);netstandard2.0 32 | 33 | 34 | 35 | full 36 | true 37 | 38 | 39 | none 40 | false 41 | 42 | 43 | 44 | 45 | 46 | 47 | all 48 | runtime; build; native; contentfiles; analyzers 49 | 50 | 51 | 52 | 53 | NETSTANDARD 54 | 55 | 56 | 57 | 58 | 59 | 60 | NETFRAMEWORK 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | $(MSBuildProjectDirectory)\bin\$(Configuration); $(MSBuildProjectDirectory)\obj 70 | 71 | 72 | <_REMOVE_DIRS Include="$(REMOVE_DIRS)" /> 73 | 74 | 75 | 76 | 77 | 78 | 79 | $(MSBuildProjectDirectory)\PowerShellModuleAdditions 80 | 81 | 82 | <_POWERSHELL_EXTRAS Include="$(POWERSHELL_EXTRAS)\**\*" /> 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellGraphSDK.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2015 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PowerShellGraphSDK", "PowerShellGraphSDK.csproj", "{0673FFAA-23A8-4BF5-B670-03A41FBD066D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {0673FFAA-23A8-4BF5-B670-03A41FBD066D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {0673FFAA-23A8-4BF5-B670-03A41FBD066D}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {0673FFAA-23A8-4BF5-B670-03A41FBD066D}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {0673FFAA-23A8-4BF5-B670-03A41FBD066D}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {E45802D0-583B-4A6F-B149-467F7DDBF338} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellModuleAdditions/CustomModules/AliasCmdlets.psm1: -------------------------------------------------------------------------------- 1 | function Set-MSGraphAlias { 2 | [CmdletBinding()] 3 | param ( 4 | [Parameter()] 5 | [ValidateNotNullOrEmpty()] 6 | [string]$Module = 'Intune', 7 | 8 | [Parameter()] 9 | [switch]$PassThru 10 | ) 11 | 12 | $newcmds = Get-Command -Module $Module | ForEach-Object {@{ 13 | Name = $_.Name 14 | Verb = $_.Verb 15 | Noun = $_.Noun 16 | NewNoun = $_.Noun 17 | }} 18 | $rep = [Ordered]@{ 19 | ManagedDeviceMobileApp = "MDMA" 20 | ManagedAppRegistrations = "MAR" 21 | MediaContentRating = "MCR" 22 | DeviceCompliancePolicies = "DCP" 23 | DeviceCompliancePolicy = "DCP" 24 | DeviceAppManagement ="DAM" 25 | DeviceManagement = "DM" 26 | ManagedDevs = "MgDev" 27 | Status = "Stat" 28 | Device = "Dev" 29 | Configuration = "Cfg" 30 | Managed = "Mgd" 31 | Management = "Mgt" 32 | Compliance = "Cmp" 33 | Targeted = "Tgt" 34 | Target = "Tgt" 35 | Windows = "Win" 36 | TermsAndConditions = "TnC" 37 | Information = "Info" 38 | OperatingSystem = "OS" 39 | Object = "Obj" 40 | Protections = "Prot" 41 | Protection = "Prot" 42 | Policies = "Pol" 43 | Message = "Msg" 44 | Template = "Tpl" 45 | Registrations = "Reg" 46 | Operations = "Op" 47 | Summaries = "Sum" 48 | Summary = "Sum" 49 | Default = "Def" 50 | Reference = "Ref" 51 | Security = "Sec" 52 | Availability = "Avail" 53 | Deployment = "Dep" 54 | Categories = "Cat" 55 | Mobile = "Mob" 56 | Scheduled = "Sched" 57 | Actions = "Act" 58 | Events = "Evt" 59 | Definitions = "Dfn" 60 | Software = "SW" 61 | Notification = "Notif" 62 | Connectors = "Conn" 63 | Workbook = "Wbk" 64 | } 65 | foreach ($c in $newcmds) { 66 | $c.newNoun = $c.Noun 67 | foreach ($k in $rep.Keys) 68 | { 69 | if ($c.Noun -match $k) 70 | { 71 | $c.NewNoun = $c.NewNoun -replace $k, $rep.$k 72 | } 73 | } 74 | } 75 | 76 | # Set aliases 77 | $newcmds | ForEach-Object { 78 | $oldName = $_.Name 79 | $newName = "$($_.Verb)-$($_.NewNoun)" 80 | 81 | Set-Alias -Name $newName -Value $oldName -Scope Global 82 | 83 | if ($PassThru) { 84 | $info = [PSCustomObject]@{ 85 | Command = $oldName 86 | Alias = $newName 87 | } 88 | Write-Output $info 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellModuleAdditions/CustomModules/UtilCmdlets.psm1: -------------------------------------------------------------------------------- 1 | [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope='Function', Target='Get-MSGraphAllPages')] 2 | param() 3 | 4 | function Get-MSGraphDebugInfo { 5 | if ($global:error.Count -eq 0) { 6 | Write-Information 'No errors found' 7 | } else { 8 | $myError = $global:error[0].TargetObject 9 | if (-not $myError) { 10 | Write-Warning 'No debugging information found for the most recent error' 11 | } else { 12 | $myError | Write-Output 13 | } 14 | } 15 | } 16 | 17 | function Get-MSGraphAllPages { 18 | [CmdletBinding( 19 | ConfirmImpact = 'Medium', 20 | DefaultParameterSetName = 'SearchResult' 21 | )] 22 | param ( 23 | [Parameter(Mandatory = $true, ParameterSetName = 'NextLink', ValueFromPipelineByPropertyName = $true)] 24 | [ValidateNotNullOrEmpty()] 25 | [Alias('@odata.nextLink')] 26 | [string]$NextLink, 27 | 28 | [Parameter(Mandatory = $true, ParameterSetName = 'SearchResult', ValueFromPipeline = $true)] 29 | [ValidateNotNull()] 30 | [PSObject]$SearchResult 31 | ) 32 | 33 | begin {} 34 | 35 | process { 36 | if ($PSCmdlet.ParameterSetName -eq 'SearchResult') { 37 | # Set the current page to the search result provided 38 | $page = $SearchResult 39 | 40 | # Extract the NextLink 41 | $currentNextLink = $page.'@odata.nextLink' 42 | 43 | # We know this is a wrapper object if it has an "@odata.context" property 44 | if (Get-Member -InputObject $page -Name '@odata.context' -Membertype Properties) { 45 | $values = $page.value 46 | } else { 47 | $values = $page 48 | } 49 | 50 | # Output the values 51 | if ($values) { 52 | $values | Write-Output 53 | } 54 | } 55 | 56 | while (-Not ([string]::IsNullOrWhiteSpace($currentNextLink))) 57 | { 58 | # Make the call to get the next page 59 | try { 60 | $page = Get-MSGraphNextPage -NextLink $currentNextLink 61 | } catch { 62 | throw 63 | } 64 | 65 | # Extract the NextLink 66 | $currentNextLink = $page.'@odata.nextLink' 67 | 68 | # Output the items in the page 69 | $values = $page.value 70 | if ($values) { 71 | $values | Write-Output 72 | } 73 | } 74 | } 75 | 76 | end {} 77 | } -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellModuleAdditions/LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | Third Party Programs: The software may include third party programs that 24 | Microsoft, not the third party, licenses to you under this agreement. Notices, 25 | if any, for the third party programs are included for your information only. -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/PowerShellModuleAdditions/README.md: -------------------------------------------------------------------------------- 1 | # PowerShellModuleAdditions 2 | Allows the generated cmdlets to be augmented with custom hand-crafted cmdlets. 3 | 4 | In order to add a new set of PowerShell cmdlets: 5 | 1. Add hand-crafted cmdlets to the 'CustomModules' folder in a '.psm1' file 6 | - Create subfolders to organize these '.psm1' files 7 | 2. Add the relative path of the new file as an entry at the bottom of the 'PowerShellGraphSDK.psd1' file in the 'NestedModules' array -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("GraphODataPowerShellSDKWriter")] -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/Apps.psm1: -------------------------------------------------------------------------------- 1 | function Get-MobileApp { 2 | [CmdletBinding(DefaultParameterSetName='__AllParameterSets')] 3 | param( 4 | [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName='GetSingleApp')] 5 | [ValidateNotNullOrEmpty()] 6 | [string]$mobileAppId 7 | ) 8 | 9 | if ($PSCmdlet.ParameterSetName -eq 'GetSingleApp') { 10 | Get-IntuneMobileApp -mobileAppId $mobileAppId 11 | } else { 12 | Get-IntuneMobileApp | Get-MSGraphAllPages 13 | } 14 | } -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/Microsoft.Graph.Intune.Apps.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'Microsoft.Graph.Intune.Apps' 3 | # 4 | # Generated by: Microsoft Corporation 5 | # 6 | # Generated on: 9/19/2018 7 | # 8 | 9 | @{ 10 | 11 | # Script module or binary module file associated with this manifest. 12 | RootModule = '.\Apps.psm1' 13 | 14 | # Version number of this module. 15 | ModuleVersion = '6.1810.0.0' 16 | 17 | # Supported PSEditions 18 | # CompatiblePSEditions = @() 19 | 20 | # ID used to uniquely identify this module 21 | GUID = '9C123876-61CF-419B-A889-FF5BA18B1049' 22 | 23 | # Author of this module 24 | Author = 'Microsoft Corporation' 25 | 26 | # Company or vendor of this module 27 | CompanyName = 'Microsoft Corporation' 28 | 29 | # Copyright statement for this module 30 | Copyright = '(c) 2018 Microsoft. All rights reserved.' 31 | 32 | # Description of the functionality provided by this module 33 | Description = 'PowerShell cmdlets for managing applications with Microsoft Intune' 34 | 35 | # Minimum version of the Windows PowerShell engine required by this module 36 | # PowerShellVersion = '' 37 | 38 | # Name of the Windows PowerShell host required by this module 39 | # PowerShellHostName = '' 40 | 41 | # Minimum version of the Windows PowerShell host required by this module 42 | # PowerShellHostVersion = '' 43 | 44 | # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 45 | # DotNetFrameworkVersion = '' 46 | 47 | # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 48 | # CLRVersion = '' 49 | 50 | # Processor architecture (None, X86, Amd64) required by this module 51 | # ProcessorArchitecture = '' 52 | 53 | # Modules that must be imported into the global environment prior to importing this module 54 | # RequiredModules = @() 55 | 56 | # Assemblies that must be loaded prior to importing this module 57 | # RequiredAssemblies = @() 58 | 59 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 60 | # ScriptsToProcess = @() 61 | 62 | # Type files (.ps1xml) to be loaded when importing this module 63 | # TypesToProcess = @() 64 | 65 | # Format files (.ps1xml) to be loaded when importing this module 66 | # FormatsToProcess = @() 67 | 68 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 69 | NestedModules = @('.\UploadLobApp.psm1') 70 | 71 | # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. 72 | FunctionsToExport = '*' 73 | 74 | # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. 75 | CmdletsToExport = '*' 76 | 77 | # Variables to export from this module 78 | # VariablesToExport = @() 79 | 80 | # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. 81 | AliasesToExport = '*' 82 | 83 | # DSC resources to export from this module 84 | # DscResourcesToExport = @() 85 | 86 | # List of all modules packaged with this module 87 | # ModuleList = @() 88 | 89 | # List of all files packaged with this module 90 | # FileList = @() 91 | 92 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. 93 | PrivateData = @{ 94 | 95 | PSData = @{ 96 | 97 | # Tags applied to this module. These help with module discovery in online galleries. 98 | Tags = 'Microsoft', 'Microsoft Graph', 'Graph', 'Microsoft Intune', 'Intune', 'Applications', 'Apps' 99 | 100 | # A URL to the license for this module. 101 | LicenseUri = 'https://github.com/Microsoft/Intune-PowerShell-Management/blob/master/LICENSE-CODE' 102 | 103 | # A URL to the main website for this project. 104 | ProjectUri = 'https://github.com/Microsoft/Intune-PowerShell-Management' 105 | 106 | # A URL to an icon representing this module. 107 | # IconUri = '' 108 | 109 | # ReleaseNotes of this module 110 | # ReleaseNotes = '' 111 | 112 | } # End of PSData hashtable 113 | 114 | } # End of PrivateData hashtable 115 | 116 | # HelpInfo URI of this module 117 | # HelpInfoURI = '' 118 | 119 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 120 | # DefaultCommandPrefix = '' 121 | 122 | } 123 | 124 | -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/UploadIOSLobApp.ps1: -------------------------------------------------------------------------------- 1 | Import-Module (Join-Path -Path $PSScriptRoot -ChildPath 'UploadLobApp.psm1') 2 | 3 | # Create the object that contains information about the app 4 | $appToUpload = New-MobileAppObject ` 5 | -iosLobApp ` 6 | -displayName 'Test' ` 7 | -description 'This is a test iOS LOB app' ` 8 | -publisher 'IT Professional' ` 9 | -bundleId '' ` 10 | -applicableDeviceType (New-IosDeviceTypeObject -iPad $true -iPhoneAndIPod $true) ` 11 | -minimumSupportedOperatingSystem (New-IosMinimumOperatingSystemObject -v9_0 $true) ` 12 | -fileName 'test.ipa' ` 13 | -buildNumber 'v1' -versionNumber 'v1' -expirationDateTime ((Get-Date).AddDays(90)) 14 | 15 | # Upload the app file with the app information 16 | # !! Set $filePath to the path to your *.ipa file !! 17 | $filePath = Join-Path -Path $PSScriptRoot -ChildPath 'test.ipa' 18 | $createdApp = New-LobApp ` 19 | -filePath $filePath ` 20 | -mobileApp $appToUpload 21 | 22 | Write-Output $createdApp -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/VisualizeData.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param( 3 | [ValidateNotNullOrEmpty()] 4 | [string]$Title, 5 | 6 | [ValidateSet('Pie', 'Bar', 'Column')] 7 | [string]$ChartType, 8 | 9 | [string]$XLabel, 10 | 11 | [string]$YLabel, 12 | 13 | [ValidateNotNull()] 14 | [object[]]$XValues, 15 | 16 | [ValidateNotNull()] 17 | [object[]]$YValues 18 | ) 19 | 20 | if ($XValues.Length -ne $YValues.Length) { 21 | throw "Number of X ($($XValues.Length)) values must equal number of Y values ($($YValues.Length))" 22 | } 23 | 24 | [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null 25 | [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") | Out-Null 26 | 27 | # Create a chart object 28 | $chart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart 29 | $chart.Width = 500 30 | $chart.Height = 500 31 | $chart.Left = 40 32 | $chart.Top = 30 33 | 34 | # Create a ChartArea to draw on and add it to chart 35 | $chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea 36 | $chart.ChartAreas.Add($chartArea) 37 | 38 | # Add data to the chart 39 | $series = New-Object System.Windows.Forms.DataVisualization.Charting.Series -ArgumentList 'Data' 40 | $series.Points.DataBindXY($XValues, $YValues) 41 | 42 | # Set specialized chart options based on chart type 43 | switch ($ChartType) { 44 | 'Pie' { 45 | $series.ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie 46 | $series["PieLabelStyle"] = "Outside" 47 | $series["PieLineColor"] = "Black" 48 | $series["PieDrawingStyle"] = "Concave" 49 | ($series.Points.FindMaxByValue())["Exploded"] = $true 50 | } 51 | 52 | 'Bar' { 53 | $series.ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Bar 54 | $series['DrawingStyle'] = 'Cylinder' 55 | } 56 | 57 | 'Column' { 58 | $series.ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Column 59 | $series['DrawingStyle'] = 'Cylinder' 60 | } 61 | 62 | default { 63 | throw "Unknown chart type '$ChartType'" 64 | } 65 | } 66 | $chart.BackColor = [System.Drawing.Color]::Transparent 67 | 68 | # Add the labels 69 | $chart.Titles.Add($Title) | Out-Null 70 | $chartArea.AxisX.Title = $XLabel 71 | $chartArea.AxisY.Title = $YLabel 72 | 73 | # Display the chart on a form 74 | $chart.Series.Add($series) 75 | $chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom ` 76 | -bor [System.Windows.Forms.AnchorStyles]::Right ` 77 | -bor [System.Windows.Forms.AnchorStyles]::Top ` 78 | -bor [System.Windows.Forms.AnchorStyles]::Left 79 | $form = New-Object Windows.Forms.Form 80 | $form.Text = $Title 81 | $form.Width = 600 82 | $form.Height = 600 83 | $form.controls.add($chart) 84 | $form.Add_Shown({$form.Activate()}) 85 | $form.ShowDialog() | Out-Null -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/test.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/1a774764c77e87313f5ff97a3c493811dbad1482/src/PowerShellGraphSDK/Samples/Apps/test.apk -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Samples/Apps/test.ipa: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/1a774764c77e87313f5ff97a3c493811dbad1482/src/PowerShellGraphSDK/Samples/Apps/test.ipa -------------------------------------------------------------------------------- /src/PowerShellGraphSDK/Scripts/ListCmdlets.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [Parameter(Mandatory = $false)] 3 | [ValidateNotNullOrEmpty()] 4 | [string]$ModuleName="$env:moduleName", 5 | 6 | [Parameter(Mandatory = $false)] 7 | [ValidateNotNullOrEmpty()] 8 | [string]$OutputDirectory="$env:sdkDir", 9 | 10 | [Parameter(Mandatory = $false)] 11 | [ValidateNotNullOrEmpty()] 12 | [switch]$IsFullOutput=$false 13 | ) 14 | 15 | $OutputDirectory = $OutputDirectory | Resolve-Path 16 | $modulePath = "$OutputDirectory\$ModuleName.psd1" 17 | 18 | Push-Location $OutputDirectory 19 | 20 | Import-Module $modulePath 21 | $sdkCmdlets = ((Get-Command -Module Microsoft.Graph.Intune).Name | Sort-Object) 22 | $cmdletCount = $sdkCmdlets.Count 23 | Write-Host "$cmdletCount Intune specific cmdlets exported by $modulePath" 24 | 25 | $sdkCmdletsList = @() 26 | foreach ($sdkCmdlet in $sdkCmdlets) 27 | { 28 | $sdkCmdletHelp = (Get-Help $sdkCmdlet) 29 | $sdkCmdletInfo = new-object PSObject 30 | $sdkCmdletInfo | add-member -membertype NoteProperty -name "Name" -value $sdkCmdletHelp.Name 31 | $sdkCmdletInfo | add-member -membertype NoteProperty -name "Name-Length" -value $sdkCmdletHelp.Name.Length 32 | $sdkCmdletInfo | add-member -membertype NoteProperty -name "Synopsis" -value $sdkCmdletHelp.Synopsis 33 | if ($sdkCmdletHelp.Description) 34 | { 35 | $description = "" 36 | foreach($descriptionLine in $sdkCmdletHelp.Description) 37 | { 38 | $description += $descriptionLine.Text.replace("`n"," ").replace("`r"," ") 39 | } 40 | $sdkCmdletInfo | add-member -membertype NoteProperty -name "Description" -value $description 41 | } 42 | else 43 | { 44 | $sdkCmdletInfo | add-member -membertype NoteProperty -name "Description" -value "" 45 | } 46 | $sdkCmdletsList+=$sdkCmdletInfo 47 | } 48 | 49 | $sdkCmdletsList | Export-Csv -Path "$OutputDirectory\$ModuleName.cmdlets.csv" -NoTypeInformation 50 | popd --------------------------------------------------------------------------------