├── Design.jpg
├── Tests
├── LobApps
│ └── UploadIOSLobApp.ps1
├── DeviceManagement
│ ├── DeviceManagement.ps1
│ └── DeviceCompliancePolicies.ps1
├── Set-IntuneContext.psm1
├── ConfigurationPolicyTests.ps1
├── CompliancePolicyTests.ps1
├── AppProtectionPolicyTests.ps1
├── DeviceAppManagement
│ ├── AppProtectionPolicies.ps1
│ └── MobileApps.ps1
├── Misc
│ └── POC_AllOS_Reset_Cmdlets.ps1
└── GetDeviceAppMgmtTests.ps1
├── src
├── PowerShellGraphSDK
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Samples
│ │ └── Apps
│ │ │ ├── test.apk
│ │ │ ├── test.ipa
│ │ │ ├── Apps.psm1
│ │ │ ├── UploadIOSLobApp.ps1
│ │ │ ├── VisualizeData.ps1
│ │ │ └── Microsoft.Graph.Intune.Apps.psd1
│ ├── PowerShellModuleAdditions
│ │ ├── README.md
│ │ ├── LICENSE.txt
│ │ └── CustomModules
│ │ │ ├── UtilCmdlets.psm1
│ │ │ └── AliasCmdlets.psm1
│ ├── Common
│ │ ├── Exceptions
│ │ │ ├── AdalAuthException.cs
│ │ │ ├── AuthException.cs
│ │ │ ├── MsiAuthException.cs
│ │ │ └── PSGraphSDKException.cs
│ │ ├── Attributes
│ │ │ ├── IdParameter.cs
│ │ │ ├── TypeCastParameterAttribute.cs
│ │ │ ├── ResourceIdParameterAttribute.cs
│ │ │ ├── ResourceReferenceAttribute.cs
│ │ │ ├── ExpandableAttribute.cs
│ │ │ ├── SelectableAttribute.cs
│ │ │ ├── SortableAttribute.cs
│ │ │ ├── ResourceTypePropertyNameAttribute.cs
│ │ │ ├── DerivedTypeAttribute.cs
│ │ │ ├── ParameterSetSelectorAttribute.cs
│ │ │ ├── ODataTypeAttribute.cs
│ │ │ ├── ValidateTypeAttribute.cs
│ │ │ └── ValidateUrlAttribute.cs
│ │ ├── Constants
│ │ │ ├── RequestProperties.cs
│ │ │ ├── QueryParameters.cs
│ │ │ ├── SearchResultProperties.cs
│ │ │ ├── AnnotationTerms.cs
│ │ │ └── EdmTypeNames.cs
│ │ ├── PSAuthenticationError.cs
│ │ ├── Utils
│ │ │ ├── ExceptionUtils.cs
│ │ │ ├── SdkAuthResult.cs
│ │ │ ├── CmdletUtils.cs
│ │ │ ├── AuthUtils_NetStandard.cs
│ │ │ └── ReferencePathGenerator.cs
│ │ └── EnvironmentParameters.cs
│ ├── PowerShellCmdlets
│ │ ├── DeleteCmdlet.cs
│ │ ├── PatchCmdlet.cs
│ │ ├── GetStreamCmdlet.cs
│ │ ├── PutReferenceToEntityCmdlet.cs
│ │ ├── PostReferenceToCollectionCmdlet.cs
│ │ ├── FunctionReturningEntityCmdlet.cs
│ │ ├── FunctionReturningCollectionCmdlet.cs
│ │ ├── PostCmdlet.cs
│ │ ├── UpdateStreamCmdlet.cs
│ │ ├── ActionCmdlet.cs
│ │ ├── Utils
│ │ │ └── ModuleInitializer.cs
│ │ ├── ODataCmdletBase.cs
│ │ └── ObjectFactoryCmdletBase.cs
│ ├── PowerShellGraphSDK.sln
│ ├── LICENSE
│ ├── Scripts
│ │ └── ListCmdlets.ps1
│ └── PowerShellGraphSDK.csproj
└── GraphODataPowerShellWriter
│ ├── ListCmdlets.ps1
│ ├── Generator
│ ├── Models
│ │ ├── CSharpAbstractions
│ │ │ ├── CSharpAccessModifier.cs
│ │ │ ├── CSharpArgument.cs
│ │ │ ├── CSharpDocumentationComment.cs
│ │ │ ├── CSharpProperty.cs
│ │ │ ├── CSharpMethod.cs
│ │ │ ├── CSharpAttribute.cs
│ │ │ └── CSharpFile.cs
│ │ ├── PowerShellAbstractions
│ │ │ ├── ObjectFactoryCmdlet.cs
│ │ │ ├── CmdletOperationTypes.cs
│ │ │ ├── CmdletParameterDocumentation.cs
│ │ │ ├── CmdletDocumentationLink.cs
│ │ │ ├── CmdletDocumentation.cs
│ │ │ ├── OperationCmdlet.cs
│ │ │ ├── Cmdlet.cs
│ │ │ └── CmdletName.cs
│ │ └── OdcmNode.cs
│ └── Behaviors
│ │ ├── SDK Operations
│ │ ├── 4_CSharpFileToTextFileConversionBehavior.cs
│ │ └── 3_ResourceToCSharpFileConversionBehavior.cs
│ │ └── Object Factories
│ │ ├── 2_ObjectFactoryToCSharpFileConversionBehavior.cs
│ │ └── 1_OdcmModelToObjectFactoriesConversionBehavior.cs
│ ├── Utils
│ ├── CSharpFileHelper.cs
│ ├── CSharpAccessModifierUtils.cs
│ ├── EnumerableUtils.cs
│ ├── CmdletOperationTypeUtils.cs
│ ├── CSharpNamingUtils.cs
│ ├── CSharpMethodHelper.cs
│ ├── CSharpClassAttributeHelper.cs
│ ├── CSharpTypeUtils.cs
│ └── DocumentationUtils.cs
│ └── PowerShellSDKWriter.cs
├── Generating_the_PowerShell_Binary_Module.jpg
├── init.cmd
├── .gitmodules
├── Intune-PowerShell-SDK-Code-Generator.yml
├── Scripts
├── msbuild-install.ps1
├── build-portable.ps1
├── run.ps1
├── test.ps1
└── build-full.ps1
├── .gitattributes
├── SECURITY.md
└── PowerShellGraphSDKGenerator.sln
/Design.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/master/Design.jpg
--------------------------------------------------------------------------------
/Tests/LobApps/UploadIOSLobApp.ps1:
--------------------------------------------------------------------------------
1 | $uploadedApp = (& $env:samplesDir\Apps\UploadIOSLobApp.ps1)
2 | $uploadedApp | Remove-IntuneMobileApp
--------------------------------------------------------------------------------
/src/PowerShellGraphSDK/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | [assembly: InternalsVisibleTo("GraphODataPowerShellSDKWriter")]
--------------------------------------------------------------------------------
/Generating_the_PowerShell_Binary_Module.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/master/Generating_the_PowerShell_Binary_Module.jpg
--------------------------------------------------------------------------------
/src/PowerShellGraphSDK/Samples/Apps/test.apk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/master/src/PowerShellGraphSDK/Samples/Apps/test.apk
--------------------------------------------------------------------------------
/src/PowerShellGraphSDK/Samples/Apps/test.ipa:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/Intune-PowerShell-SDK-Code-Generator/master/src/PowerShellGraphSDK/Samples/Apps/test.ipa
--------------------------------------------------------------------------------
/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/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
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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/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/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/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/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/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/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/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
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/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/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/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/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/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/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/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/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 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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/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/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/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/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/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/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 |
--------------------------------------------------------------------------------
/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."
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/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."
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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."
--------------------------------------------------------------------------------
/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/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/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/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/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/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 | }
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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/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 | }
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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/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/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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/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/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/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