full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Examples/Sample_xOfflineDomainJoin.ps1
Sample_xOfflineDomainJoin.ps1
configuration Sample_xOfflineDomainJoin { param ( [string[]]$NodeName = 'localhost' ) Import-DSCResource -ModuleName xComputerManagement Node $NodeName { xOfflineDomainJoin ODJ { RequestFile = 'C:\ODJ\ODJBlob.txt' IsSingleInstance = 'Yes' } } } Sample_xOfflineDomainJoin Start-DscConfiguration -Path Sample_xOfflineDomainJoin -Wait -Verbose -Force
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Unit/MSFT_xScheduledTask.Tests.ps1
MSFT_xScheduledTask.Tests.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( ) $Global:DSCModuleName = 'xComputerManagement' $Global:DSCResourceName = 'MSFT_xScheduledTask' #region HEADER # Unit Test Template Version: 1.1.0 [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit # Begin Testing try { #region Pester Tests InModuleScope $Global:DSCResourceName { Describe $Global:DSCResourceName { Mock Register-ScheduledTask { } Mock Set-ScheduledTask { } Mock Unregister-ScheduledTask { } Context "No scheduled task exists, but it should" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return $null } It "should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should create the scheduled task in the set method" { Set-TargetResource @testParams } } Context "A scheduled task exists, but it shouldn't" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Ensure = "Absent" } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should remove the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Unregister-ScheduledTask } } Context "A scheduled task doesnt exist, and it shouldn't" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Ensure = "Absent" } Mock Get-ScheduledTask { return $null } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } It "should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task with minutes based repetition exists, but has the wrong settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$(($testParams.RepeatInterval) + 1)M" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task with minutes based repetition exists and has the correct settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task with hourly based repetition exists, but has the wrong settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Hourly" RepeatInterval = 4 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$(($testParams.RepeatInterval) + 1)H" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task with hourly based repetition exists and has the correct settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Hourly" RepeatInterval = 4 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)H" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task with daily based repetition exists, but has the wrong settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Daily" RepeatInterval = 3 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "P$(($testParams.RepeatInterval) + 1)D" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task with daily based repetition exists and has the correct settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Daily" RepeatInterval = 3 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "P$($testParams.RepeatInterval)D" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task exists and is configured with the wrong execution account" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 ExecuteAsCredential = New-Object System.Management.Automation.PSCredential ("DEMO\RightUser", (ConvertTo-SecureString "ExamplePassword" -AsPlainText -Force)) } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Principal = @{ UserId = "WrongUser" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task exists and is configured with the wrong working directory" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ActionWorkingPath = "C:\Example" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable WorkingDirectory = "C:\Wrong" }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task exists and is configured with the wrong executable arguments" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ActionArguments = "-File `"C:\something\right.ps1`"" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = "-File `"C:\something\wrong.ps1`"" }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task is enabled and should be disabled" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $false } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = $testParams.Arguments }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Settings = @(@{ Enabled = $true }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A scheduled task is enabled and has the correct settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $true } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = $testParams.Arguments }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Settings = @(@{ Enabled = $true }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task is disabled and has the correct settings" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $false } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = $testParams.Arguments }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Settings = @(@{ Enabled = $false }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } Context "A scheduled task is disabled but should be enabled" { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $true } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = $testParams.Arguments }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Settings = @(@{ Enabled = $false }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "should update the scheduled task in the set method" { Set-TargetResource @testParams Assert-MockCalled Set-ScheduledTask } } Context "A Scheduled task exists, is disabled, and the optional parameter enable is not specified" -Fixture { $testParams = @{ TaskName = "Test task" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 } Mock Get-ScheduledTask { return @{ Name = $testParams.TaskName Path = $testParams.TaskPath Actions = @(@{ Execute = $testParams.ActionExecutable Arguments = $testParams.Arguments }) Triggers = @(@{ Repetition = @{ Duration = $null Interval = "PT$($testParams.RepeatInterval)M" } }) Settings = @(@{ Enabled = $false }) Principal = @{ UserId = "SYSTEM" } } } It "should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Unit/MSFT_xComputer.Tests.ps1
MSFT_xComputer.Tests.ps1
$Global:DSCModuleName = 'xComputerManagement' $Global:DSCResourceName = 'MSFT_xComputer' #region HEADER [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } else { & git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull') } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { #region Pester Tests InModuleScope $Global:DSCResourceName { Describe $Global:DSCResourceName { # A real password isn't needed here - use this next line to avoid triggering PSSA rule $SecPassword = New-Object -Type SecureString $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USER',$SecPassword $NotComputerName = if($env:COMPUTERNAME -ne 'othername'){'othername'}else{'name'} Context "$($Global:DSCResourceName)\Test-TargetResource" { Mock Get-WMIObject {[PSCustomObject]@{DomainName = 'ContosoLtd'}} -ParameterFilter {$Class -eq 'Win32_NTDomain'} It 'Throws if both DomainName and WorkGroupName are specified' { {Test-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com' -WorkGroupName 'workgroup'} | Should Throw } It 'Throws if Domain is specified without Credentials' { {Test-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com'} | Should Throw } It 'Should return True if Domain name is same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $Env:ComputerName -DomainName 'Contoso.com' -Credential $Credential | Should Be $true } It 'Should return True if Workgroup name is same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $Env:ComputerName -WorkGroupName 'workgroup' | Should Be $true } It 'Should return True if ComputerName and Domain name is same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com' -Credential $Credential | Should Be $true Test-TargetResource -Name 'localhost' -DomainName 'contoso.com' -Credential $Credential | Should Be $true } It 'Should return True if ComputerName and Workgroup is same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $Env:ComputerName -WorkGroupName 'workgroup' | Should Be $true Test-TargetResource -Name 'localhost' -WorkGroupName 'workgroup' | Should Be $true } It 'Should return True if ComputerName is same and no Domain or Workgroup specified' { Mock Get-WmiObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $Env:ComputerName | Should Be $true Test-TargetResource -Name 'localhost' | Should Be $true Mock Get-WmiObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $Env:ComputerName | Should Be $true Test-TargetResource -Name 'localhost' | Should Be $true } It 'Should return False if ComputerName is not same and no Domain or Workgroup specified' { Mock Get-WmiObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $NotComputerName | Should Be $false Mock Get-WmiObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $NotComputerName | Should Be $false } It 'Should return False if Domain name is not same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $Env:ComputerName -DomainName 'adventure-works.com' -Credential $Credential | Should Be $false Test-TargetResource -Name 'localhost' -DomainName 'adventure-works.com' -Credential $Credential | Should Be $false } It 'Should return False if Workgroup name is not same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $Env:ComputerName -WorkGroupName 'NOTworkgroup' | Should Be $false Test-TargetResource -Name 'localhost' -WorkGroupName 'NOTworkgroup' | Should Be $false } It 'Should return False if ComputerName is not same as specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Workgroup';Workgroup='Workgroup';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $NotComputerName -WorkGroupName 'workgroup' | Should Be $false Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $NotComputerName -DomainName 'contoso.com' -Credential $Credential | Should Be $false } It 'Should return False if Computer is in Workgroup and Domain is specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$false}} Mock GetComputerDomain {''} Test-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com' -Credential $Credential | Should Be $false Test-TargetResource -Name 'localhost' -DomainName 'contoso.com' -Credential $Credential | Should Be $false } It 'Should return False if ComputerName is in Domain and Workgroup is specified' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Test-TargetResource -Name $Env:ComputerName -WorkGroupName 'Contoso' -Credential $Credential -UnjoinCredential $Credential | Should Be $false Test-TargetResource -Name 'localhost' -WorkGroupName 'Contoso' -Credential $Credential -UnjoinCredential $Credential | Should Be $false } It 'Throws if name is to long' { {Test-TargetResource -Name "ThisNameIsTooLong"} | Should Throw } It 'Throws if name contains illigal characters' { {Test-TargetResource -Name "ThisIsBad<>"} | Should Throw } It 'Should not Throw if name is localhost' { {Test-TargetResource -Name "localhost"} | Should Not Throw } } Context "$($Global:DSCResourceName)\Get-TargetResource" { It 'should not throw' { {Get-TargetResource -Name $env:COMPUTERNAME} | Should Not Throw } It 'Should return a hashtable containing Name, DomainName, JoinOU, CurrentOU, Credential, UnjoinCredential and WorkGroupName' { $Result = Get-TargetResource -Name $env:COMPUTERNAME $Result.GetType().Fullname | Should Be 'System.Collections.Hashtable' $Result.Keys | Sort-Object | Should Be @('Credential', 'CurrentOU', 'DomainName', 'JoinOU', 'Name', 'UnjoinCredential', 'WorkGroupName') } It 'Throws if name is to long' { {Get-TargetResource -Name "ThisNameIsTooLong"} | Should Throw } It 'Throws if name contains illigal characters' { {Get-TargetResource -Name "ThisIsBad<>"} | Should Throw } } Context "$($Global:DSCResourceName)\Set-TargetResource" { Mock Rename-Computer {} Mock Add-Computer {} It 'Throws if both DomainName and WorkGroupName are specified' { {Set-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com' -WorkGroupName 'workgroup'} | Should Throw Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It } It 'Throws if Domain is specified without Credentials' { {Set-TargetResource -Name $Env:ComputerName -DomainName 'contoso.com'} | Should Throw Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It } It 'Changes ComputerName and changes Domain to new Domain' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $NotComputerName -DomainName 'adventure-works.com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName -and $NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes ComputerName and changes Domain to new Domain with specified OU' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $NotComputerName -DomainName 'adventure-works.com' -JoinOU 'OU=Computers,DC=contoso,DC=com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName -and $NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes ComputerName and changes Domain to Workgroup' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $NotComputerName -WorkGroupName 'contoso' -Credential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$WorkGroupName -and $NewName -and $Credential} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$DomainName -or $UnjoinCredential} } It 'Changes ComputerName and changes Workgroup to Domain' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso';Workgroup='Contoso';PartOfDomain=$false}} Mock GetComputerDomain {''} Set-TargetResource -Name $NotComputerName -DomainName 'Contoso.com' -Credential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName -and $NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes ComputerName and changes Workgroup to Domain with specified OU' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso';Workgroup='Contoso';PartOfDomain=$false}} Mock GetComputerDomain {''} Set-TargetResource -Name $NotComputerName -DomainName 'Contoso.com' -JoinOU 'OU=Computers,DC=contoso,DC=com' -Credential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName -and $NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes ComputerName and changes Workgroup to new Workgroup' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso';Workgroup='Contoso';PartOfDomain=$false}} Mock GetComputerDomain {''} Set-TargetResource -Name $NotComputerName -WorkGroupName 'adventure-works' | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$WorkGroupName -and $NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$DomainName} } It 'Changes only the Domain to new Domain' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $Env:ComputerName -DomainName 'adventure-works.com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes only the Domain to new Domain when name is [localhost]' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name 'localhost' -DomainName 'adventure-works.com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes only the Domain to new Domain with specified OU' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $Env:ComputerName -DomainName 'adventure-works.com' -JoinOU 'OU=Computers,DC=contoso,DC=com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes only the Domain to new Domain with specified OU when Name is [localhost]' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name 'localhost' -DomainName 'adventure-works.com' -JoinOU 'OU=Computers,DC=contoso,DC=com' -Credential $Credential -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$DomainName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$WorkGroupName} } It 'Changes only Domain to Workgroup' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {''} Set-TargetResource -Name $Env:ComputerName -WorkGroupName 'Contoso' -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$WorkGroupName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$DomainName} } It 'Changes only Domain to Workgroup when Name is [localhost]' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {''} Set-TargetResource -Name 'localhost' -WorkGroupName 'Contoso' -UnjoinCredential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$NewName} Assert-MockCalled -CommandName Add-Computer -Exactly 1 -Scope It -ParameterFilter {$WorkGroupName} Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It -ParameterFilter {$DomainName} } It 'Changes only ComputerName in Domain' { Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso.com';Workgroup='Contoso.com';PartOfDomain=$true}} Mock GetComputerDomain {'contoso.com'} Set-TargetResource -Name $NotComputerName -Credential $Credential | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 1 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It } It 'Changes only ComputerName in Workgroup' { Mock GetComputerDomain {''} Mock Get-WMIObject {[PSCustomObject]@{Domain = 'Contoso';Workgroup='Contoso';PartOfDomain=$false}} Set-TargetResource -Name $NotComputerName | Should BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly 1 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly 0 -Scope It } It 'Throws if name is to long' { {Set-TargetResource -Name "ThisNameIsTooLong"} | Should Throw } It 'Throws if name contains illigal characters' { {Set-TargetResource -Name "ThisIsBad<>"} | Should Throw } } } } #end InModuleScope $DSCResourceName #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Unit/MSFT_xOfflineDomainJoin.tests.ps1
MSFT_xOfflineDomainJoin.tests.ps1
$Global:DSCModuleName = 'xComputerManagement' $Global:DSCResourceName = 'MSFT_xOfflineDomainJoin' #region HEADER [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } else { & git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull') } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { #region Pester Tests InModuleScope $Global:DSCResourceName { $TestOfflineDomainJoin = @{ IsSingleInstance = 'Yes' RequestFile = 'C:\ODJRequest.txt' } Describe "$($Global:DSCResourceName)\Get-TargetResource" { It 'should return the correct values' { $Result = Get-TargetResource ` @TestOfflineDomainJoin $Result.IsSingleInstance | Should Be $TestOfflineDomainJoin.IsSingleInstance $Result.RequestFile | Should Be '' } } Describe "$($Global:DSCResourceName)\Set-TargetResource" { Mock Test-Path -MockWith { return $True } Mock Join-Domain Context 'Domain is not joined' { It 'should not throw exception' { { Set-TargetResource @TestOfflineDomainJoin } | Should Not Throw } It 'Should do call all the mocks' { Assert-MockCalled Test-Path -Times 1 Assert-MockCalled Join-Domain -Times 1 } } Mock Test-Path -MockWith { return $False } Context 'ODJ Request file is not found' { It 'should throw RequestFileNotFoundError exception' { $errorId = 'RequestFileNotFoundError' $errorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound $errorMessage = $($LocalizedData.RequestFileNotFoundError) ` -f $TestOfflineDomainJoin.RequestFile $exception = New-Object -TypeName System.ArgumentException ` -ArgumentList $errorMessage $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $exception, $errorId, $errorCategory, $null { Test-TargetResource @TestOfflineDomainJoin } | Should Throw $errorRecord } It 'should do call all the mocks' { Assert-MockCalled Test-Path -Times 1 Assert-MockCalled Join-Domain -Times 0 } } } Describe "$($Global:DSCResourceName)\Test-TargetResource" { Mock Test-Path -MockWith { return $True } Mock Get-DomainName -MockWith { return $null } Context 'Domain is not joined' { It 'should return false' { Test-TargetResource @TestOfflineDomainJoin | should be $false } It 'Should do call all the mocks' { Assert-MockCalled Test-Path -Times 1 Assert-MockCalled Get-DomainName -Times 1 } } Mock Get-DomainName -MockWith { return 'contoso.com' } Context 'Domain is already joined' { It 'should return false' { Test-TargetResource @TestOfflineDomainJoin | should be $true } It 'Should do call all the mocks' { Assert-MockCalled Test-Path -Times 1 Assert-MockCalled Get-DomainName -Times 1 } } Mock Test-Path -MockWith { return $False } Context 'ODJ Request file is not found' { It 'should throw RequestFileNotFoundError exception' { $errorId = 'RequestFileNotFoundError' $errorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound $errorMessage = $($LocalizedData.RequestFileNotFoundError) ` -f $TestOfflineDomainJoin.RequestFile $exception = New-Object -TypeName System.ArgumentException ` -ArgumentList $errorMessage $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $exception, $errorId, $errorCategory, $null { Test-TargetResource @TestOfflineDomainJoin } | Should Throw $errorRecord } It 'Should do call all the mocks' { Assert-MockCalled Test-Path -Times 1 Assert-MockCalled Get-DomainName -Times 0 } } } Describe "$($Global:DSCResourceName)\Join-Domain" { Mock djoin.exe -MockWith { $Global:LASTEXITCODE = 0; return "OK" } Context 'Domain Join successful' { It 'should not throw' { { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should Not Throw } It 'Should do call all the mocks' { Assert-MockCalled djoin.exe -Times 1 } } Mock djoin.exe -MockWith { $Global:LASTEXITCODE = 99; return "ERROR" } Context 'Domain Join successful' { $errorId = 'DjoinError' $errorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound $errorMessage = $($LocalizedData.DjoinError) ` -f 99 $exception = New-Object -TypeName System.ArgumentException ` -ArgumentList $errorMessage $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $exception, $errorId, $errorCategory, $null It 'should not throw' { { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should Throw $errorRecord } It 'Should do call all the mocks' { Assert-MockCalled djoin.exe -Times 1 } } } } #end InModuleScope $DSCResourceName #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Unit/MSFT_xPowerPlan.Tests.ps1
MSFT_xPowerPlan.Tests.ps1
$script:DSCModuleName = 'xComputerManagement' $script:DSCResourceName = 'MSFT_xPowerPlan' #region HEADER # Unit Test Template Version: 1.2.0 $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Unit #endregion HEADER function Invoke-TestCleanup { Restore-TestEnvironment -TestEnvironment $TestEnvironment } # Begin Testing try { Describe "$($script:DSCResourceName)\Get-TargetResource" { BeforeEach { $testParameters = @{ IsSingleInstance = 'Yes' Name = 'High performance' } } Context 'When the system is in the desired present state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { return New-Object Object | Add-Member -MemberType NoteProperty -Name IsActive -Value $true -PassThru -Force } -ModuleName $script:DSCResourceName -Verifiable } It 'Should return the same values as passed as parameters' { $result = Get-TargetResource @testParameters $result.IsSingleInstance | Should Be 'Yes' $result.Name | Should Be $testParameters.Name } } Context 'When the system is not in the desired present state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { return New-Object Object | Add-Member -MemberType NoteProperty -Name IsActive -Value $false -PassThru -Force } -ModuleName $script:DSCResourceName -Verifiable } It 'Should not return any plan name' { $result = Get-TargetResource @testParameters $result.IsSingleInstance | Should Be 'Yes' $result.Name | Should Be $null } } Context 'When the Get-CimInstance cannot retrive information about power plans' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { throw } -ModuleName $script:DSCResourceName -Verifiable } It 'Should throw the correct error' { { Get-TargetResource @testParameters } | Should Throw 'Could not get the Common Information Model (CIM) instances of class Win32_PowerPlan' } } Context 'When the preferred plan does not exist' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { return $null } -ModuleName $script:DSCResourceName -Verifiable } It 'Should throw saying it was not able to find the plan High performance' { { Get-TargetResource @testParameters } | Should Throw "Unable to find the power plan 'High performance'." } } Assert-VerifiableMocks } Describe "$($script:DSCResourceName)\Set-TargetResource" { BeforeEach { $testParameters = @{ IsSingleInstance = 'Yes' Name = 'High performance' } Mock -CommandName Invoke-CimMethod -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName Get-CimInstance -MockWith { return New-Object -TypeName Microsoft.Management.Infrastructure.CimInstance -ArgumentList @('Win32_PowerPlan','dummyNamespace') } -ModuleName $script:DSCResourceName -Verifiable } Context 'When the system is not in the desired present state' { It 'Should call the mocked function Invoke-CimMethod exactly once' { Set-TargetResource @testParameters Assert-MockCalled -CommandName Invoke-CimMethod -Exactly 1 -Scope It -ModuleName $script:DSCResourceName } } Context 'When the Get-CimInstance cannot retrive information about power plans' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { throw } -ModuleName $script:DSCResourceName -Verifiable } It 'Should throw the correct error' { { Set-TargetResource @testParameters } | Should Throw 'Could not get the Common Information Model (CIM) instances of class Win32_PowerPlan' } } Context 'When the Invoke-CimMethod throws an error' { BeforeEach { Mock -CommandName Invoke-CimMethod -MockWith { throw 'Failed to set value' } -ModuleName $script:DSCResourceName -Verifiable } It 'Should catch the correct error thrown by Invoke-CimMethod' { { Set-TargetResource @testParameters } | Should Throw "Unable to set the power plan 'High performance' to the active plan. Error message: Failed to set value" } } Assert-VerifiableMocks } Describe "$($script:DSCResourceName)\Test-TargetResource" { BeforeEach { $testParameters = @{ IsSingleInstance = 'Yes' Name = 'High performance' } } Context 'When the system is in the desired present state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { return New-Object Object | Add-Member -MemberType NoteProperty -Name IsActive -Value $true -PassThru -Force } -ModuleName $script:DSCResourceName -Verifiable } It 'Should return the the state as present ($true)' { Test-TargetResource @testParameters | Should Be $true } } Context 'When the system is not in the desired state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { return New-Object Object | Add-Member -MemberType NoteProperty -Name IsActive -Value $false -PassThru -Force } -ModuleName $script:DSCResourceName -Verifiable } It 'Should return the the state as absent ($false)' { Test-TargetResource @testParameters | Should Be $false } } Assert-VerifiableMocks } } finally { Invoke-TestCleanup }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Unit/MSFT_xVirtualMemory.Tests.ps1
MSFT_xVirtualMemory.Tests.ps1
#region HEADER $script:DSCModuleName = 'xComputerManagement' $script:DSCResourceName = 'MSFT_xVirtualMemory' # Unit Test Template Version: 1.2.0 $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Unit #endregion HEADER function Invoke-TestSetup { } function Invoke-TestCleanup { Restore-TestEnvironment -TestEnvironment $TestEnvironment } # Begin Testing try { Invoke-TestSetup InModuleScope 'MSFT_xVirtualMemory' { Describe "$($script:DSCResourceName)\Get-TargetResource" { BeforeEach { $testParameters = @{ Drive = 'D:' Type = 'CustomSize' } } Context 'When the system is in the desired present state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { [PSObject] @{ AutomaticManagedPageFile = $false; Name = 'D:\pagefile.sys' } } -ModuleName $script:DSCResourceName -Verifiable } It 'It should return the same values as passed as parameters' { $result = Get-TargetResource @testParameters $result.Type | Should Be $testParameters.Type $result.Drive | Should Be ([System.IO.DriveInfo]$testParameters.Drive).Name } } Context 'When the system is not in the desired present state' { BeforeEach { Mock -CommandName Get-CimInstance -MockWith { [PSObject] @{ InitialSize = 0 MaximumSize = 0 Name = "C:\pagefile.sys" } } -ModuleName $script:DSCResourceName -Verifiable } It 'It should not return a valid type' { $result = Get-TargetResource @testParameters $result.Type | Should Not Be $testParameters.Type } It 'It should not return a valid drive letter' { $result = Get-TargetResource @testParameters $result.Drive | Should Not Be ([System.IO.DriveInfo]$testParameters.Drive).Name } } Assert-VerifiableMocks } Describe "$($script:DSCResourceName)\Set-TargetResource" { Context 'When the system is not in the desired state' { BeforeEach { $testParameters = @{ Drive = 'C:' Type = 'CustomSize' InitialSize = 0 MaximumSize = 1337 } } Mock -CommandName Set-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName New-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName Remove-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName Get-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable It 'Should call the mocked function Set-CimInstance exactly once' { Set-TargetResource @testParameters Assert-MockCalled -CommandName Set-CimInstance -Exactly -Times 1 -Scope It } } context 'When an exception is expected' { Mock -CommandName Set-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName New-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName Remove-CimInstance -MockWith {} -ModuleName $script:DSCResourceName -Verifiable Mock -CommandName Get-CimInstance -MockWith { [PSObject] @{ InitialSize = 0 MaximumSize = 1338 Name = "D:\pagefile.sys" AutomaticManagedPageFile = $false } } $testParameters = @{ Drive = 'abc' Type = 'CustomSize' InitialSize = 0 MaximumSize = 1337 } It 'Should throw if no valid drive letter has been used' { { Set-TargetResource @testParameters } | Should Throw } $testParameters = @{ Drive = 'N:' Type = 'CustomSize' InitialSize = 0 MaximumSize = 1337 } It 'Should throw if the drive is not ready' { { Set-TargetResource @testParameters } | Should Throw } } Assert-VerifiableMocks } Describe "$($script:DSCResourceName)\Test-TargetResource" { Context 'When a True or False is expected' { BeforeEach { $testParameters = @{ Drive = 'D:' Type = 'CustomSize' InitialSize = 0 MaximumSize = 1337 } } $pageFileObject = [PSObject] @{ InitialSize = 0 MaximumSize = 1338 Name = "D:\pagefile.sys" AutomaticManagedPageFile = $false } Mock -CommandName Get-CimInstance -MockWith { $pageFileObject.MaximumSize = 1337 $pageFileObject } It 'Should return True if the input matches the actual values' { Test-TargetResource @testParameters | Should Be $true } Mock -CommandName Get-CimInstance -MockWith { $pageFileObject.MaximumSize = 1337 $pageFileObject.AutomaticManagedPageFile = $true $pageFileObject } It 'Should return False if the type is wrong' { Test-TargetResource @testParameters | Should Be $false } Mock -CommandName Get-CimInstance -MockWith { $pageFileObject.MaximumSize = 1338 $pageFileObject } It 'Should return False if InitialSize and/or MaximumSize do not match' { Test-TargetResource @testParameters | Should Be $false } Mock -CommandName Get-CimInstance -MockWith { # In this case Get-CimInstance returns an empty object } It 'Should return False if Name does not match' { Test-TargetResource @testParameters | Should Be $false } } } } } finally { Invoke-TestCleanup }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Integration/MSFT_xVirtualMemory.Config.ps1
MSFT_xVirtualMemory.Config.ps1
Configuration setToAuto { Import-DscResource -ModuleName xComputerManagement node "localhost" { xVirtualMemory vMem { Type = 'AutoManagePagingFile' Drive = 'C' } } } Configuration setToCustom { Import-DscResource -ModuleName xComputerManagement node "localhost" { xVirtualMemory vMem { Type = 'CustomSize' Drive = 'C' InitialSize = 128 MaximumSize = 1024 } } } Configuration setToSystemManaged { Import-DscResource -ModuleName xComputerManagement node "localhost" { xVirtualMemory vMem { Type = 'SystemManagedSize' Drive = 'C' } } } Configuration setToNone { Import-DscResource -ModuleName xComputerManagement node "localhost" { xVirtualMemory vMem { Type = 'NoPagingFile' Drive = 'C' } } }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Integration/MSFT_xScheduledTask.Integration.Tests.ps1
MSFT_xScheduledTask.Integration.Tests.ps1
#Requires -Version 5.0 $Global:DSCModuleName = 'xComputerManagement' $Global:DSCResourceName = 'MSFT_xScheduledTask' #region HEADER # Unit Test Template Version: 1.1.0 [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Integration # Begin Testing try { $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($Global:DSCResourceName).config.ps1" . $ConfigFile #region Pester Tests Describe $Global:DSCResourceName { Context "No scheduled task exists, but it should" { $CurrentConfig = "xScheduledTask_Add" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task with minutes based repetition exists, but has the wrong settings" { $CurrentConfig = "xScheduledTask_Edit1" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task with hourly based repetition exists, but has the wrong settings" { $CurrentConfig = "xScheduledTask_Edit2" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task with daily based repetition exists, but has the wrong settings" { $CurrentConfig = "xScheduledTask_Edit3" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task exists and is configured with the wrong working directory" { $CurrentConfig = "xScheduledTask_Edit4" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task exists and is configured with the wrong executable arguments" { $CurrentConfig = "xScheduledTask_Edit5" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task exists, but it shouldn't" { $CurrentConfig = "xScheduledTask_Remove" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task exists, and should be enabled" { $CurrentConfig = "xScheduledTask_Enable" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "A scheduled task exists, and should be disabled" { $CurrentConfig = "xScheduledTask_Disable" $ConfigDir = (Join-Path $TestDrive $CurrentConfig) $ConfigMof = (Join-Path $ConfigDir "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } AfterEach { Remove-DscConfigurationDocument -Stage Current, Pending, Previous -Force -Confirm:$false -WarningAction SilentlyContinue } } #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Integration/MSFT_xVirtualMemory.Integration.Tests.ps1
MSFT_xVirtualMemory.Integration.Tests.ps1
$script:DSCModuleName = 'xComputerManagement' $script:DSCResourceName = 'MSFT_xVirtualMemory' #region HEADER # Integration Test Template Version: 1.1.1 [String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Integration #endregion # Using try/finally to always cleanup. try { #region Integration Tests $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $configFile Describe "$($script:DSCResourceName)_Integration" { Context "Set page file to automatically managed" { $CurrentConfig = "setToAuto" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "Set page file to custom size" { $CurrentConfig = "setToCustom" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "Set page file to system managed" { $CurrentConfig = "setToSystemManaged" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } Context "Set page file to none" { $CurrentConfig = "setToNone" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir } | Should Not Throw } It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force } | Should Not Throw } It "should return a compliant state after being applied" { (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true } } } } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Tests/Integration/MSFT_xScheduledTask.Config.ps1
MSFT_xScheduledTask.Config.ps1
Configuration xScheduledTask_Add { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Add { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 } } } Configuration xScheduledTask_Edit1 { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Edit1 { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 45 } } } Configuration xScheduledTask_Edit2 { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Edit2 { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Hourly" RepeatInterval = 4 } } } Configuration xScheduledTask_Edit3 { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Edit3 { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Daily" RepeatInterval = 1 } } } Configuration xScheduledTask_Edit4 { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Edit3 { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ActionWorkingPath = "C:\" ScheduleType = "Daily" RepeatInterval = 1 } } } Configuration xScheduledTask_Edit5 { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Edit5 { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ActionWorkingPath = "C:\" ActionArguments = "-Command 'Get-ChildItem'" ScheduleType = "Daily" RepeatInterval = 1 } } } Configuration xScheduledTask_Remove { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Remove { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Ensure="Absent" } } } Configuration xScheduledTask_Enable { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Remove { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $true Ensure="Present" } } } Configuration xScheduledTask_Disable { Import-DscResource -ModuleName xComputerManagement node "localhost" { xScheduledTask xScheduledTask_Remove { TaskName = "Test task" TaskPath = "\xComputerManagement\" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ScheduleType = "Minutes" RepeatInterval = 15 Enable = $false Ensure="Present" } } }
PowerShellCorpus/PowerShellGallery/ProvanceITSM/0.7.0.0/functions/mainfunctions.ps1
mainfunctions.ps1
function New-ProvITSMCategoryMain { <# .Synopsis Creates a new Category .DESCRIPTION This function creates a new Category main record and gives back the new record for pipe-operations. If a category with the same name exists it emits a verbose message A Provance ITSM category has many mandatory values, so they are asked at the beginning .EXAMPLE New-ProvITSMCategoryMain -Name "Hardware" .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess)] Param( [Parameter(Mandatory=$true)][String]$Name, [Parameter(Mandatory=$false)][String]$Description, [Parameter(Mandatory=$false)][String]$Service, [Parameter(Mandatory=$false)][Switch]$HideOnIR, [Parameter(Mandatory=$false)][Switch]$HideOnSR, [Parameter(Mandatory=$false)][Switch]$HideOnCR, [Parameter(Mandatory=$false)][Switch]$HideOnPR ) $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMCategoryMain') #region Get Service ID by Name # Query the Service based on ServiceName and set a Service ID # Is there any service found ? if ($Service) { #Create Array bcs of .Count operator [Array]$ServiceRecord = Get-ProvITSMService -name $Service -ErrorAction SilentlyContinue Write-Verbose "$ServiceRecord" if($null -eq $ServiceRecord) { write-warning "Could not find service with name `"$service`", please specify a valid service DisplayName (apitil_service - apitil_name). Will create SR without linked Service" } # if ServiceRecord is unique all is good elseif ($serviceRecord.Count -eq 1) { [GUID]$serviceID = $ServiceRecord.serviceid.GUID $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId Write-Verbose "Unique Service $Service found" } # if sericename emits more that one service we take the first one (index [0]) elseif ($serviceRecord.Count -gt 1) { [GUID]$serviceID = $ServiceRecord[0].serviceid.GUID Write-Warning "Multiple Services are found, the first Service in the listing will be linked" $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId } } # Check if category Main already exists and if not, create it If ((Get-ProvITSMUniqueRecord -EntityLogicalName apitil_symptom -FilterAttribute apitil_name -FilterValue $name -WarningAction SilentlyContinue).Count -eq 0) { # Generate property Hastable to create the record $fields= @{ 'apitil_name' = $Name;` 'apitil_description' = $Description` } # Add Hide Options if set if ($serviceRelation) {$fields.apitil_service = $servicerelation} If ($HideOnIR) {$fields.apitil_incident = $false} If ($HideOnSR) {$fields.apitil_servicerequests = $false} If ($HideOnCR) {$fields.apitil_changerequests = $false} If ($HideOnPR) {$fields.apitil_problems = $false} # Generate the Category Main record and store the GUID if ($nowhatif) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_symptom -Fields $fields } } else { # The category already exists [string]$SourceCatName = $Name Write-warning "ITSM Category Main `"$SourceCatName`" already exists" } # Clear variables $servicerelation = $null $HideOnCR = $null $HideOnIR = $null $HideOnPR = $null $HideOnSR = $null } function New-ProvITSMCategoryDetailed { <# .Synopsis Creates a new Category .DESCRIPTION This function creates a new Category detailed record and gives back the new record for pipe-operations. A Category Main records need to exist. If a category detailed with the same name exists it emits a verbose message A Provance ITSM category has many mandatory values, so they are asked at the beginning Known BUG: Owner is always the cred runing the connection .EXAMPLE New-ProvITSMCategoryDetailed -Name "Hardware" -CategoryMainname 'Hardware' .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess)] Param( [Parameter(Mandatory=$true)][alias("CatDetName")] [String]$Name, [String]$Description, [Parameter(Mandatory=$true)][alias("CatMainName")] [String]$CategoryMainName, [String]$Owner ) $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMCategoryDetailed') #region Get Category Main by Name # Query the Main Category based on Name and set a Service ID $CategoryMain = Get-ProvITSMUniqueRecord -EntityLogicalName apitil_symptom -FilterAttribute apitil_name -FilterValue $CategoryMainName # only try to find a GUID if the Main category exists If($CategoryMain) { [GUID]$CategoryMainId = $CategoryMain.apitil_symptomid.Guid $CategoryMainRelation = New-CrmEntityReference -EntityLogicalName apitil_symptom -Id $CategoryMainId } Else{ $CategoryMainID = $null } #endregion #region Check if Owner exists and set ID and type (Owner is mandatory) if (($owner) -and (Get-ProvITSMUserOrTeam -name $owner)) { $ownerRecord = (Get-ProvITSMUserOrTeam -name $owner) [GUID]$ownerId = $ownerRecord.id $ownerType = $ownerRecord.type $ownerRelation = New-CrmEntityReference -EntityLogicalName systemuser -Id $ownerId } else { $ownerId = $null $ownerRelation = $null $ownerType = $null } #region Check if Category Detailed already exists and if not create it $CategoryDetailed = Get-ProvITSMUniqueRecord -EntityLogicalName apitil_symptomdetailed -FilterAttribute apitil_name -FilterValue $name -Warningaction Silentlycontinue If (!($CategoryDetailed)) { # Create hastable for the Category properties $fields= @{ 'apitil_name' = $Name;` 'apitil_description' = $Description` } # If a owner is found, add owner relationship according to type If ($ownerRelation) { # For Teams we need to set 'owningteam' if ($ownertype -eq 'owningteam') {$fields.owningteam = $ownerRelation} # For Users we need to set 'owninguser' if ($ownertype -eq 'owninguser') {$fields.owninguser = $ownerRelation} } # If a Category Main is set add the relation If ($CategoryMainRelation) {$fields.apitil_categorymain = $CategoryMainRelation} # Create the record and get record details if ($nowhatif) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_symptomdetailed -Fields $fields } } else { # The category detailed exists already, we dont need to create a new one Write-Warning "ITSM Category Detailed `"$CategoryDetailed.apitil_name`" already exists" } #endregion } function New-ProvITSMServiceRequest { <# .Synopsis Creates a new Service Request in Provance ITSM .DESCRIPTION This function needs a Title, Contact and Account as mandatory parameters. Additionally more values may be set (i.e. description) but those can also be set via template with the -tickettemplate parameter .EXAMPLE New-ProvITSMServicerequest -Title 'Need extended Internet Access' -Contact 'Mary Jones' -Account 'Contoso' npiir -Title 'Need new Monitor' -Contact 'Mary Jones' -Account 'Contoso' -TicketTemplate 'Hardware Request' .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess=$true)] Param( [Parameter( Mandatory = $true, HelpMessage = 'apitil_title', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Title, [Parameter( Mandatory = $true, HelpMessage = 'contact', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Contact, [Parameter( Mandatory = $true, HelpMessage = 'account', Valuefrompipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter( Helpmessage = 'apitil_description', Valuefrompipeline = $true)] [String]$Description, [Parameter( HelpMessage = 'apitil_servicename', ValueFromPipeline = $true)] [String]$Service, [Parameter( HelpMessage = 'User of Team', ValueFromPipeline = $true)] [String]$Owner, [Parameter( HelpMessage = 'apitil_tickettemplate')] [String]$TicketTemplate, [Parameter( HelpMessage = 'apitil_urgencyname')] [ValidateSet ('1-Critical','2-High','3-Minimum','4-Low')] [String]$Urgency, [Parameter( HelpMessage = 'apitil_impactname')] [ValidateSet ('1-Extensive','2-Significant','3-Moderate','4-Minor')] [String]$Impact ) $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMServiceRequest') #region check if mandatory parameter values exist. Only if mandatory values exist create the ticket otherwise write error # find contact and account $contactrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'contact' -FilterAttribute 'fullname' -FilterValue $contact -Warningaction Silentlycontinue $accountrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'account' -FilterAttribute 'name' -FilterValue $account -Warningaction Silentlycontinue #Create entity references if (($contactrecord) -and ($accountrecord)) { $contactrelation = New-CrmEntityReference -EntitylogicalName contact -id $contactrecord.contactid.guid -Warningaction Silentlycontinue $accountrelation = New-CrmEntityReference -EntitylogicalName account -id $accountrecord.accountid.guid -Warningaction Silentlycontinue #region Check if Owner exists and set ID if (($owner) -and (Get-ProvITSMUserOrTeam -name $owner)) { $ownerRecord = Get-ProvITSMUserOrTeam -name $owner [GUID]$ownerid = $ownerrecord.id $ownerRelation = New-CrmEntityReference -EntityLogicalName systemuser -Id $ownerId $ownerType = $ownerRecord.type } else { $ownerid = $null $ownerRelation = $null $ownerType = $null } # Query the Service based on ServiceName and set a Service ID # Is there any service found ? if ($Service) { #Create Array bcs of .Count operator [Array]$ServiceRecord = Get-ProvITSMService -name $Service -ErrorAction SilentlyContinue Write-Verbose "$ServiceRecord" if($null -eq $ServiceRecord) { write-warning "Could not find service with name `"$service`", please specify a valid service DisplayName (apitil_service - apitil_name). Will create SR without linked Service" } # if ServiceRecord is unique all is good elseif ($serviceRecord.Count -eq 1) { [GUID]$serviceID = $ServiceRecord.serviceid.GUID $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId Write-Verbose "Unique Service $Service found" } # if sericename emits more that one service we take the first one (index [0]) elseif ($serviceRecord.Count -gt 1) { [GUID]$serviceID = $ServiceRecord[0].serviceid.GUID Write-Warning "Multiple Services are found, the first Service in the listing will be linked" $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId } } # Check if tickettemplate was set, the template exists and create Relationship if valiable has value if ($ticketTemplate -ne '') { # Check is there is a tickettemplate record if ($null -ne ($TicketTemplateRecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'apitil_tickettemplate' -FilterAttribute 'apitil_name' -FilterValue $TicketTemplate)) { Write-Verbose "Found template with name $TicketTemplateRecord.apitil_name" # Check if the template is configured for service Requests if ($TicketTemplateRecord.apitil_tickettype -eq 'Service Request') { $ticketTemplateRelation = New-CrmEntityReference -EntitylogicalName apitil_tickettemplate -id $TicketTemplateRecord.apitil_tickettemplateid.guid } else { $TicketTemplateRecordName = $TicketTemplateRecord.apitil_name Write-Warning "Template `"$TicketTemplateRecordName`" not configured for Service Requests, creating record without template" } } } #region Transform Impact and urgency to Optionsetvalues $impactvalue = switch ($impact) {` 1-Extensive {New-CrmOptionSetValue -Value 100}` 2-Significant {New-CrmOptionSetValue -Value 200}` 3-Moderate {New-CrmOptionSetValue -Value 300}` 4-Minor {New-CrmOptionSetValue -Value 400}` } $urgencyvalue = switch ($urgency) {` 1-Critical {New-CrmOptionSetValue -Value 100}` 2-High {New-CrmOptionSetValue -Value 200}` 3-Minimum {New-CrmOptionSetValue -Value 300}` 4-Low {New-CrmOptionSetValue -Value 400}` } #endregion $createdate = Get-Date #Create property hashtable for record creation $fields = $null $fields = @{ 'apitil_title' = $title;` 'apitil_description' = $description;` 'apitil_contact' = $contactrelation;` 'apitil_account' = $accountrelation;` 'apitil_dateandtimeofrecording' = $createdate } # Add data to $fields hastable only if values have been set if ($null -ne $ownerRelation) {$fields.ownerid = $ownerRelation} if ($null -ne $servicerelation) {$fields.apitil_serviceid = $serviceRelation} if ($null -ne $urgencyvalue) {$fields.apitil_urgency = $urgencyValue} if ($null -ne $impactvalue) {$fields.apitil_impact = $impactValue} if ($null -ne $ticketTemplateRelation) {$fields.apitil_tickettemplate = $ticketTemplateRelation} #Create service request record if ($noWhatIf) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_servicerequest -Fields $Fields } } else { write-error "$contact or $account information is not correct, please enter existing values or create them" } } function New-ProvITSMIncident { <# .Synopsis Creates a New Incident in Provance ITSM .DESCRIPTION This function needs a Title, Contact and Account as mandatory parameters. Additionally more values may be set (i.e. description) but those can also be set via template with the -tickettemplate parameter .EXAMPLE New-ProvITSMIncident -Title 'Cannot access Intranet' -Contact 'Mary Jones' -Account 'Contoso' npiir -Title 'Cannot access Intranet' -Contact 'Mary Jones' -Account 'Contoso' -TicketTemplate 'Network Incident' .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess=$true)] Param( [Parameter( Mandatory = $true, HelpMessage = 'apitil_title', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Title, [Parameter( Mandatory = $true, HelpMessage = 'contact', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Contact, [Parameter( Mandatory = $true, Helpmessage = 'apitil_incidentdescription', Valuefrompipeline = $true)] [String]$Description, [Parameter( HelpMessage = 'account', Valuefrompipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter( HelpMessage = 'apitil_service', ValueFromPipeline = $true)] [String]$Service, [Parameter( HelpMessage = 'User or Team', ValueFromPipeline = $true)] [String]$Owner, [Parameter( HelpMessage = 'apitil_tickettemplate')] [String]$TicketTemplate, [Parameter( HelpMessage = 'apitil_urgencyname')] [ValidateSet ('1-Critical','2-High','3-Minimum','4-Low')] [String]$Urgency, [Parameter( HelpMessage = 'apitil_impactname')] [ValidateSet ('1-Extensive','2-Significant','3-Moderate','4-Minor')] [String]$Impact ) $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMIncident') #region check if mandatory parameter values exist. Only if mandatory values exist create the ticket otherwise write error # find contact $contactrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'contact' -FilterAttribute 'fullname' -FilterValue $contact -Warningaction Silentlycontinue #Create entity references if ($contactrecord) { $contactrelation = New-CrmEntityReference -EntitylogicalName contact -id $contactrecord.contactid.guid -Warningaction Silentlycontinue # find Account if ($account){ $accountrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'account' -FilterAttribute 'name' -FilterValue $account -Warningaction Silentlycontinue $accountrelation = New-CrmEntityReference -EntitylogicalName account -id $accountrecord.accountid.guid -Warningaction Silentlycontinue } #region Check if Owner exists and set ID if (($owner) -and (Get-ProvITSMUserOrTeam -name $owner)) { $ownerRecord = Get-ProvITSMUserOrTeam -name $owner [GUID]$ownerid = $ownerrecord.id $ownerRelation = New-CrmEntityReference -EntityLogicalName systemuser -Id $ownerId $ownerType = $ownerRecord.type } else { $ownerid = $null $ownerRelation = $null $ownerType = $null } # Query the Service based on ServiceName and set a Service ID # Is there any service found ? if ($Service) { #Create Array bcs of .Count operator [Array]$ServiceRecord = Get-ProvITSMService -name $Service -ErrorAction SilentlyContinue Write-Verbose "$ServiceRecord" if($null -eq $ServiceRecord) { write-warning "Could not find service with name `"$service`", please specify a valid service DisplayName (apitil_service - apitil_name). Will create IR without linked Service" } # if ServiceRecord is unique all is good elseif ($serviceRecord.Count -eq 1) { [GUID]$serviceID = $ServiceRecord.serviceid.GUID $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId Write-Verbose "Unique Service $Service found" } # if sericename emits more that one service we take the first one (index [0]) elseif ($serviceRecord.Count -gt 1) { [GUID]$serviceID = $ServiceRecord[0].serviceid.GUID Write-Warning "Multiple Services are found, the first Service in the listing will be linked" $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId } } # Check if tickettemplate was set, the template exists and create Relationship if valiable has value if ($ticketTemplate -ne '') { # Check is there is a tickettemplate record if ($null -ne ($TicketTemplateRecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'apitil_tickettemplate' -FilterAttribute 'apitil_name' -FilterValue $TicketTemplate)) { Write-Verbose "Found template with name $TicketTemplateRecord.apitil_name" # Check if the template is configured for service Requests if ($TicketTemplateRecord.apitil_tickettype -eq 'Incident') { $ticketTemplateRelation = New-CrmEntityReference -EntitylogicalName apitil_tickettemplate -id $TicketTemplateRecord.apitil_tickettemplateid.guid } else { $TicketTemplateRecordName = $TicketTemplateRecord.apitil_name Write-Warning "Template `"$TicketTemplateRecordName`" not configured for Incidents, creating record without template" } } } #region Transform Impact and urgency to Optionsetvalues $impactvalue = switch ($impact) {` 1-Extensive {New-CrmOptionSetValue -Value 100}` 2-Significant {New-CrmOptionSetValue -Value 200}` 3-Moderate {New-CrmOptionSetValue -Value 300}` 4-Minor {New-CrmOptionSetValue -Value 400}` } $urgencyvalue = switch ($urgency) {` 1-Critical {New-CrmOptionSetValue -Value 100}` 2-High {New-CrmOptionSetValue -Value 200}` 3-Minimum {New-CrmOptionSetValue -Value 300}` 4-Low {New-CrmOptionSetValue -Value 400}` } #endregion $createdate = Get-Date #Create property hashtable for record creation $fields = $null $fields = @{ 'apitil_title' = $title;` 'apitil_incidentdescription' = $description;` 'apitil_contact' = $contactrelation;` 'apitil_dateandtimeofrecording' = $createdate } # Add data to $fields hastable only if values have been set if ($null -ne $accountRelation) {$fields.apitil_account = $accountrelation} if ($null -ne $ownerRelation) {$fields.ownerid = $ownerRelation} if ($null -ne $servicerelation) {$fields.apitil_serviceid = $serviceRelation} if ($null -ne $urgencyvalue) {$fields.apitil_urgency = $urgencyValue} if ($null -ne $impactvalue) {$fields.apitil_impact = $impactValue} if ($null -ne $ticketTemplateRelation) {$fields.apitil_tickettemplate = $ticketTemplateRelation} #Create incident request record if ($noWhatIf) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_incident -Fields $Fields } } else { write-error "$contact information is not correct, please enter existing values or create them" } } function New-ProvITSMProblem { <# .Synopsis Creates a New Problem record in Provance ITSM .DESCRIPTION This function needs a Title, Description and Account as mandatory parameters. Additionally more values may be set. .EXAMPLE New-ProvITSMProblem -Title 'Intranet performance slow' -Description 'weak performance over the day' -Contact 'Mary Jones' npipr -Title 'Intranet performance slow' -Description 'weak performance over the day' -Contact 'Mary Jones' .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess=$true)] Param( [Parameter( Mandatory = $true, HelpMessage = 'apitil_title', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Title, [Parameter( Mandatory = $true, HelpMessage = 'contact', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Contact, [Parameter( Mandatory = $true, Helpmessage = 'apitil_description', Valuefrompipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Description, [Parameter( HelpMessage = 'account', Valuefrompipeline = $true)] [String]$Account, [Parameter( HelpMessage = 'apitil_environment', Valuefrompipeline = $true)] [ValidateSet ('Production','Test','Development')] [String]$Environment, [Parameter( HelpMessage = 'apitil_providedservice', ValueFromPipeline = $true)] [String]$Service, [Parameter( HelpMessage = 'User or Team', ValueFromPipeline = $true)] [String]$Owner, [Parameter( HelpMessage = 'apitil_tickettemplate')] [String]$TicketTemplate, [Parameter( HelpMessage = 'apitil_urgencyname')] [ValidateSet ('1-Critical','2-High','3-Minimum','4-Low')] [String]$Urgency, [Parameter( HelpMessage = 'apitil_impactname')] [ValidateSet ('1-Extensive','2-Significant','3-Moderate','4-Minor')] [String]$Impact ) # If -WhatIf Parameter ist set, define output data $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMProblem') #region check if mandatory parameter values exist. Only if mandatory values exist create the ticket otherwise write error #find contact and create link if ($contact) { $contactrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'contact' -FilterAttribute 'fullname' -FilterValue $contact -Warningaction Silentlycontinue if ($contactrecord) {$contactrelation = New-CrmEntityReference -EntitylogicalName contact -id $contactrecord.contactid.guid -Warningaction Silentlycontinue} #Check if Owner exists and set ID if (($owner) -and (Get-ProvITSMUserOrTeam -name $owner)) { $ownerRecord = Get-ProvITSMUserOrTeam -name $owner [GUID]$ownerid = $ownerrecord.id $ownerRelation = New-CrmEntityReference -EntityLogicalName systemuser -Id $ownerId $ownerType = $ownerRecord.type } else { $ownerid = $null $ownerRelation = $null $ownerType = $null } #endredion #region check other paramaters # Check if account exists and create account reference if ($account) { $accountrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'account' -FilterAttribute 'name' -FilterValue $account -Warningaction Silentlycontinue $accountrelation = New-CrmEntityReference -EntitylogicalName account -id $accountrecord.accountid.guid -Warningaction Silentlycontinue } # Query the Service based on ServiceName and set a Service ID if ($Service) { #Create Array bcs of .Count operator [Array]$ServiceRecord = Get-ProvITSMService -name $Service -ErrorAction SilentlyContinue Write-Verbose "$ServiceRecord" if($null -eq $ServiceRecord) { write-warning "Could not find service with name `"$service`", please specify a valid service DisplayName (apitil_service - apitil_name). Will create IR without linked Service" } # if ServiceRecord is unique all is good elseif ($serviceRecord.Count -eq 1) { [GUID]$serviceID = $ServiceRecord.serviceid.GUID $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId Write-Verbose "Unique Service $Service found" } # if sericename emits more that one service we take the first one (index [0]) elseif ($serviceRecord.Count -gt 1) { [GUID]$serviceID = $ServiceRecord[0].serviceid.GUID Write-Warning "Multiple Services are found, the first Service in the listing will be linked" $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId } } #Check if tickettemplate was set, the template exists and create Relationship if valiable has value if ($ticketTemplate -ne '') { # Check is there is a tickettemplate record if ($null -ne ($TicketTemplateRecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'apitil_tickettemplate' -FilterAttribute 'apitil_name' -FilterValue $TicketTemplate)) { Write-Verbose "Found template with name $TicketTemplateRecord.apitil_name" # Check if the template is configured for Problems if ($TicketTemplateRecord.apitil_tickettype -eq 'Problem') { $ticketTemplateRelation = New-CrmEntityReference -EntitylogicalName apitil_tickettemplate -id $TicketTemplateRecord.apitil_tickettemplateid.guid } else { $TicketTemplateRecordName = $TicketTemplateRecord.apitil_name Write-Warning "Template `"$TicketTemplateRecordName`" not configured for Incidents, creating record without template" } } } #> #region Transform Names to Optionsetvalues $impactValue = switch ($impact) {` 1-Extensive {New-CrmOptionSetValue -Value 100}` 2-Significant {New-CrmOptionSetValue -Value 200}` 3-Moderate {New-CrmOptionSetValue -Value 300}` 4-Minor {New-CrmOptionSetValue -Value 400}` } $urgencyValue = switch ($urgency) {` 1-Critical {New-CrmOptionSetValue -Value 100}` 2-High {New-CrmOptionSetValue -Value 200}` 3-Minimum {New-CrmOptionSetValue -Value 300}` 4-Low {New-CrmOptionSetValue -Value 400}` } $environmentValue = switch ($environment) {` Production {New-CrmOptionSetValue -Value 345550000}` Test {New-CrmOptionSetValue -Value 345550001}` Development {New-CrmOptionSetValue -Value 345550002}` } #endregion #endregion $createdate = Get-Date #Create property hashtable for record creation $fields = $null $fields = @{ 'apitil_title' = $title;` 'apitil_description' = $description;` 'apitil_contact' = $contactrelation;` 'apitil_dateandtimeofrecording' = $createdate } #region Add data to $fields hastable only if values have been set if ($null -ne $ownerRelation) {$fields.ownerid = $ownerRelation} if ($null -ne $serviceRelation) {$fields.apitil_providedservice = $serviceRelation} if ($null -ne $urgencyValue) {$fields.apitil_urgency = $urgencyValue} if ($null -ne $impactValue) {$fields.apitil_impact = $impactValue} if ($null -ne $environmentValue) {$fields.apitil_environment = $environmentValue} if ($null -ne $ticketTemplateRelation) {$fields.apitil_tickettemplate = $ticketTemplateRelation} if ($null -ne $accountRelation) {$fields.apitil_account = $accountrelation} #endregion #Create incident request record if ($noWhatIf) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_problem -Fields $fields } } # if no contact record is found ... else { write-error "$contact information is not correct, please enter existing values or create them" } } function New-ProvITSMChangeRequest { <# .Synopsis Creates a New Change Request record in Provance ITSM .DESCRIPTION This function needs a Title, Description, Contact and CR-type as mandatory parameters. Additionally more values may be set. .EXAMPLE New-ProvITSMChangeRequest -Title 'Redundant Internet Connection' -Description 'add more bandwith' -Contact 'Mary Jones' -RequestType 'Normal' npicr -Title 'Redundant Internet Connection' -Description 'add more bandwith' -Contact 'Mary Jones' -RequestType 'Normal' .INPUTS [String] .OUTPUTS [GUID] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [cmdletbinding(SupportsShouldProcess=$true)] Param( [Parameter( Mandatory = $true, HelpMessage = 'apitil_title', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Title, [Parameter( Mandatory = $true, HelpMessage = 'contact', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Contact, [Parameter( Mandatory = $true, Helpmessage = 'apitil_changerequestdescription', Valuefrompipeline = $true)] [ValidateNotNullOrEmpty()] [String]$Description, [Parameter( Mandatory = $true, HelpMessage = 'apitil_changerequesttype', Valuefrompipeline = $true)] [ValidateNotNullOrEmpty()] [ValidateSet ('Emergency','Normal','Standard')] [String]$RequestType, [Parameter( HelpMessage = 'account', Valuefrompipeline = $true)] [String]$Account, [Parameter( HelpMessage = 'apitil_service', ValueFromPipeline = $true)] [String]$Service, [Parameter( HelpMessage = 'User or Team', ValueFromPipeline = $true)] [String]$Owner, [Parameter( HelpMessage = 'apitil_tickettemplate')] [String]$TicketTemplate, [Parameter( HelpMessage = 'apitil_urgencyname')] [ValidateSet ('1-Critical','2-High','3-Minimum','4-Low')] [String]$Urgency, [Parameter( HelpMessage = 'apitil_impactname')] [ValidateSet ('1-Extensive','2-Significant','3-Moderate','4-Minor')] [String]$Impact ) # If -WhatIf Parameter ist set, define output data $noWhatIf = $PSCmdlet.Shouldprocess($crmconn.ConnectedOrgFriendlyName,'New-ProvITSMChangeRequest') #region check if mandatory parameter values exist. Only if mandatory values exist create the ticket otherwise write error #find contact and create link if ($contact) { $contactrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'contact' -FilterAttribute 'fullname' -FilterValue $contact -Warningaction Silentlycontinue if ($contactrecord) {$contactrelation = New-CrmEntityReference -EntitylogicalName contact -id $contactrecord.contactid.guid -Warningaction Silentlycontinue} #Check if Owner exists and set ID if (($owner) -and (Get-ProvITSMUserOrTeam -name $owner)) { $ownerRecord = Get-ProvITSMUserOrTeam -name $owner [GUID]$ownerid = $ownerrecord.id $ownerRelation = New-CrmEntityReference -EntityLogicalName systemuser -Id $ownerId $ownerType = $ownerRecord.type } else { $ownerid = $null $ownerRelation = $null $ownerType = $null } #region check other paramaters # Check if account exists and create account reference if ($account) { $accountrecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'account' -FilterAttribute 'name' -FilterValue $account -Warningaction Silentlycontinue $accountrelation = New-CrmEntityReference -EntitylogicalName account -id $accountrecord.accountid.guid -Warningaction Silentlycontinue } # Query the Service based on ServiceName and set a Service ID if ($Service) { #Create Array bcs of .Count operator [Array]$ServiceRecord = Get-ProvITSMService -name $Service -ErrorAction SilentlyContinue Write-Verbose "$ServiceRecord" if($null -eq $ServiceRecord) { write-warning "Could not find service with name `"$service`", please specify a valid service DisplayName (apitil_service - apitil_name). Will create IR without linked Service" } # if ServiceRecord is unique all is good elseif ($serviceRecord.Count -eq 1) { [GUID]$serviceID = $ServiceRecord.serviceid.GUID $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId Write-Verbose "Unique Service $Service found" } # if sericename emits more that one service we take the first one (index [0]) elseif ($serviceRecord.Count -gt 1) { [GUID]$serviceID = $ServiceRecord[0].serviceid.GUID Write-Warning "Multiple Services are found, the first Service in the listing will be linked" $serviceRelation = New-CrmEntityReference -EntityLogicalName 'apitil_service' -id $serviceId } } # Check if tickettemplate was set, the template exists and create Relationship if valiable has value if ($ticketTemplate -ne '') { # Check is there is a tickettemplate record if ($null -ne ($TicketTemplateRecord = Get-ProvITSMUniqueRecord -EntityLogicalName 'apitil_tickettemplate' -FilterAttribute 'apitil_name' -FilterValue $TicketTemplate)) { Write-Verbose "Found template with name $TicketTemplateRecord.apitil_name" # Check if the template is configured for Change Requests if ($TicketTemplateRecord.apitil_tickettype -eq 'Change Request') { $ticketTemplateRelation = New-CrmEntityReference -EntitylogicalName apitil_tickettemplate -id $TicketTemplateRecord.apitil_tickettemplateid.guid } else { $TicketTemplateRecordName = $TicketTemplateRecord.apitil_name Write-Warning "Template `"$TicketTemplateRecordName`" not configured for Change Requests, creating record without template" } } } #endregion #region Transform Names to Optionsetvalues $impactValue = switch ($impact) {` 1-Extensive {New-CrmOptionSetValue -Value 100}` 2-Significant {New-CrmOptionSetValue -Value 200}` 3-Moderate {New-CrmOptionSetValue -Value 300}` 4-Minor {New-CrmOptionSetValue -Value 400}` } $urgencyValue = switch ($urgency) {` 1-Critical {New-CrmOptionSetValue -Value 100}` 2-High {New-CrmOptionSetValue -Value 200}` 3-Minimum {New-CrmOptionSetValue -Value 300}` 4-Low {New-CrmOptionSetValue -Value 400}` } $RequestTypeValue = switch ($RequestType) {` Normal {New-CrmOptionSetValue -Value 345550000}` Standard {New-CrmOptionSetValue -Value 345550001}` Emergency {New-CrmOptionSetValue -Value 345550002}` } #endregion #Start preparing data $createdate = Get-Date #Create property hashtable for record creation $fields = $null $fields = @{ 'apitil_title' = $title;` 'apitil_changerequestdescription' = $description;` 'apitil_contact' = $contactrelation;` 'apitil_changerequesttype' = $RequestTypeValue;` 'apitil_dateandtimeofrecording' = $createdate } #region Add data to $fields hastable only if values have been set if ($null -ne $ownerRelation) {$fields.ownerid = $ownerRelation} if ($null -ne $serviceRelation) {$fields.apitil_service = $serviceRelation} if ($null -ne $urgencyValue) {$fields.apitil_urgency = $urgencyValue} if ($null -ne $impactValue) {$fields.apitil_impact = $impactValue} if ($null -ne $ticketTemplateRelation) {$fields.apitil_tickettemplate = $ticketTemplateRelation} if ($null -ne $accountRelation) {$fields.apitil_account = $accountrelation} #endregion #Create change request record if ($noWhatIf) { New-CrmRecord -conn $crmconn -EntityLogicalName apitil_request -Fields $fields } } # if no contact record is found ... else { write-error "$contact information is not correct, please enter existing values or create them" } } function Get-ProvITSMIncident { <# .Synopsis This function searches for Incidents and emits the most important attributes .DESCRIPTION This function gets Incidents and the major properties of the incident for listing or further processing .EXAMPLE Get-ProvITSMIncident -Name <String> .INPUTS Name .OUTPUTS PSObject .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] Param( [parameter( Mandatory = $true, Position = 0, HelpMessage = 'Incident Name with wildcards * and ? allowed', ValueFromPipeline = $true)] [string]$Name ) # Replace Wildcards to SQL Wildcards $replaceName = Convertto-ProvITSMSQLWildCard -Invalue $name # FetchXML to be used to get data from CRM $fetchXML = @" <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="apitil_incident"> <attribute name="apitil_account" /> <attribute name="apitil_caseorigin" /> <attribute name="apitil_contact" /> <attribute name="apitil_currentlevel" /> <attribute name="apitil_dateandtimeofrecording" /> <attribute name="apitil_escalationlevel" /> <attribute name="apitil_impact" /> <attribute name="apitil_incidentdescription" /> <attribute name="apitil_incidentid" /> <attribute name="apitil_name" /> <attribute name="apitil_olaassigned" /> <attribute name="apitil_originatingsource" /> <attribute name="apitil_priority" /> <attribute name="apitil_problemprimary" /> <attribute name="apitil_respondedto" /> <attribute name="apitil_service" /> <attribute name="apitil_sladuedate" /> <attribute name="apitil_slarecordassigned" /> <attribute name="apitil_slastatus" /> <attribute name="apitil_slastatuscolor" /> <attribute name="apitil_symptom" /> <attribute name="apitil_symptomdetailed" /> <attribute name="apitil_team" /> <attribute name="apitil_tickettemplate" /> <attribute name="apitil_title" /> <attribute name="apitil_ucassigned" /> <attribute name="apitil_uniqueid" /> <attribute name="apitil_urgency" /> <attribute name="createdon" /> <attribute name="modifiedon" /> <attribute name="ownerid" /> <attribute name="stageid" /> <attribute name="statecode" /> <attribute name="statuscode" /> <order attribute="apitil_dateandtimeofrecording" descending="true" /> <filter type="and"> <condition attribute="statecode" operator="in"> <value>1</value> <value>0</value> </condition> <condition attribute="apitil_name" operator="like" value="$replaceName" /> </filter> </entity> </fetch> "@ #region get data and format with Select: Alphabethical order to easier management $Incidents = (Get-CrmRecordsByFetch -conn $crmconn -Fetch $fetchXML).CrmRecords If ($incidents) { ForEach ($incident in $incidents) { #Convert StageID to StageName if ($incident.stageid) { $stageName = ConvertTo-ProvITSMStageName -stageGUID $incident.stageid|Select-Object -ExpandProperty * } #PS Object output Properties (should be in sync with fetchXML properties) $incidentProps = @{ 'Account' = $Incident.apitil_account; 'NotificationMethod' = $Incident.apitil_caseorigin; 'Contact' = $Incident.apitil_contact; 'CurrentLevel' = $Incident.apitil_currentlevel; 'RaisedOn' = $Incident.apitil_dateandtimeofrecording; 'EscalationLevel' = $Incident.apitil_escalationlevel; 'Impact' = $Incident.apitil_impact; 'Description' = $Incident.apitil_incidentdescription; 'GUID' = $Incident.apitil_incidentid; 'OlaAassigned' = $Incident.apitil_olaassigned; 'Source' = $Incident.apitil_originatingsource; 'Priority' = $Incident.apitil_priority; 'Problem' = $Incident.apitil_problemprimary; 'Name' = $Incident.apitil_name; 'RespondedTo' = $Incident.apitil_respondedto; 'Service' = $Incident.apitil_service; 'SlaDueDate' = $Incident.apitil_sladuedate; 'SlaAssigned' = $Incident.apitil_slarecordassigned; 'SlaStatus' = $Incident.apitil_slastatus; 'SlaStatusColor' = $Incident.apitil_slastatuscolor; 'StageName' = $stageName; 'Category' = $Incident.apitil_symptom; 'CategoryDetailed' = $Incident.apitil_symptomdetailed; 'Team' = $Incident.apitil_team; 'Title' = $Incident.apitil_title; 'UcAssigned' = $Incident.apitil_ucassigned; 'ID' = $Incident.apitil_uniqueid; 'Urgency' = $Incident.apitil_urgency; 'CreatedOn' = $Incident.createdon; 'LastModified' = $Incident.modifiedon; 'Owner' = $Incident.ownerid; 'Status' = $Incident.statecode; 'IncidentStatus' = $Incident.statuscode} New-Object -TypeName PSObject -Property $IncidentProps } } else { Write-Warning "No Incident records found" } } function Get-ProvITSMServiceRequest { <# .Synopsis This function gets Service Requests and the major properties of for listing or further processing .DESCRIPTION This function gets Service requests and the major properties for listing or further processing .EXAMPLE Get-ProvITSMServiceRequest -Name 'SR-10*' Get-ProvITSMServiceRequest -Name '*Tablet*'|select-object Title,Account,Priority Get-ProvITSMServiceRequest -Name '*7010?* .INPUTS Name .OUTPUTS PSObject .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] Param( [parameter( Mandatory = $true, Position = 0, HelpMessage = 'Service Request Name with wildcards * and ? allowed', ValueFromPipeline = $true)] [string]$Name ) # Replace Wildcards to SQL Wildcards ==> Create function for this feature $replaceName = Convertto-ProvITSMSQLWildCard -Invalue $name # FetchXML to be used to get data from CRM $fetchXML = @" <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="apitil_servicerequest"> <attribute name="apitil_account" /> <attribute name="apitil_caseorigin" /> <attribute name="apitil_contact" /> <attribute name="apitil_costcentre" /> <attribute name="apitil_currentlevel" /> <attribute name="apitil_dateandtimeofrecording" /> <attribute name="apitil_escalationlevel" /> <attribute name="apitil_fulfillmentcost" /> <attribute name="apitil_impact" /> <attribute name="apitil_description" /> <attribute name="apitil_name" /> <attribute name="apitil_olaassigned" /> <attribute name="apitil_originatingsource" /> <attribute name="apitil_priority" /> <attribute name="apitil_serviceid" /> <attribute name="apitil_servicerequestid" /> <attribute name="apitil_servicerequesttype" /> <attribute name="apitil_sladuedate" /> <attribute name="apitil_slarecordassigned" /> <attribute name="apitil_slastatus" /> <attribute name="apitil_slastatuscolor" /> <attribute name="apitil_symptom" /> <attribute name="apitil_symptomdetailed" /> <attribute name="apitil_team" /> <attribute name="apitil_tickettemplate" /> <attribute name="apitil_title" /> <attribute name="apitil_ucassigned" /> <attribute name="apitil_requestnumber" /> <attribute name="apitil_respondedto" /> <attribute name="apitil_urgency" /> <attribute name="createdon" /> <attribute name="modifiedon" /> <attribute name="ownerid" /> <attribute name="stageid" /> <attribute name="statecode" /> <attribute name="statuscode" /> <order attribute="apitil_dateandtimeofrecording" descending="true" /> <filter type="and"> <condition attribute="statecode" operator="in"> <value>1</value> <value>0</value> </condition> <condition attribute="apitil_name" operator="like" value="$replaceName" /> </filter> </entity> </fetch> "@ #region get data and format with Select: Alphabethical order to easier management $ServiceRequests = (Get-CrmRecordsByFetch -conn $crmconn -Fetch $fetchXML).CrmRecords If ($ServiceRequests) { ForEach ($ServiceRequest in $ServiceRequests) { #Convert StageID to StageName if ($ServiceRequest.stageid) { $stageName = ConvertTo-ProvITSMStageName -StageGUID $ServiceRequest.stageid|Select-Object -ExpandProperty * } #PS Object output Properties (should be in sync with fetchXML properties) $ServiceRequestProps = @{ 'Account' = $ServiceRequest.apitil_account; 'NotificationMethod' = $ServiceRequest.apitil_caseorigin; 'Contact' = $ServiceRequest.apitil_contact; 'CostCentre' = $ServiceRequest.apitil_costcentre; 'CurrentLevel' = $ServiceRequest.apitil_currentlevel; 'RaisedOn' = $ServiceRequest.apitil_dateandtimeofrecording; 'EscalationLevel' = $ServiceRequest.apitil_escalationlevel; 'FulfillmentCosts' = $ServiceRequest.apitil_fulfillmentcost; 'Impact' = $ServiceRequest.apitil_impact; 'Description' = $ServiceRequest.apitil_description; 'GUID' = $ServiceRequest.apitil_servicerequestid; 'OlaAassigned' = $ServiceRequest.apitil_olaassigned; 'Source' = $ServiceRequest.apitil_originatingsource; 'Priority' = $ServiceRequest.apitil_priority; 'Name' = $ServiceRequest.apitil_name; 'Service' = $ServiceRequest.apitil_serviceid; 'ServiceRequestType' = $ServiceRequest.apitil_servicerequesttype; 'SlaDueDate' = $ServiceRequest.apitil_sladuedate; 'SlaAssigned' = $ServiceRequest.apitil_slarecordassigned; 'SlaStatus' = $ServiceRequest.apitil_slastatus; 'SlaStatusColor' = $ServiceRequest.apitil_slastatuscolor; 'StageName' = $stageName; 'Category' = $ServiceRequest.apitil_symptom; 'CategoryDetailed' = $ServiceRequest.apitil_symptomdetailed; 'Team' = $ServiceRequest.apitil_team; 'Title' = $ServiceRequest.apitil_title; 'UcAssigned' = $ServiceRequest.apitil_ucassigned; 'ID' = $ServiceRequest.apitil_requestnumber; 'Urgency' = $ServiceRequest.apitil_urgency; 'CreatedOn' = $ServiceRequest.createdon; 'LastModified' = $ServiceRequest.modifiedon; 'Owner' = $ServiceRequest.ownerid; 'Status' = $ServiceRequest.statecode; 'ServiceReqeuestStatus' = $ServiceRequest.statuscode} New-Object -TypeName PSObject -Property $ServiceRequestProps } } else { Write-Warning "No Service Request records found" } } function Get-ProvITSMChangeRequest { <# .Synopsis Read Change Requests by Name .DESCRIPTION This function gets Change Requests and the major properties of for listing or further processing .EXAMPLE Get-ProvITSMChangeRequest -Name 'SCR-10*' Get-ProvITSMChangeRequest -Name '*Tablet*'|select-object Title,Account,Priority Get-ProvITSMChangeRequest -Name '*7010?* .INPUTS Value .OUTPUTS PSObject .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] Param( [parameter( Mandatory = $true, Position = 0, HelpMessage = 'Change Request Name with wildcards * and ? allowed', ValueFromPipeline = $true)] [string]$Name ) # Replace Wildcards to SQL Wildcards ==> Create function for this feature $replaceName = Convertto-ProvITSMSQLWildCard -Invalue $name # FetchXML to be used to get data from CRM $fetchXML = @" <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="apitil_request"> <attribute name="apitil_account" /> <attribute name="apitil_caseorigin" /> <attribute name="apitil_contact" /> <attribute name="apitil_currentlevel" /> <attribute name="apitil_changerequestdescription" /> <attribute name="apitil_changerequestclass" /> <attribute name="apitil_dateandtimeofrecording" /> <attribute name="apitil_escalationlevel" /> <attribute name="apitil_impact" /> <attribute name="apitil_implementationrisk" /> <attribute name="apitil_name" /> <attribute name="apitil_olaassigned" /> <attribute name="apitil_originatingsource" /> <attribute name="apitil_priority" /> <attribute name="apitil_risktype" /> <attribute name="apitil_service" /> <attribute name="apitil_requestid" /> <attribute name="apitil_changerequesttype" /> <attribute name="apitil_sladuedate" /> <attribute name="apitil_slarecordassigned" /> <attribute name="apitil_slastatus" /> <attribute name="apitil_slastatuscolor" /> <attribute name="apitil_symptom" /> <attribute name="apitil_symptomdetailed" /> <attribute name="apitil_team" /> <attribute name="apitil_tickettemplate" /> <attribute name="apitil_title" /> <attribute name="apitil_ucassigned" /> <attribute name="apitil_respondedto" /> <attribute name="apitil_urgency" /> <attribute name="apitil_uniqueid" /> <attribute name="createdon" /> <attribute name="modifiedon" /> <attribute name="ownerid" /> <attribute name="stageid" /> <attribute name="statecode" /> <attribute name="statuscode" /> <order attribute="apitil_dateandtimeofrecording" descending="true" /> <filter type="and"> <condition attribute="statecode" operator="in"> <value>1</value> <value>0</value> </condition> <condition attribute="apitil_name" operator="like" value="$replaceName" /> </filter> </entity> </fetch> "@ #region get data and format with Select: Alphabethical order to easier management $ChangeRequests = (Get-CrmRecordsByFetch -conn $crmconn -Fetch $fetchXML).CrmRecords If ($ChangeRequests) { ForEach ($ChangeRequest in $ChangeRequests) { #Convert StageID to StageName if ($ChangeRequest.stageid) { $stageName = ConvertTo-ProvITSMStageName -StageGUID $ChangeRequest.stageid|Select-Object -ExpandProperty * } #PS Object output Properties (should be in sync with fetchXML properties) $ChangeRequestProps = @{ 'Account' = $ChangeRequest.apitil_account; 'NotificationMethod' = $ChangeRequest.apitil_caseorigin; 'Contact' = $ChangeRequest.apitil_contact; 'CurrentLevel' = $ChangeRequest.apitil_currentlevel; 'Description' = $ChangeRequest.apitil_changerequestdescription; 'RequestClass' = $ChangeRequest.apitil_changerequestclass; 'RaisedOn' = $ChangeRequest.apitil_dateandtimeofrecording; 'EscalationLevel' = $ChangeRequest.apitil_escalationlevel; 'Impact' = $ChangeRequest.apitil_impact; 'ImplementationRisk' = $ChangeRequest.apitil_implementationrisk; 'GUID' = $ChangeRequest.apitil_requestid; 'RiskType' = $ChangeRequest.apitil_risktype; 'OlaAassigned' = $ChangeRequest.apitil_olaassigned; 'Source' = $ChangeRequest.apitil_originatingsource; 'Priority' = $ChangeRequest.apitil_priority; 'Name' = $ChangeRequest.apitil_name; 'Service' = $ChangeRequest.apitil_serviceid; 'ChangeRequestType' = $ChangeRequest.apitil_changerequesttype; 'SlaDueDate' = $ChangeRequest.apitil_sladuedate; 'SlaAssigned' = $ChangeRequest.apitil_slarecordassigned; 'SlaStatus' = $ChangeRequest.apitil_slastatus; 'SlaStatusColor' = $ChangeRequest.apitil_slastatuscolor; 'StageName' = $stageName; 'Category' = $ChangeRequest.apitil_symptom; 'CategoryDetailed' = $ChangeRequest.apitil_symptomdetailed; 'Team' = $ChangeRequest.apitil_team; 'Title' = $ChangeRequest.apitil_title; 'ID' = $ChangeRequest.apitil_uniqueid; 'UcAssigned' = $ChangeRequest.apitil_ucassigned; 'Urgency' = $ChangeRequest.apitil_urgency; 'CreatedOn' = $ChangeRequest.createdon; 'LastModified' = $ChangeRequest.modifiedon; 'Owner' = $ChangeRequest.ownerid; 'Status' = $ChangeRequest.statecode; 'ServiceReqeuestStatus' = $ChangeRequest.statuscode} New-Object -TypeName PSObject -Property $ChangeRequestProps } } else { Write-Warning "No Change Request records found" } } function Get-ProvITSMService { <# .Synopsis Read Services with main attributes .DESCRIPTION This function gets Services and their properties .EXAMPLE Get-ProvITSMService -Name <String> Get-ProvITSMService -Name 'E-Mail' Get-ProvITSMService -Name '*Tablet*'|select-object Title,Account,Priority Get-ProvITSMService -Name 'Active-Direc* .INPUTS Name .OUTPUTS PSObject .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] Param( [parameter( Mandatory = $true, Position = 0, HelpMessage = 'Service Name with wildcards * and ? allowed', ValueFromPipeline = $true)] [string]$Name ) # Replace Wildcards to SQL Wildcards $replaceName = Convertto-ProvITSMSQLWildCard -Invalue $name # FetchXML to be used to get data from CRM $fetchXML = @" <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="apitil_service"> <attribute name="apitil_3rdpartyprovidername" /> <attribute name="apitil_accessinstructions" /> <attribute name="apitil_agreedservicehours" /> <attribute name="apitil_agreementdate" /> <attribute name="apitil_alternativeroutingdetails" /> <attribute name="apitil_baselineincidentscreatedlast30days" /> <attribute name="apitil_baselineincidentscreatedlasthour" /> <attribute name="apitil_baselineincidentscreatedtoday" /> <attribute name="apitil_baselineopenincidents" /> <attribute name="apitil_baselineopentickets" /> <attribute name="apitil_budgetcategory" /> <attribute name="apitil_businesscategory" /> <attribute name="apitil_businessservice" /> <attribute name="apitil_cost" /> <attribute name="apitil_cost_base" /> <attribute name="apitil_costcurrency" /> <attribute name="apitil_customerbenefits" /> <attribute name="apitil_defaultdataclassification" /> <attribute name="apitil_description" /> <attribute name="apitil_displayname" /> <attribute name="apitil_external" /> <attribute name="apitil_forecastedcost" /> <attribute name="apitil_forecastedcost_base" /> <attribute name="apitil_forecastedusers" /> <attribute name="apitil_itdescription" /> <attribute name="apitil_itservicemanagername" /> <attribute name="apitil_lastupdated" /> <attribute name="apitil_manufacturerpartnumber" /> <attribute name="apitil_maxliveinstances" /> <attribute name="apitil_maxtestinstances" /> <attribute name="apitil_name" /> <attribute name="apitil_nickname" /> <attribute name="apitil_notes" /> <attribute name="apitil_parentserviceid" /> <attribute name="apitil_refreshcycleduration" /> <attribute name="apitil_refreshcycledurationunit" /> <attribute name="apitil_releasedate" /> <attribute name="apitil_requirecausecodes" /> <attribute name="apitil_retirementdate" /> <attribute name="apitil_retirementinitiationdate" /> <attribute name="apitil_scope" /> <attribute name="apitil_servicearea" /> <attribute name="apitil_servicecriticality" /> <attribute name="apitil_serviceid" /> <attribute name="apitil_serviceleveltargets" /> <attribute name="apitil_servicerevenue" /> <attribute name="apitil_servicerevenue_base" /> <attribute name="apitil_servicereviewdate" /> <attribute name="apitil_servicesuccessful" /> <attribute name="apitil_standardbillingtype" /> <attribute name="apitil_standardcost" /> <attribute name="apitil_standardcost_base" /> <attribute name="apitil_standardprice" /> <attribute name="apitil_standardprice_base" /> <attribute name="apitil_storesdata" /> <attribute name="apitil_subscribers" /> <attribute name="apitil_subscribers_date" /> <attribute name="apitil_subscribers_state" /> <attribute name="apitil_supplierpartnumber" /> <attribute name="apitil_type" /> <attribute name="createdby" /> <attribute name="createdon" /> <attribute name="modifiedby" /> <attribute name="modifiedon" /> <attribute name="owninguser" /> <attribute name="stageid" /> <attribute name="statecode" /> <attribute name="statuscode" /> <order attribute="createdon" descending="true" /> <filter type="and"> <condition attribute="statecode" operator="in"> <value>1</value> <value>0</value> </condition> <condition attribute="apitil_name" operator="like" value="$replaceName" /> </filter> </entity> </fetch> "@ #region get data and format with Select: Alphabethical order to easier management $Services = (Get-CrmRecordsByFetch -conn $crmconn -Fetch $fetchXML).CrmRecords #Emit data in a formatted way If ($Services) { ForEach ($Service in $Services) { #Convert StageID to StageName if ($Service.stageid) { $stageName = ConvertTo-ProvITSMStageName -stageGUID $Service.stageid|Select-Object -ExpandProperty * } #PS Object output Properties (should be in sync with fetchXML properties) $serviceProps = @{ '3rdpartyprovidername' = $Service.apitil_3rdpartyprovidername; 'Aaccessinstructions' = $Service.apitil_accessinstructions; 'Agreedservicehours' = $Service.apitil_agreedservicehours; 'Alternativeroutingdetails' = $Service.apitil_alternativeroutingdetails; 'Baselineincidentscreatedlast30days' = $Service.apitil_baselineincidentscreatedlast30days; 'Baselineincidentscreatedlasthour' = $Service.apitil_baselineincidentscreatedlasthour; 'Baselineincidentscreatedtoday' = $Service.apitil_baselineincidentscreatedtoday; 'Baselineopenincidents' = $Service.apitil_baselineopenincidents; 'Baselineopentickets' = $Service.apitil_baselineopentickets; 'Budgetcategory' = $Service.apitil_budgetcategory; 'Businesscategory' = $Service.apitil_businesscategory; 'Businessservice' = $Service.apitil_businessservice; 'Cost' = $Service.apitil_cost; 'Cost_base' = $Service.apitil_cost_base; 'Costcurrency' = $Service.apitil_costcurrency; 'Customerbenefits' = $Service.apitil_customerbenefits; 'Defaultdataclassification' = $Service.apitil_defaultdataclassification; 'Description' = $Service.apitil_description; 'Displayname' = $Service.apitil_displayname; 'External' = $Service.apitil_external; 'Forecastedcost' = $Service.apitil_forecastedcost; 'Forecastedcost_base' = $Service.apitil_forecastedcost_base; 'Forecastedusers' = $Service.apitil_forecastedusers; 'Itdescription' = $Service.apitil_itdescription; 'Itservicemanagername' = $Service.apitil_itservicemanagername; 'Lastupdated' = $Service.apitil_lastupdated; 'Manufacturerpartnumber' = $Service.apitil_manufacturerpartnumber; 'Maxliveinstances' = $Service.apitil_maxliveinstances; 'Maxtestinstances' = $Service.apitil_maxtestinstances; 'Name' = $Service.apitil_name; 'Nickname' = $Service.apitil_nickname; 'Notes' = $Service.apitil_notes; 'Parentserviceid' = $Service.apitil_parentserviceid; 'Refreshcycleduration' = $Service.apitil_refreshcycleduration; 'Refreshcycledurationunit' = $Service.apitil_refreshcycledurationunit; 'Releasedate' = $Service.apitil_releasedate; 'Requirecausecodes' = $Service.apitil_requirecausecodes; 'Retirementdate' = $Service.apitil_retirementdate; 'Retirementinitiationdate' = $Service.apitil_retirementinitiationdate; 'Scope' = $Service.apitil_scope; 'Servicearea' = $Service.apitil_servicearea; 'Servicecriticality' = $Service.apitil_servicecriticality; 'Serviceid' = $Service.apitil_serviceid; 'Serviceleveltargets' = $Service.apitil_serviceleveltargets; 'Servicerevenue' = $Service.apitil_servicerevenue; 'Servicerevenue_base' = $Service.apitil_servicerevenue_base; 'Servicereviewdate' = $Service.apitil_servicereviewdate; 'Servicesuccessful' = $Service.apitil_servicesuccessful; 'Standardbillingtype' = $Service.apitil_standardbillingtype; 'Standardcost' = $Service.apitil_standardcost; 'Standardcost_base' = $Service.apitil_standardcost_base; 'Standardprice' = $Service.apitil_standardprice; 'Standardprice_base' = $Service.apitil_standardprice_base; 'Storesdata' = $Service.apitil_storesdata; 'Subscribers' = $Service.apitil_subscribers; 'Subscribers_date' = $Service.apitil_subscribers_date; 'Subscribers_state' = $Service.apitil_subscribers_state; 'Supplierpartnumber' = $Service.apitil_supplierpartnumber; 'Type' = $Service.apitil_type; 'Createdby' = $Service.createdby; 'Createdon' = $Service.createdon; 'Modifiedby' = $Service.modifiedby; 'Modifiedon' = $Service.modifiedon; 'Owninguser' = $Service.owninguser; 'Stageid' = $stageName; 'Statecode' = $Service.statecode; 'Statuscode' = $Service.statuscode;} New-Object -TypeName PSObject -Property $ServiceProps } } else { Write-Warning "No Service records found" } } function Get-ProvITSMProblem { <# .Synopsis Read Services with main attributes .DESCRIPTION This function gets Problems and the major properties of the Problem for listing or further processing .EXAMPLE Get-ProvITSMProblem -Name 'PRO10*' Get-ProvITSMProblem -Name '*Tablet*'|select-object Title,Account,Priority Get-ProvITSMProblem -Name '*7010?* .INPUTS Name .OUTPUTS PSObject .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] Param( [parameter( Mandatory = $true, Position = 0, HelpMessage = 'Problem Name with wildcards * and ? allowed', ValueFromPipeline = $true)] [string]$Name ) # Replace Wildcards to SQL Wildcards $replaceName = Convertto-ProvITSMSQLWildCard -Invalue $name # FetchXML to be used to get data from CRM $fetchXML = @" <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="apitil_problem"> <attribute name="apitil_account" /> <attribute name="apitil_caseorigin" /> <attribute name="apitil_contact" /> <attribute name="apitil_currentlevel" /> <attribute name="apitil_dateandtimeofrecording" /> <attribute name="apitil_escalationlevel" /> <attribute name="apitil_impact" /> <attribute name="apitil_description" /> <attribute name="apitil_knownerror" /> <attribute name="apitil_problemid" /> <attribute name="apitil_name" /> <attribute name="apitil_olaassigned" /> <attribute name="apitil_originatingsource" /> <attribute name="apitil_priority" /> <attribute name="apitil_respondedto" /> <attribute name="apitil_service" /> <attribute name="apitil_sladuedate" /> <attribute name="apitil_slarecordassigned" /> <attribute name="apitil_slastatus" /> <attribute name="apitil_slastatuscolor" /> <attribute name="apitil_symptom" /> <attribute name="apitil_symptomdetailed" /> <attribute name="apitil_team" /> <attribute name="apitil_tickettemplate" /> <attribute name="apitil_title" /> <attribute name="apitil_ucassigned" /> <attribute name="apitil_problemnumber" /> <attribute name="apitil_urgency" /> <attribute name="createdon" /> <attribute name="modifiedon" /> <attribute name="ownerid" /> <attribute name="stageid" /> <attribute name="statecode" /> <attribute name="statuscode" /> <order attribute="apitil_dateandtimeofrecording" descending="true" /> <filter type="and"> <condition attribute="statecode" operator="in"> <value>1</value> <value>0</value> </condition> <condition attribute="apitil_name" operator="like" value="$replaceName" /> </filter> </entity> </fetch> "@ #region get data and format with Select: Alphabethical order to easier management $problems = (Get-CrmRecordsByFetch -conn $crmconn -Fetch $fetchXML).CrmRecords If ($problems) { ForEach ($problem in $problems) { #Convert StageID to StageName if ($problem.stageid) { $stageName = ConvertTo-ProvITSMStageName -stageGUID $problem.stageid|Select-Object -ExpandProperty * } #PS Object output Properties (should be in sync with fetchXML properties) $problemProps = @{ 'Account' = $problem.apitil_account; 'NotificationMethod' = $problem.apitil_caseorigin; 'Contact' = $problem.apitil_contact; 'CurrentLevel' = $problem.apitil_currentlevel; 'RaisedOn' = $problem.apitil_dateandtimeofrecording; 'EscalationLevel' = $problem.apitil_escalationlevel; 'Impact' = $problem.apitil_impact; 'KnownError' = $problem.apitil_knownerror; 'Description' = $problem.apitil_description; 'GUID' = $problem.apitil_problemid; 'OlaAassigned' = $problem.apitil_olaassigned; 'Source' = $problem.apitil_originatingsource; 'Priority' = $problem.apitil_priority; 'Name' = $problem.apitil_name; 'RespondedTo' = $problem.apitil_respondedto; 'Service' = $problem.apitil_service; 'SlaDueDate' = $problem.apitil_sladuedate; 'SlaAssigned' = $problem.apitil_slarecordassigned; 'SlaStatus' = $problem.apitil_slastatus; 'SlaStatusColor' = $problem.apitil_slastatuscolor; 'StageName' = $stageName; 'Category' = $problem.apitil_symptom; 'CategoryDetailed' = $problem.apitil_symptomdetailed; 'Team' = $problem.apitil_team; 'Title' = $problem.apitil_title; 'UcAssigned' = $problem.apitil_ucassigned; 'ID' = $problem.apitil_problemnumber; 'Urgency' = $problem.apitil_urgency; 'CreatedOn' = $problem.createdon; 'LastModified' = $problem.modifiedon; 'Owner' = $problem.ownerid; 'Status' = $problem.statecode; 'ProblemStatus' = $problem.statuscode} New-Object -TypeName PSObject -Property $problemProps } } else { Write-Warning "No Problem records found" } } #region function aliases Set-Alias -Name npicm -Value New-ProvITSMCategoryMain -Description 'Creates a new Main category' Set-Alias -Name npicd -Value New-ProvITSMCategoryDetailed -Description 'Creates a new Detailed category' Set-Alias -Name npisr -Value New-ProvITSMServiceRequest -Description 'Creates a new Service Request record' Set-Alias -Name npiir -Value New-ProvITSMIncident -Description 'Creates a new Incident record' Set-Alias -Name npipr -Value New-ProvITSMProblem -Description 'Creates a new Problem record' Set-Alias -Name npicr -Value New-ProvITSMChangeRequest -Description 'Creates a new Change Request record' Set-Alias -Name gpiir -Value Get-ProvITSMIncident -Description 'Gets Incidents' Set-Alias -Name gpisr -Value Get-ProvITSMServiceRequest -Description 'Gets Service Requests' Set-Alias -Name gpisv -Value Get-ProvITSMService -Description 'Gets Services' Set-Alias -Name gpicr -Value Get-ProvITSMChangeRequest -Description 'Gets Change Requests' Set-Alias -Name gpipr -Value Get-ProvITSMProblem -Description 'Gets Problems' #endregion
PowerShellCorpus/PowerShellGallery/ProvanceITSM/0.7.0.0/functions/helperfunctions.ps1
helperfunctions.ps1
function ConvertTo-ProvITSMStageName { <# .Synopsis Transform Stage GUID to Stage DisplayName .DESCRIPTION Many records in CRM are managed via a business provess. When those records are read, they emit a stage ID as GUID which is not human readable. This funtion transforms the stageUI GUID to a DisplayName of the stage .EXAMPLE ConvertTo-ProvITSMStageName -StageGUID "000-0000-0000-0000-000000" .EXAMPLE ctpisn -StageGUID "000-0000-0000-0000-000000" .INPUTS [GUID] .OUTPUTS [STRING] .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY See description #> [CmdletBinding()] param( [Parameter(ValueFromPipeLine = $true, Mandatory = $true)] [GUID]$StageGUID ) Get-CrmRecord -Id $stageGUID -conn $crmconn -EntityLogicalName processstage -Fields 'stagename'|Select-Object stagename } function ConvertTo-ProvITSMSQLWildCard { <# .Synopsis Transforms Windows WIldcards to SQL Wildcards .DESCRIPTION When fetching data from CRM, the wildcards used in Fetchxml files are based on the SQL wildcards syntax. People are more used to * and ? aswildcards. This function transforms: * ==> % ? ==> _ .EXAMPLE ConvertTo-ProvanceITSMSQLWildcard -Invalue 'A?C*' .EXAMPLE ctpisw -Invalue 'A?C*' .INPUTS [String] with Wildcards * and ? .OUTPUTS [String] withreplaced Wildcards % and _ .NOTES See description .COMPONENT Die Komponente, zu der dieses Cmdlet gehört .ROLE none .FUNCTIONALITY see description #> [CmdletBinding()] param( [Parameter(ValueFromPipeLine = $true, Mandatory = $true)] $invalue ) if (($invalue -match '`*') -or ($invalue -match '`?')) { ($invalue.Replace('*','%')).Replace('?','_') } else { $invalue} } function Get-ProvITSMUniqueRecord { <# .Synopsis Emits a Unique Provance ITSM record even if wildcards are used in selection .DESCRIPTION This function emits a unique ITSM record based on a logical entity name an attribute for that property and a value for that property If there are more than one record, the function emits the record with the newest modified date. .EXAMPLE Get-ProvITSMUniqueRecord -entityLogicalName 'contact' -filterAttribute 'apitil_displayname' -Value 'Sam Money' .EXAMPLE gpiur -entityLogicalName 'contact' -filterAttribute 'apitil_displayname' -Value 'Sam Money' .INPUTS [String] .OUTPUTS [GUID] of the record .NOTES You can use wildcards * (anything) and ? (one character) .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY see decription #> [CmdletBinding()] Param( [parameter(Mandatory=$true, Position=1)][alias("Entity","LogicalName")] [string]$entityLogicalName, [parameter(Mandatory=$true, Position=2)][alias("Attrib")] [string]$filterAttribute, [parameter(Mandatory=$true, Position=4)][alias("Value", "FieldValue")] [string]$filterValue ) # Transform Windows Wildcards to SQL Wildcards $replaceValue = Convertto-ProvITSMSQLWildCard -Invalue $filtervalue # Set specific ITSM based GUID Value to query on $apitilId = $entityLogicalName + "Id" # Get the data based on the unique criteria $records = Get-CrmRecords -WarningAction SilentlyContinue -conn $crmconn -EntityLogicalName $entityLogicalName -FilterAttribute $filterAttribute -FilterOperator like -FilterValue $replaceValue #If we found nothing - emit Warning Message if ($records.Count -eq 0) { Write-Warning "No entity of type `"$entityLogicalName`" found based on attribute `"$filterattribute`" equals `"$replaceValue`"" } # if we found one or more entries, process else { # Exactly one entry if ($records.Count -eq 1) { # Get the GUID $ITSMUniquerecordID = $records.CrmRecords.$apitilId|Select-Object -ExpandProperty GUID # Get the ITSM data record $ITSMUniqueRecord = Get-CrmRecord -conn $crmconn -EntityLogicalName $EntityLogicalName -Id $ITSMUniquerecordID -Field * } else { # if we found more than one record get the newest one and use it as ITSM data record $sortedRecords = $records|Sort-Object -Property 'modifiedon' -Descending # Get the GUID $ITSMUniquerecordID = $sortedRecords.CrmRecords[0].$apitilId|Select-Object -ExpandProperty GUID # Get the ITSM data record $ITSMUniqueRecord = Get-CrmRecord -conn $crmconn -EntityLogicalName $EntityLogicalName -Id $ITSMUniquerecordID -Fields * } # Write-out Data $ITSMUniqueRecord } } function Get-ProvITSMUserOrTeam { <# .Synopsis Find GUID or a User or Team .DESCRIPTION Takes a Display Name of a User or Team and emits the GUID, or if no records are found, a verbose message is shown and no value is emitted. .EXAMPLE Get-ProvITSMUserOrTeam -Name 'Eric Clipton' Get-ProvITSMUserOrTeam -Name 'Service Desk' .EXAMPLE gpiuot -Name 'Eric Clipton' gpiuot -Name 'Service Desk' .INPUTS [String] .OUTPUTS [GUID] $ownerInfo.ownerrecordid $ownerInfo.ownerrecordtype .NOTES none .COMPONENT Provance ITSM Module .ROLE none .FUNCTIONALITY see description #> [cmdletBinding()] Param( [Parameter( Mandatory=$true, Helpmessage='User or Team DisplayName', ValuefromPipeline = $true)] [ValidateNotNullOrEmpty()] [String]$name ) #Check if Owner value is set if (Get-ProvITSMUniqueRecord -EntityLogicalName systemuser -FilterAttribute fullname -FilterValue $name -OutVariable UserRecord -WarningAction SilentlyContinue) { #$OwnerUserRecord = Get-ProvITSMUniqueRecord -EntityLogicalName systemuser -FilterAttribute fullname -FilterValue $OwnerName $OwnerId = $UserRecord.systemuserid $owningtype = 'owninguser' } #Check if ownerrecord exists as Team and set as GUID elseif (Get-ProvITSMUniqueRecord -EntityLogicalName team -FilterAttribute name -FilterValue $name -OutVariable TeamRecord -WarningAction SilentlyContinue) { #$OwnerTeamRecord = Get-ProvITSMUniqueRecord -EntityLogicalName team -FilterAttribute name -FilterValue $OwnerName $ownerId = $TeamRecord.teamid $owningType = 'owningteam' } else { $ownerId = $null Write-Verbose "Neiter found User nor Team record" } if ($ownerId) { $ownerInfo = @{ 'id' = $ownerId;` 'Type' = $owningType} $ownerInfo } } #region function Aliases Set-Alias -Name ctpisw -Value ConvertTo-ProvITSMSQLWildCard -Description 'Converts Windows Wildcards to SQL Wildcards' Set-Alias -Name ctpisn -Value ConvertTo-ProvITSMStageName -Description 'Converts a Stage GUID to a Stage Name' Set-Alias -Name gpiur -Value Get-ProvITSMUniqueRecord -Description 'Emits the GUID of a Unique (the newest) record' Set-Alias -Name gpiuot -Value Get-ProvITSMUserOrTeam -Description 'Converts a User or TeamName to a GUID' #endregion
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Reload-ISEFile.ps1
Reload-ISEFile.ps1
#requires -version 4.0 <# reload an file in the ISE that might have been modified outside of the ISE. #> Function Reset-ISEFile { #save the current file path $path = $psise.CurrentFile.FullPath #get current index $i = $psise.CurrentPowerShellTab.files.IndexOf($psise.CurrentFile) #remove the file $psise.CurrentPowerShellTab.Files.Remove($psise.CurrentFile) | out-null $psise.CurrentPowerShellTab.Files.Add($path) | out-null #file always added to the end $psise.CurrentPowerShellTab.files.Move(($psise.CurrentPowerShellTab.files.count-1),$i) | out-Null }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-PSCommand.ps1
New-PSCommand.ps1
#requires -version 3.0 Function New-PSCommand { <# .SYNOPSIS Create an advanced function outline .DESCRIPTION This command will create the outline of an advanced function based on a hash table of new parameter values. You will still need to flesh out the function and insert the actual commands. You might need to tweak parameters in the resulting code for items such a default value, help message, parameter aliases and validation. The New-PSCommand command takes a lot of the grunt work out of the scripting process so you can focus on the actual working part of the function. .PARAMETER Name The name of the new function .PARAMETER NewParameters A hash table of new parameter values. The key should be the parameter name. The entry value should be the object type. You can also indicate if it should be an array by using [] with the object type. Here's an example: @{Name="string[]";Test="switch";Path="string"} Or you can use an "advanced" version of the hash table to specify optional parameter attributes that follows the format: @{ParamName="type[]",Mandatory,ValuefromPipeline,ValuefromPipelinebyPropertyName,Position} Here's an example: $h = @{Name="string[]",$True,$True,$False,0; Path="string",$false,$false,$false,1; Size="int",$false,$false,$true; Recurse="switch" } You can also specify an ordered hash table if you are running PowerShell v or later. .PARAMETER ShouldProcess Set SupportsShouldProcess to True in the new function. .PARAMETER Synopsis Provide a brief synopsis of your command. Optional. .PARAMETER Description Provide a description for your command. You can always add and edit this later. .PARAMETER BeginCode A block of code to insert in the Begin scriptblock. This can be either a scriptblock or a string. .PARAMETER ProcessCode A block of code to insert at the start of the Process scriptblock. This can be either a scriptblock or a string. .PARAMETER EndCode A block of code to insert at the start of the End scriptblock. This can be either a scriptblock or a string. .PARAMETER UseISE If you are running this command in the ISE, send the new function to the editor as a new file. .EXAMPLE PS C:\> $paramhash=@{Name="string[]";Test="switch";Path="string"} PS C:\> New-PSCommand -name "Set-MyScript" -Newparameters $paramhash | out-file "c:\scripts\set-myscript.ps1" Create an advanced script outline for Set-MyScript with parameters of Name, Test and Path. Results are saved to a file. .EXAMPLE PS C:\> $hash = [ordered]@{Name="string[]",$True,$True,$False,0;Path="string",$false,$false,$false,1;Size="int",$false,$false,$true;Recurse="switch"} PS C:\> $begin={ #initialize some variables $arr=@() $a=$True $b=123 } PS C:\> $end="write-host 'Finished' -foreground Green" PS C:\> $synopsis = "Get user data" PS C:\> $desc = @" This command will do something really amazing. All you need to do is provide the right amount of pixie dust and shavings from a unicorn horn. This requires PowerShell v4 and a full moon. "@ PS C:\> New-PSCommand -Name Get-UserData -NewParameters $hash -BeginCode $begin -EndCode $end -Synopsis $synopsis -Description $desc -useise Create an advanced function from the ordered hash table. This expression will also insert extra code into the Begin and End scriptblocks as well as enter text for the help synopsis and description. The new command will be opened in the ISE. .NOTES Last Updated : 4/15/2014 Version : 2.0 Author : Jeffery Hicks (http://jdhitsolutions.com/blog) .LINK http://jdhitsolutions.com/blog/2012/12/create-powershell-scripts-with-a-single-command .LINK About_Functions About_Functions_Advanced About_Functions_Advanced_Parameters #> [cmdletbinding()] Param( [Parameter(Mandatory=$True,HelpMessage="Enter the name of your new command")] [ValidateNotNullorEmpty()] [string]$Name, [ValidateScript({ #test if using a hashtable or an [ordered] hash table in v3 or later ($_ -is [hashtable]) -OR ($_ -is [System.Collections.Specialized.OrderedDictionary]) })] [Alias("Parameters")] [object]$NewParameters, [switch]$ShouldProcess, [string]$Synopsis, [string]$Description, [string]$BeginCode, [string]$ProcessCode, [string]$EndCode, [switch]$UseISE ) Write-Verbose "Starting $($myinvocation.mycommand)" #add parameters $myparams="" $helpparams="" Write-Verbose "Processing parameter names" foreach ($k in $newparameters.keys) { Write-Verbose " $k" $paramsettings = $NewParameters.item($k) #process any remaining elements from the hashtable value #@{ParamName="type[]",Mandatory,ValuefromPipeline,ValuefromPipelinebyPropertyName,Position} if ($paramsettings.count -gt 1) { $paramtype=$paramsettings[0] if ($paramsettings[1] -is [object]) { $Mandatory = "Mandatory=`${0}," -f $paramsettings[1] Write-Verbose $Mandatory } if ($paramsettings[2] -is [object]) { $PipelineValue = "ValueFromPipeline=`${0}," -f $paramsettings[2] Write-Verbose $PipelineValue } if ($paramsettings[3] -is [object]) { $PipelineName = "ValueFromPipelineByPropertyName=`${0}" -f $paramsettings[3] Write-Verbose $PipelineName } if ($paramsettings[4] -is [object]) { $Position = "Position={0}," -f $paramsettings[4] Write-Verbose $Position } } else { #the only hash key is the parameter type $paramtype=$paramsettings } $item = "[Parameter({0}{1}{2}{3})]`n" -f $Position,$Mandatory,$PipelineValue,$PipelineName $item +="[{0}]`${1}" -f $paramtype,$k Write-Verbose "Adding $item to myparams" $myparams+="$item, `n" $helpparams+=".PARAMETER {0} `n`n" -f $k #clear variables but ignore errors for those that don't exist Clear-Variable "Position","Mandatory","PipelineValue","PipelineName","ParamSettings" -ErrorAction SilentlyContinue } #foreach hash key #get trailing comma and remove it $myparams=$myparams.Remove($myparams.lastIndexOf(",")) Write-Verbose "Building text" $text=@" #requires -version 3.0 Function $name { <# .SYNOPSIS $Synopsis .DESCRIPTION $Description $HelpParams .EXAMPLE PS C:\> $Name .NOTES Version: 0.1 Author : $env:username .INPUTS .OUTPUTS .LINK #> [cmdletbinding(SupportsShouldProcess=`$$ShouldProcess)] Param ( $MyParams ) Begin { Write-Verbose "Starting `$(`$myinvocation.mycommand)" $BeginCode } #begin Process { $ProcessCode } #process End { $EndCode Write-Verbose "Ending `$(`$myinvocation.mycommand)" } #end } #end $name function "@ if ($UseISE -and $psise) { $newfile=$psise.CurrentPowerShellTab.Files.Add() $newfile.Editor.InsertText($Text) } else { $Text } Write-Verbose "Ending $($myinvocation.mycommand)" } #end New-PSCommand function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Get-ASTScriptProfile.ps1
Get-ASTScriptProfile.ps1
#requires -version 3.0 #Get-ASTScriptProfile.ps1 Function Get-ASTProfile { <# .Synopsis Profile a PowerShell script .Description This script will parse a PowerShell script using the AST to identify elements and any items that might be dangerous. The output is a text report which by default is turned into a help topic stored in your Windows PowerShell folder under Documents, although you can specify an alternate location. DETAILS The script takes the name of a script to profile. You can specify a ps1 or psm1 filename. Using the AST the script will prepare a text report showing you any script requirements, script parameters, commands and type names. You will see all commands used including those that can't be resolved as well as those that I thought might be considered potentially dangerous such as cmdlets that use the verbs Remove or Stop. Because some people might invoke methods from .NET classes directly I've also captured all typenames. Most of them will probably be related to parameters but as least you'll know what to look for. The report won't detail parameters from nested functions but you'll still see what commands they will use. The script uses Get-Command to identify commands which might entail loading a module. Most of the time this shouldn't be an issue but you still might want to profile the script in virtualized or test environment. Any unresolved command you see is either from a module that couldn't be loaded or it might be an internally defined command. Once you know what to look for you can open the script in your favorite editor and search for the mystery commands. Note that if the script uses application names like Main or Control for function names, they might be misinterpreted. In that case, search the script for the name, ie "main". This version will only analyze files with an extension of .ps1, .psm1 or .txt. .Parameter Path The path to the script file. It should have an extension of .ps1, .psm1 or .bat. .Parameter FilePath The path for the report file. The default is your WindowsPowerShell folder. This paramter has aliases of fp and out. .Example PS C:\> c:\scripts\Get-ASTScriptProfile c:\download\UnknownScript.ps1 This will analyze the script UnknownScript.ps1 and show the results in a help window. It will also create a text file in your Documents\WindowsPowerShell folder called UnknownScript.help.txt. .Example PS C:\> c:\scripts\Get-ASTScriptProfile c:\download\UnknownScript.ps1 -filepath c:\work This command is the same as the first example except the help file will be created in C:\Work. .Notes Version : 3.0 Last Updated : October 29, 2014 Author : Jeffery Hicks (http://twitter.com/jeffhicks) Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/ **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** .Inputs None .Outputs Help topic .Link Get-Command Get-Alias #> [cmdletbinding()] Param( [Parameter(Position=0,HelpMessage="Enter the path of a PowerShell script")] [ValidateScript({Test-Path $_})] [ValidatePattern( "\.(ps1|psm1|txt)$")] [string]$Path=$(Read-Host "Enter the filename and path to a PowerShell script"), [ValidateScript({Test-Path $_})] [Alias("fp","out")] [string]$FilePath = "$env:userprofile\Documents\WindowsPowerShell" ) Write-Verbose "Starting $($myinvocation.MyCommand)" #region setup profiling #need to resolve full path and convert it $Path = (Resolve-Path -Path $Path).Path | Convert-Path Write-Verbose "Analyzing $Path" Write-Verbose "Parsing File for AST" New-Variable astTokens -force New-Variable astErr -force $AST = [System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$astTokens,[ref]$astErr) #endregion #region generate AST data #include PowerShell version information Write-Verbose "PSVersionTable" Write-Verbose ($PSversionTable | Out-String) if ($ast.ScriptRequirements) { $requirements = ($ast.ScriptRequirements | Out-String).Trim() } else { $requirements = "-->None detected" } if ($ast.ParamBlock.Parameters ) { write-verbose "Parameters detected" $foundParams = $(($ast.ParamBlock.Parameters | Select Name,DefaultValue,StaticType,Attributes | Format-List | Out-String).Trim() ) } else { $foundParams = "-->None detected. Parameters for nested commands not tested." } #define the report text $report=@" This is an analysis of a PowerShell script or module. Analysis will most likely NOT be 100% thorough. "@ Write-Verbose "Getting requirements and parameters" $report+=@" REQUIREMENTS $requirements PARAMETERS $foundparams "@ Write-Verbose "Getting all command elements" $commands = @() $unresolved = @() $genericCommands = $astTokens | where {$_.tokenflags -eq 'commandname' -AND $_.kind -eq 'generic'} $aliases = $astTokens | where {$_.tokenflags -eq 'commandname' -AND $_.kind -eq 'identifier'} Write-Verbose "Parsing commands" foreach ($command in $genericCommands) { Try { $commands+= Get-Command -Name $command.text -ErrorAction Stop } Catch { $unresolved+= $command.Text } } foreach ($command in $aliases) { Try { $commands+= Get-Command -Name $command.text -erroraction Stop | foreach { #get the resolved command Get-Command -Name $_.Definition } } Catch { $unresolved+= $command.Text } } Write-Verbose "All commands" $report+=@" ALL COMMANDS All possible PowerShell commands. This list may not be complete or even correct. $(($Commands | Sort -Unique | Format-Table -autosize | Out-String).Trim()) "@ Write-Verbose "Unresolved commands" if ($unresolved) { $unresolvedText = $Unresolved | Sort -Unique | Format-Table -autosize | Out-String } else { $unresolvedText = "-->None detected" } $report+=@" UNRESOLVED These commands may be called from nested commands or unknown modules. $unresolvedtext "@ Write-Verbose "Potentially dangerous commands" #identify dangerous commands $danger="Remove","Stop","Disconnect","Suspend","Block", "Disable","Deny","Unpublish","Dismount","Reset","Resize", "Rename","Redo","Lock","Hide","Clear" $danger = $commands | where {$danger -contains $_.verb} | Sort Name | Get-Unique if ($danger) { $dangercommands = $($danger | Format-Table -AutoSize | Out-String).Trim() } else { $dangercommands = "-->None detected" } #get type names, some of which may come from parameters Write-Verbose "Typenames" $typetokens = $asttokens | where {$_.tokenflags -eq 'TypeName'} if ($typetokens ) { $foundTypes = $typetokens | Sort @{expression={$_.text.toupper()}} -unique | Select -ExpandProperty Text | foreach { "[$_]"} | Out-String } else { $foundTypes = "-->None detected" } $report+=@" TYPENAMES These are identified .NET type names that might be used as accelerators. $foundTypes "@ $report+=@" WARNING These are potentially dangerous commands. $dangercommands "@ #endregion Write-Verbose "Display results" #region create and display the result #create a help topic file using the script basename $basename = (Get-Item $Path).basename #stored in the Documents folder $reportFile = Join-Path -Path $FilePath -ChildPath "ABOUT_$basename.help.txt" Write-Verbose "Saving report to $reportFile" #insert the Topic line so help recognizes it @" TOPIC about $basename profile "@ |Out-File -FilePath $reportFile -Encoding ascii #create the report @" SHORT DESCRIPTION Script Profile report for: $Path "@ | Out-File -FilePath $reportFile -Encoding ascii -Append @" LONG DESCRIPTION $report "@ | Out-File -FilePath $reportFile -Encoding ascii -Append #view the report with Notepad Notepad $reportFile #endregion Write-Verbose "Profiling complete." } #end of function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Print-ISEFile.ps1
Print-ISEFile.ps1
#requires -version 2.0 <# Comments: This function is intended to be used in the ISE to print the current script file to the default printer. #> Function Send-ToPrinter { Param([string]$path=$PSISE.CurrentFile.FullPath) Start-Process -filepath Notepad.exe -ArgumentList "/p",$path -WindowStyle Hidden <# this is an alternative way using the default printer get-content -Path $path | out-printer #> } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Bookmarks.ps1
Bookmarks.ps1
#requires -version 4.0 #create a script bookmarking system for the PowerShell ISE Function Get-ISEBookmark { [cmdletbinding()] Param() Write-Verbose "Importing bookmarks from $MyBookmarks" Try { Import-CSV $MyBookmarks -ErrorAction Stop | Out-GridView -Title "My ISE Bookmarks" -OutputMode Single } Catch { Write-Warning "Failed to find or import bookmarks from $($MyBookmarks). Does file exist?" } } #close Get-ISEBookmark Function Open-ISEBookmark { [cmdletbinding()] Param() $bookmark = Get-ISEBookmark if ($bookmark) { Write-Verbose "Processing bookmark $($bookmark.name) for $($bookmark.path)" #open the file psedit $bookmark.path #find the file in the collection of open files $search = $psise.CurrentPowerShellTab.files.where({$_.fullpath -eq $bookmark.path}) #make the file the currently selected $psise.CurrentPowerShellTab.files.SelectedFile = $search[0] #jump to the bookmark location Write-Verbose "Jumping to line $($Bookmark.LineNumber)" $search[0].editor.SetCaretPosition($bookmark.LineNumber,1) } #if bookmark } #close Open-ISEBookmark Function Remove-ISEBookmark { [cmdletbinding(SupportsShouldProcess)] Param() $bookmark = Get-ISEBookmark if ($bookmark) { Write-Verbose "Processing bookmark $($bookmark.name) for $($bookmark.path)" $save = Import-CSV -Path $MyBookmarks | where {$_.id -notmatch $bookmark.id} Write-Verbose "Updating $MyBookmarks" $save | Export-Csv -Path $MyBookmarks -Encoding ASCII } #if bookmark } #close Remove-ISEBookmark Function Update-ISEBookmark { [cmdletbinding()] Param( [Parameter(Position=0,ValueFromPipeline)] [object]$Bookmark ) $bookmark = Get-ISEBookmark if ($bookmark) { Write-Verbose "Processing bookmark $($bookmark.name) for $($bookmark.path)" $line = New-Inputbox -Prompt "Enter the line number" -Title $MyInvocation.MyCommand -Default $Bookmark.LineNumber if ($line) { $name = New-Inputbox -Prompt "Enter the name" -Title $MyInvocation.MyCommand -Default $Bookmark.name } else { #nothing entered so bail out Write-Verbose "Cancelling" Return } If ($name) { #get all bookmarks $all = Get-content -Path $MyBookmarks | ConvertFrom-Csv #get matching bookmark by ID from CSV file $bmk = $all.where({$_.id -eq $bookmark.id}) #update the entry $bmk[0].Linenumber = $line $bmk[0].name = $name #save the results back to the file $all | Export-Csv -Path $MyBookmarks } else { #cancelling Write-Verbose "Cancelling" } } #close if bookmark } #close Update-ISEBookmark Function Add-ISEBookmark { $line = $psise.CurrentFile.Editor.CaretLine $path = $psise.CurrentFile.FullPath $name = New-Inputbox -Prompt "Enter a name or description for this bookmark." -Title "Add ISE Bookmark" $obj = [pscustomobject]@{ ID = [guid]::NewGuid().guid LineNumber = $line Name = $name Path = $Path } $obj | Export-Csv -Path $MyBookmarks -Append -Encoding ASCII } #close Add-ISEBookmark
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-PSDriveHere.ps1
New-PSDriveHere.ps1
#requires -version 2.0 Function New-PSDriveHere { <# .Synopsis Create a new PSDrive at the current location. .Description This function will create a new PSDrive at the specified location. The default is the current location, but you can specify any PSPath. The function will take the last word of the path and use it as the name of the new PSDrive. If you prefer to use the first word of the location, use -First. If you prefer to specify a totally different name, then use the -Name parameter. .Parameter Path The path for the new PSDrive. The default is the current location. .Parameter Name The name for the new PSDrive. The default is the last word in the specified location, unless you use -First. .Parameter First Use the first word of the current location for the new PSDrive. .Parameter SetLocation Set location to this new drive. .Example PS C:\users\jeff\Documents\Enterprise Mgmt Webinar> new-psdrivehere Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- Webinar 146.57 FileSystem C:\users\jeff\Documents\Enter... .Example PS C:\users\jeff\Documents\Enterprise Mgmt Webinar> new-psdrivehere -first Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- Enterprise 146.57 FileSystem C:\users\jeff\Documents\Enter... .Example PS C:\> new-psdrivehere HKLM:\software\microsoft Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- microsoft Registry HKEY_LOCAL_MACHINE\software\micr... .Example PS C:\> new-psdrivehere -Path "\\jdh-nvnas\files\powershell" -Name PSFiles Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- PSFiles FileSystem \\jdh-nvnas\files\powershell .Example PS C:\Users\Jeff\Documents\DeepDive> new-psdrivehere . DeepDive -setlocation Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- DeepDive 130.53 FileSystem C:\Users\Jeff\Documents\DeepDive PS DeepDive:\> Set a new PSDrive and change to it. .Inputs None. You cannot pipe to this function. .Outputs System.Management.Automation.PSDrive .Link http://jdhitsolutions.com/blog/2010/08/new-psdrivehere/ .Link Get-PSDrive New-PSDrive .Notes NAME: New-PSDriveHere VERSION: 2.0 AUTHOR: Jeffery Hicks LASTEDIT: Octber 15, 2011 Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/ #> [cmdletBinding(SupportsShouldProcess=$True)] Param( [Parameter(Position=0)] [ValidateScript({Test-Path $_})] [string]$Path=".", [Parameter(Position=1)] [string]$Name, [switch]$First, [Alias("cd")] [switch]$SetLocation ) #get the specified location $location=Get-Item -Path $path #did the user specify a name? if ($Name) { Write-Verbose "Name parameter used for $name" } #if $name else { if ($first) { $pattern="^\w+" } else { $pattern="\w+$" } #Make sure name contains valid characters. This function #should work for all but the oddest named folders. if ($location.Name -match $pattern) { $name=$matches[0] } else { #The location has something odd about it so bail out Write-Warning "$path doesn't meet the criteria" Break } } #else $name not specified #verify a PSDrive doesn't already exist Write-Verbose "Testing $($name):" If (-not (Test-Path -path "$($name):")) { Write-Verbose "Creating PSDrive for $name" New-PSDrive -Name $name -PSProvider $location.PSProvider -Root $Path ` -Description "Created $(get-date)" -scope Global if ($SetLocation) { Write-Verbose "Setting location to $($name):" set-location -Path "$($name):" } } else { Write-Warning "A PSDrive for $name already exists" } } #function #create an alias for the function Set-Alias -Name npsd -Value New-PSDriveHere
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/ConvertTo-CommentHelp.ps1
ConvertTo-CommentHelp.ps1
#requires -version 3.0 <# this function will make a best effort to convert help from an existing cmdlet to comment based help. This is handy when building a proxy function. Converted help will be opened in a new ISE Tab. #> Function ConvertTo-CommentHelp { Param() Add-Type -AssemblyName "microsoft.visualbasic" -ErrorAction Stop $Prompt = "Enter the name of a cmdlet. Leave blank to cancel" $Default = "" $Title = $MyInvocation.MyCommand.Name [string]$command = [microsoft.visualbasic.interaction]::InputBox($Prompt,$Title,$Default) if ($command) { Try { $help = get-help -Name $command -full -errorAction Stop } Catch { Throw $_ #bail out Return } } Else { #cancelled } If ($help) { $myHelp = @" <# .Synopsis $($help.Synopsis) .Description $($help.description.Text) $(foreach ($param in $help.parameters.parameter) { ".Parameter $($param.name)`n" "$($param.Description.Text)" "`n" }) .Inputs $(($help.inputTypes | out-string).trim()) .Outputs $(($help.returnValues | out-string).trim()) .Notes $($help.alertSet.alert | foreach {"$($_.text)`n"}) $(foreach ($item in $help.examples.example) { ".Example`n" $($item.code) "`n" $(($item.remarks| out-string).trimEnd()) "`n" }) .Link $(($help.relatedLinks | out-string).Trim()) #> "@ $myHelp | Out-ISETab } #if $help }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-InputBox.ps1
New-InputBox.ps1
Function New-Inputbox { <# .Synopsis Display a Visual Basic style inputbox. .Description This function will display a graphical Inputbox, like the one from VisualBasic and VBScript. You must specify a messag prompt. You can specify a title, the default is "Input". You can also specify a default value. The inputbox will write whatever is entered into it to the pipeline. If you click Cancel the inputbox will still write a string to the pipeline with a length of 0. It is recommended that you validate input. .Example PS C:\> $c = New-Inputbox -prompt "Enter the Netbios name of a domain computer." -title "Enter a computername" -default $env:computername PS C:\> get-service -computer $c .Notes Last Updated: Version : 0.9 .Inputs None .Outputs [string] #> [cmdletbinding()] Param ( [Parameter(Position=0,Mandatory,HelpMessage="Enter a message prompt")] [ValidateNotNullorEmpty()] [string]$Prompt, [Parameter(Position=1)] [string]$Title="Input", [Parameter(Position=2)] [string]$Default ) Try { Add-Type -AssemblyName "microsoft.visualbasic" -ErrorAction Stop [microsoft.visualbasic.interaction]::InputBox($Prompt,$Title,$Default) } Catch { Write-Warning "There was a problem creating the inputbox" Write-Warning $_.Exception.Message } } #end New-Inputbox
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Get-SearchResult.ps1
Get-SearchResult.ps1
#requires -version 4.0 Function Get-SearchResult { [cmdletbinding()] Param( [Parameter(Position=0)] [ValidateNotNullorEmpty()] [string]$Text = $psise.currentfile.editor.selectedText, [ValidateSet("Bing","Google","Yahoo")] [string]$SearchEngine="Google" ) Switch ($SearchEngine) { "Bing" { $lang = (get-culture).parent.name $url = "http://www.bing.com/search?q=$text+language%3A$lang" Break } "Google" { $url = "http://www.google.com/search?q=$text" } "Yahoo" { $url = "http://search.yahoo.com/search?p=$text" } } #switch write-Verbose "Opening $url in $SearchEngine" Start $url } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/CurrentProjects.ps1
CurrentProjects.ps1
#requires -version 4.0 <# The list is a simple text file with the complete path to scripts you are working on. #> Function Add-CurrentProject { <# .Synopsis Add the file to the current project list file .Description This command adds the current file path to the current project list. The list is simply a text file with full file names to a group of scripts that you might be working on. The ISEScriptingGeek module uses a built-in variable, $currentProjectList. .Link Edit-CurrentProject Import-CurrentProject #> [cmdletbinding()] Param( [ValidateNotNullorEmpty()] [string]$List = $currentProjectList ) #add the current file path to the list if it isn't already there If ((Get-Content -path $CurrentProjectList) -notcontains $psise.CurrentFile.FullPath) { $psise.CurrentFile.FullPath | Out-File -FilePath $list -Encoding ascii -Append } else { write-warning "$($psise.CurrentFile.FullPath) already in $list" } } #Add-CurrentProject Function Edit-CurrentProject { <# .Synopsis Edit the current project list file .Description Open the current project list in the PowerShell ISE to view or edit. You will need to manually remove items. The list is simply a text file with full file names to a group of scripts that you might be working on. The ISEScriptingGeek module uses a built-in variable, $currentProjectList. .Link Add-CurrentProject Import-CurrentProject #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory)] [ValidateScript({ if (Test-Path $_) { $True } else { Throw "Cannot validate path $_" } })] [string]$List ) psedit $list } #Edit-CurrentProject Function Import-CurrentProject { <# .Synopsis Open files from the project list .Description Read the current project list and open each file in the ISE. The list is simply a text file with full file names to a group of scripts that you might be working on. The ISEScriptingGeek module uses a built-in variable, $currentProjectList. .Link Add-CurrentProject Edit-CurrentProject #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory)] [ValidateScript({ if (Test-Path $_) { $True } else { Throw "Cannot validate path $_" } })] [string]$List ) #get the list of file paths filtering out any blank lines $items = Get-Content -Path $list | where {$_} foreach ($item in $items) { if (Test-Path $item) { psedit $item } else { write-warning "Can't find $item" } } } #Import-CurrentProject
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/CloseAllFiles.ps1
CloseAllFiles.ps1
#requires -version 4.0 #close all saved files in the ISE Function CloseAllFiles { [cmdletbinding()] Param() $saved = $psISE.CurrentPowerShellTab.Files.Where({$_.isSaved}) foreach ($file in $saved) { write-Verbose "closing $($file.FullPath)" $psISE.CurrentPowerShellTab.files.Remove($file) | out-null } } #end function #close all other saved files except for the active file Function CloseAllFilesButCurrent { [cmdletbinding()] Param() $saved = $psISE.CurrentPowerShellTab.Files.Where({$_.isSaved -AND $_.fullpath -ne $psISE.CurrentFile.FullPath }) foreach ($file in $saved) { write-Verbose "closing $($file.FullPath)" $psISE.CurrentPowerShellTab.files.Remove($file) | out-null } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/ConvertFrom-Alias.ps1
ConvertFrom-Alias.ps1
#requires -version 2.0 Function ConvertFrom-Alias { Param ( [Parameter(Position=0)] [ValidateNotNullorEmpty()] $Text=$psISE.CurrentFile.Editor.text ) #make sure we are using the ISE if ($host.name -match "ISE"){ #Turn the script into syntax tokens Write-Verbose "Tokenizing" #verify there are no syntax errors first by Tokenizing the script $out=$null $tokens = [System.Management.Automation.PSparser]::Tokenize($text, [ref]$out) #if there are errors they will be directed to $out if ($out) { #enumerate each parsing error in $out foreach ($problem in $out) { Write-Warning $problem.message Write-Warning "Line: $($problem.Token.Startline) at character: $($problem.token.StartColumn)" } } else { #if no errors then proceed to convert $tokens | Where-Object { $_.Type -eq 'Command'} | Sort-Object StartLine, StartColumn -Descending | ForEach-Object { #handle the ? by escaping it if($_.content -eq '?') { Write-Verbose "Found a ?" $result = Get-Command -name '`?' -CommandType Alias } else { $result = Get-Command -name $_.Content -CommandType Alias -ErrorAction SilentlyContinue } #check and see if Get-Command returned anything if($result) { #find each command and insert the corresponding command definition Write-Verbose "Replacing $($result.name) with $($result.definition)" $psISE.CurrentFile.Editor.Select($_.StartLine,$_.StartColumn,$_.EndLine,$_.EndColumn) $psISE.CurrentFile.Editor.InsertText($result.Definition) } } #foreach } #else $tokens exists and there were no parsing errors } #if ISE else { Write-Warning "You must be using the PowerShell ISE" } Write-Verbose "Finished" } #end Function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-CommentHelp.ps1
New-CommentHelp.ps1
#requires -version 4.0 # Comments: This will generate comment based help based on a loaded command. #This works best in the ISE with your function already loaded. Function New-CommentHelp { Param( [Parameter(Position=0,Mandatory,HelpMessage = "What is the name of your function or command?" )] [ValidateNotNullorEmpty()] [string]$Name, [Parameter(Position=1,Mandatory,HelpMessage = "Enter a brief synopsis" )] [ValidateNotNullorEmpty()] [string]$Synopsis, [Parameter(Position=2,Mandatory,HelpMessage = "Enter a description. You can expand and edit later" )] [ValidateNotNullorEmpty()] [string]$Description ) #define beginning of comment based string $comment=@" <# .SYNOPSIS {0} .DESCRIPTION {1} "@ #Create comment based help string $help = $comment -f $synopsis,$description #test if command is loaded and if so get parameters #ignore common: $common = "VERBOSE|DEBUG|ERRORACTION|WARNINGACTION|ERRORVARIABLE|WARNINGVARIABLE|OUTVARIABLE|OUTBUFFER|PIPELINEVARIABLE|WHATIF|CONFIRM|INFORMATIONVARIABLE|INFORMATIONACTION" Try { $command = Get-Command -Name $name -ErrorAction Stop $params = $command.parameters.keys | where {$_ -notmatch $common} } Catch { #otherwise prompt $scriptname = Read-Host "If your command is a script file, enter the full file name with extension. Otherwise leave blank" if ($scriptname) { Try { $command = Get-Command -Name $scriptname -ErrorAction Stop $params = $command.parameters.keys | where {$_ -notmatch $common} } Catch { Write-Warning "Failed to find $scriptname" #BAIL OUT Return } } #if $scriptname else { #prompt for a comma separated list of parameter names $EnterParams = Read-Host "Enter a comma separated list of parameter names" $Params = $EnterParams.Split(",") } } #get parameters from help or prompt for comma separated list if ($params) { Foreach ($param in $params) { #get aliases from the command $aliases = $command.parameters[$param].aliases #get parameter attribute $pa = $command.parameters[$param].Attributes | where {$_.GetType().name -eq "ParameterAttribute"} #extract any parameter help messages if ($pa.HelpMessage) { [string]$paramDesc = $pa.HelpMessage } if ($aliases) { $paramDesc+= " This command has aliases of: $($aliases -join ",")" } #define a new line #this must be left justified to avoid a parsing error $paramHelp=@" .PARAMETER $Param $paramDesc "@ #append the parameter to the help comment $help+=$paramHelp } #foreach param } #if $params #Define a default example using the command name #this must be left justified to avoid a parsing error $exHelp=@" .EXAMPLE PS C:\> $Name "@ #add the example to the help comment $help+=$exHelp #stuff for the Notes section $version = "1.0" $verDate=(Get-Date).ToShortDateString() #construct a Notes section $NoteHere=@" .NOTES NAME : {0} VERSION : {1} LAST UPDATED: {2} AUTHOR : {3}\{4} Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/ **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** "@ #insert the values $Notes = $NoteHere -f $Name,$version,$verDate,$env:userdomain,$env:username #add the section to help $help+= $Notes #define a here string for any links you might want to add $linkHelp=@" .LINK "@ #add the section to help $help+= $linkHelp #} #Inputs $inputHelp=@" .INPUTS "@ $help+= $InputHelp #outputs $outputHelp=@" .OUTPUTS "@ $help+= $OutputHelp #close the help comment $help+= "#>" #if ISE insert into current file if ($psise) { $psise.CurrentFile.Editor.InsertText($help) | Out-Null } else { #else write to the pipeline $help } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Sign-ISEScript.ps1
Sign-ISEScript.ps1
#requires -version 2.0 Function Write-Signature { Param() Set-StrictMode -Version Latest #get the certificate $cert = Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert If ($cert.Count -eq '0') { Write-Warning 'No code signing certificate found.' Exit } ElseIf ($cert.Count -gt '1') { $cert = ($cert | Out-GridView -Title 'Select the desired code signing certificate' -OutputMode Single) } #save the file if necessary if (!$psise.CurrentFile.IsSaved) { $psise.CurrentFile.Save() } #if the file is encoded as BigEndian, resave as Unicode if ($psise.CurrentFile.Encoding.EncodingName -match "Big-Endian") { $psise.CurrentFile.Save([Text.Encoding]::Unicode) | Out-Null } #save the filepath for the current file so it can be re-opened later $filepath=$psise.CurrentFile.FullPath #sign the file Try { Set-AuthenticodeSignature -FilePath $filepath -Certificate $cert -errorAction Stop #close the file $psise.CurrentPowerShellTab.Files.Remove(($psise.CurrentFile)) | Out-Null #reopen the file $psise.CurrentPowerShellTab.Files.Add(($filepath)) | Out-Null } Catch { Write-Warning ("Script signing failed. {0}" -f $_.Exception.message) } }#end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Copy-ToWord.ps1
Copy-ToWord.ps1
#requires -version 3.0 #this is an ISE only function #copy selected ISE text to Microsoft Word Function Copy-ToWord { [cmdletbinding()] Param( [ValidatePattern("\S+")] [string[]]$Text = $psise.CurrentFile.Editor.SelectedText, [switch]$Colorized ) If (($global:word.Application -eq $Null) -OR -NOT (Get-Process WinWord)) { #remove any variables that might be left over just to be safe Remove-Variable -Name doc,selection -Force -ErrorAction SilentlyContinue #create a Word instance if the object doesn't already exist $global:word = New-Object -ComObject word.application #create a new document $global:doc = $global:word.Documents.add() #create a selection $global:selection = $global:word.Selection #set font and paragraph for fixed width content $global:selection.Font.Name = "Consolas" $global:selection.font.Size = 10 $global:selection.paragraphFormat.SpaceBefore = 0 $global:selection.paragraphFormat.SpaceAfter = 0 #show the Word document $global:word.Visible = $True } if ($Colorized) { #copy the selection to the clipboard and paste #This is a shortcut hack that may not always work the first time $wshell = New-Object -ComObject Wscript.shell #must be lower-case c otherwise you will end up sending #ctrl+shift+c $wshell.SendKeys("^c") #timing is everything with SendKeys. This could be a lower value start-sleep -Milliseconds 500 $global:selection.Paste() } else { #insert the text $global:selection.TypeText($text) } #insert a new paragraph (ENTER) $global:selection.TypeParagraph() } #end Function #add to menu #$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word",{Send-ToWord},"Ctrl+Alt+W") | Out-Null #keyboard shortcut doesn't always work #$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word Colorized",{Send-ToWord -Colorized},"") | Out-Null
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/ConvertAll.ps1
ConvertAll.ps1
#requires -version 2.0 #converts all command aliases in selected text to their corresponding command #definition Function ConvertTo-Definition { [cmdletbinding()] Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a string to convert")] [string]$Text ) if ($host.name -match "ISE") { Write-Verbose "Getting aliases" $aliases = get-alias | where {$_.name -notmatch "\?|\%"} foreach ($alias in $aliases) { #write-verbose $alias.name #match any alias on a word boundary that doesn't start with a $ if ($Text -match "(m?)(?<=\b)(?<!-|\$)$($alias.name)(?=\b)(?!-)") { Write-Verbose ("Replacing {0} with {1}" -f $alias.name,$alias.Definition) $Text=$Text -replace "(m?)(?<=\b)(?<!-|\$)$($alias.name)(?=\b)(?!-)",$alias.definition } } #foreach #handle special cases of ? and % if ($Text -match "\?") { Write-Verbose "Replacing with Where-Object" $Text=$Text -replace "\?","Where-Object" } if ($Text -match "\%") { Write-Verbose "Replacing with ForEach-Object" $Text=$Text -replace "\%","ForEach-Object" } #write the replacement string to the current file $psise.currentfile.editor.insertText($Text) write-verbose $text } #if ISE else { Write-Warning "You must be using the PowerShell ISE" } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Convert-CommandToHash.ps1
Convert-CommandToHash.ps1
#requires -version 3.0 #Convert the named parameter part of a command into a hash table in the ISE Function Convert-CommandtoHash { [cmdletbinding()] Param( [ValidateNotNullorEmpty()] [string]$Text = $psise.currentfile.editor.SelectedText ) Set-StrictMode -Version latest New-Variable astTokens -force New-Variable astErr -force Write-verbose "Converting $text" $ast = [System.Management.Automation.Language.Parser]::ParseInput($Text,[ref]$astTokens,[ref]$astErr) #resolve the command name $cmdType = Get-Command $asttokens[0].text if ($cmdType.CommandType -eq 'Alias') { $cmd = $cmdType.ResolvedCommandName } else { $cmd = $cmdType.Name } Write-Verbose "Command is $cmd" Write-Verbose ($astTokens | out-string) #last item is end of input token $r= for ($i = 1;$i -lt $astTokens.count-2 ;$i++) { if ($astTokens[$i].ParameterName) { $p = $astTokens[$i].ParameterName write-verbose "Parameter name = $p" write-verbose ($astTokens[$i] | out-string) $v="" #check next token if ($astTokens[$i+1].Kind -match 'Parameter|NewLine|EndOfInput') { #the parameter must be a switch $v= "`$True" } else { While ($astTokens[$i+1].Kind -notmatch 'Parameter|NewLine|EndOfInput') { #break out of loop if there is no text write-verbose "While: $($astTokens[$i])" $i++ #test if value is a string and if it is quoted, if not include quotes if ($astTokens[$i].Text -match "\D" -AND $astTokens[$i].Text -notmatch """\w+.*""" -AND $astTokens[$i].Text -notmatch "'\w+.*'") { #ignore commas and variables if ($astTokens[$i].Kind -match 'Comma|Variable') { $value = $astTokens[$i].Text } else { #Assume text and quote it Write-Verbose "Quoting $($astTokens[$i].Text)" $value="'$($astTokens[$i].Text)'" } } else { Write-Verbose "Using text as is for $($astTokens[$i].Text)" $value = $astTokens[$i].Text } Write-Verbose "Adding $Value to `$v" $v+= $value } } #while "$p = $v`r" Write-Verbose "hashentry -> $p = $v`r" } } #for Write-Verbose "Finished processing AST" Write-verbose ($r | out-string) #create text $hashtext = @" `$paramHash = @{ $r} $cmd @paramHash "@ #insert the text which should replace the highlighted line $psise.CurrentFile.Editor.InsertText($hashtext) }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Convert-CodetoSnippet.ps1
Convert-CodetoSnippet.ps1
#requires -version 3.0 Function Convert-CodetoSnippet { [cmdletbinding(SupportsShouldProcess=$True)] Param( [Parameter(Position=0,Mandatory=$True, HelpMessage="Enter some code text or break, select text in the ISE and try again.")] [ValidateNotNullorEmpty()] [string]$Text ) Add-Type -AssemblyName "Microsoft.VisualBasic" $title = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a title for your snippet",$MyInvocation.mycommand.name) if ($title) { $description = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a description for your snippet",$MyInvocation.mycommand.name,"This is required") if ($description) { $author = [Microsoft.VisualBasic.Interaction]::InputBox("Enter an author for your snippet",$MyInvocation.mycommand.name,$env:username) if (!$author) { $author=" " } #if author } #if description else { #if no description assume user cancelled Write-Warning -Message "No description was specified. Operation cancelled." Return } if ($PSCmdlet.ShouldProcess($title) ) { Try { New-IseSnippet -Title $title -Text $Text -description $Description -author $Author } Catch { $message = ("There was an error creating the snippet. `n`n{0} `n`nDo you want to force an overwrite?" -f $_.exception.message) $returnValue=[microsoft.visualbasic.interaction]::Msgbox($message,"YesNo,Exclamation",$MyInvocation.MyCommand.name) if ($returnValue -eq "yes") { #re-run the command but this time with -Force New-IseSnippet -Title $title -Text $Text -description $Description -author $Author -Force } } } #shouldprocess } } #end Convert-CodeToSnippet Set-Alias ccs Convert-CodeToSnippet
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Get-ScriptComments.ps1
Get-ScriptComments.ps1
#requires -version 4.0 #parse a script file for comments only Function Get-ScriptComments { <# .Synopsis Get comments from a PowerShell script file. .Description This command will use the AST parser to go through a PowerShell script, either a .ps1 or .psm1 file, and display only the comments. .Example PS C:\> get-scriptcomments c:\scripts\MyScript.ps1 #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory,HelpMessage="Enter the path of a PS1 file", ValueFromPipeline,ValueFromPipelineByPropertyName)] [Alias("PSPath","Name")] [ValidateScript({Test-Path $_})] [ValidatePattern("\.ps(1|m1)$")] [string]$Path ) Begin { #Begin scriptblock Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" #initialization commands #explicitly define some AST variables New-Variable astTokens -force New-Variable astErr -force } #close begin Process { #Process scriptblock #convert each path to a nice filesystem path $Path= Convert-Path -Path $Path Write-Verbose -Message "Parsing $Path" #Parse the file $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$astTokens,[ref]$astErr) #filter tokens for comments and display text $asttokens.where({$_.kind -eq 'comment'}) | Select-Object -ExpandProperty Text } #close process End { #end scriptblock #ending the function Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" } #close end } #close function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Out-ISETab.ps1
Out-ISETab.ps1
#requires -version 2.0 <# This function will take pipelined input and insert into a new PowerShell ISE tab #> Function Out-ISETab { <# .Synopsis Send command output to an ISE tab .Description This command will accept pipelined input and place it in a new PowerShell ISE tab. .Parameter UseCurrentFile Insert the text into the current ISE tab. .Example PS C:\> get-process | sort WS -descending | Select -first 5 | out-isetab .Notes version 2.0 updated May 20, 2014 Learn more: PowerShell in Depth: An Administrator's Guide, 2nd Edition (http://www.manning.com/jones6/) PowerShell Deep Dives (http://manning.com/hicks/) Learn PowerShell 3 in a Month of Lunches (http://manning.com/jones3/) Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/) **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** #> [cmdletbinding()] Param ( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$True)] [object[]]$InputObject, [Switch]$UseCurrentFile ) Begin { Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" if ($UseCurrentFile) { Write-Verbose "Using current file" $tab= $psise.CurrentFile } else { #create a new file Write-Verbose "Creating a new tab" $tab= $psise.CurrentPowerShellTab.Files.Add() } $data = @() } Process { #add each piped object $data+= $InputObject } #process End { #send the data to the ISE tab $tab.Editor.InsertText(($data | Out-String)) Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" } } #end function Set-Alias -Name tab -Value Out-ISETab
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Edit-Snippet.ps1
Edit-Snippet.ps1
#requires -version 4.0 <# view snippets and edit selected in the PowerShell ISE Changes won't be effective until the next ISE session or tab #> Function Edit-Snippet { Param( [string]$Path = "$env:userprofile\Documents\WindowsPowerShell\Snippets" ) #display snippets by name without the .snippet.ps1xml extension $snips = dir $path | Select @{Name="Name";Expression={$_.name.split(".")[0]}} | Out-Gridview -title "Select one or more snippets to edit" -OutputMode Multiple foreach ($snip in $snips) { $file = join-path -Path $path -ChildPath "$($snip.name).snippets.ps1xml" psedit $file } }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/ConvertTo-TextFile.ps1
ConvertTo-TextFile.ps1
#requires -version 2.0 Function ConvertTo-TextFile { Param ( [switch]$Reload ) #verify we are in the ISE if ($psise) { #get the current file name and path and change the extension $psVersion=$psise.CurrentFile.FullPath $textVersion=$psversion -replace "ps1","txt" #save the file. $psise.CurrentFile.SaveAs($textVersion) #if -Reload then reload the PowerShell file into the ISE if ($Reload) { $psise.CurrentPowerShellTab.Files.Add($psVersion) } } #if $psise else { Write-Warning "This function requires the Windows PowerShell ISE." } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Open-SelectedInISE.ps1
Open-SelectedInISE.ps1
#requires -version 3.0 #open selected file in an ISE Tab. #modified to trim off any extra spaces and write if warning if file not found Function Open-SelectedISE { [cmdletbinding()] Param([string]$Text = $psise.CurrentFile.Editor.SelectedText) #trim off any spaces $file = $Text.Trim() if (Test-Path -Path $file ) { psedit $file } else { Write-Warning "Can't find $file" } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Find-InFile.ps1
Find-InFile.ps1
#Requires -version 3.0 Function Find-InFile { [cmdletbinding()] Param() Set-StrictMode -Version Latest Write-Verbose "Starting $($myinvocation.mycommand)" #verify we are in the ISE if ($host.name -match "ISE") { $Title = "Find in Files" #prompt for file types to search $Prompt = "Enter a path and file types to search. Leave blank to cancel" $Default = ".\*.ps1" $path = New-Inputbox -prompt $prompt -title $Title -default $Default if ($path) { #prompt for what to search for $Prompt = "What do you want to search for" $Default= $Null $find = New-Inputbox -prompt $prompt -title $Title -default $Default #execute search $results= Select-String -Pattern $find -Path $path | Select Path,Filename, @{Name="Line";Expression={$_.Line.Trim()}},LineNumber | Out-Gridview -Title "Select one or more matching files" -OutputMode Multiple #open files and jump to matching line foreach ($item in $results) { Write-Verbose ($item | out-string) psedit $item.path #give file a chance to open start-sleep -Milliseconds 100 #get current files $f = $psise.CurrentPowerShellTab.Files #select the last one $psise.CurrentPowerShellTab.Files.SelectedFile = $f[-1] #set the cursor $psise.CurrentPowerShellTab.files.SelectedFile.Editor.SetCaretPosition($item.linenumber,1) } } } else { Write-Warning "This version only works in the PowerShell ISE" } Write-Verbose "Ending $($myinvocation.mycommand)" }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Convert-AliasDefinition.ps1
Convert-AliasDefinition.ps1
#requires -version 2.0 Function Convert-AliasDefinition { [cmdletBinding(DefaultParameterSetName="ToDefinition")] Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a string to convert")] [string]$Text, [Parameter(ParameterSetName="ToAlias")] [switch]$ToAlias, [Parameter(ParameterSetName="ToDefinition")] [switch]$ToDefinition ) #make sure we are using the ISE if ($host.name -match "ISE") { Try { #get alias if it exists otherwise throw an exception that #will be caught if ($ToAlias) { #get alias by definition and convert to name $alias=get-alias -definition $Text -ErrorAction Stop #there might be multiples so use the first one found if ($alias -is [array]) { $replace=$alias[0].name } else { $replace=$alias.name } } else { #get alias by name and convert to definition #if the text is ?, this is a special character so #we'll just assume it is Where-Object if ($Text -eq "?") { $Replace="Where-Object" } else { $alias= Get-Alias -name $Text -ErrorAction Stop $replace=$alias.definition } } #Else ToDefinition } #close Try Catch { Write-Host "Nothing for for $text" -ForegroundColor Cyan } #make changes if an alias was found If ($replace) { #Insert the replacment $psise.currentfile.editor.insertText($replace) } } #if ISE else { Write-Warning "You must be using the PowerShell ISE" } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-ISEFunction.ps1
New-ISEFunction.ps1
Function New-Function { $name= Read-Host "What do you want to call the new function?" $functionText=@" #requires -version 4.0 # ----------------------------------------------------------------------------- # Script: $name.ps1 # Author: $env:username # Date: $((get-date).ToShortDateString()) # Keywords: # Comments: # # ----------------------------------------------------------------------------- Function $name { <# .Synopsis This... .Description A longer explanation .Parameter FOO The parameter... .Example PS C:\> FOO Example- accomplishes .Notes NAME: $Name VERSION: 1.0 AUTHOR: Jeffery Hicks LASTEDIT: $(Get-Date) .Link .Inputs .Outputs #> [cmdletBinding()] Param( [Parameter(Position=0,Mandatory=`$False,ValueFromPipeline=`$True)] [string[]]`$FOO ) Begin { Write-Verbose "`$(Get-Date) Starting `$(`$myinvocation.mycommand)" } #close Begin Process { Foreach (`$item in `$FOO) { }#close Foreach item } #close process End { Write-Verbose "`$(Get-Date) Ending `$(`$myinvocation.mycommand)" } #close End } #end Function "@ $psise.CurrentFile.Editor.InsertText($FunctionText) } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/Convert-ISEComment.ps1
Convert-ISEComment.ps1
#requires -version 3.0 #convert selected text into a multi-line comment Function ConvertTo-MultiLineComment { [cmdletbinding()] Param([string]$Text = $psise.CurrentFile.Editor.SelectedText) if ($text -match "^<#" -AND $text -match "#>$") { Write-Warning "Selected text already appears to be a multiline comment" } elseif ($text -match "^#") { #strip off # in text $text = $text.Replace("#","") $replace="<#`n$text`n#>" } else { $replace=@" <# $Text #> "@ } #else if ($replace) { $psise.currentfile.editor.InsertText($replace) } } #end function Function ConvertFrom-MultiLineComment { [cmdletbinding()] Param([string]$Text = $psise.CurrentFile.Editor.SelectedText) #trim off leading and trailing spaces $MyText = $Text.Trim() if ($MyText.StartsWith("<#") -AND $MyText.EndsWith("#>")) { #get everything between the first 2 and last 2 characters $replace = $myText.Substring(2,$MyText.length -4) #insert a #character [string[]]$newText = $replace.split("`n") | select -Skip 1 -First ($MyText.Split("`n").count-2) | foreach {("#$_").Trim()} $psise.currentfile.editor.InsertText(($newtext.trim() | out-string)) } else { Write-Warning "Could not detect that selected text is a multiline comment" } } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/get-commandmetadata.ps1
get-commandmetadata.ps1
#requires -version 3.0 #run this in the PowerShell ISE for best results Function Get-CommandMetadata { <# .Synopsis Create a proxy function of a PowerShell command. .Description This command will create a proxy version of a PowerShell cmdlet, function or alias. The intent is to simplify creating a new function from command metadata. You can give your command and opt to remove help references for the original command. If you run this in the PowerShell ISE, code for the new function will be inserted into a new Powershell tab. .Parameter Command The name of a PowerShell command to proxy. This can be a cmdlet, function or alias. .Parameter NewName The name you want to use for your new command. .Parameter NoHelp Remove references to existing command help. Using this parameter will insert a comment-based help outline. .Example PS C:\> Get-CommandMetadata Get-WMIObject -nohelp -newname Get-MyOS Create a proxy function for Get-WMIObject that will be called Get-MyOS. Help references will be replaced with a comment-help block. .Notes Last Updated: Sept. 3, 2014 Version : 1.1 .Link http://jdhitsolutions.com/blog/2014/09/friday-fun-creating-powershell-scripts-with-powershell #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory,HelpMessage="Enter the name of a PowerShell command")] [ValidateNotNullorEmpty()] [string]$Command, [string]$NewName, [switch]$NoHelp ) Try { Write-Verbose "Getting command metadata for $command" $gcm = Get-Command -Name $command -ErrorAction Stop #allow an alias or command name if ($gcm.CommandType -eq 'Alias') { $cmdName = $gcm.ResolvedCommandName } else { $cmdName = $gcm.Name } Write-Verbose "Resolved to $cmdName" $cmd = New-Object System.Management.Automation.CommandMetaData ($gcm) } Catch { Write-Warning "Failed to create command metadata for $command" Write-Warning $_.Exception.Message } if ($cmd) { #create the metadata if ($NewName) { $Name = $NewName } else { $Name = $cmd.Name } if ($noHelp) { #remove help link $cmd.HelpUri = $Null Write-Verbose "Defining a new comment based help block" #define outline for comment based help $myHelp = @" .Synopsis PUT SYNTAX HERE .Description PUT DESCRIPTION HERE .Notes Created:`t$(Get-Date -format d) .Example PS C:\> $Name .Link $cmdname "@ Write-Verbose "Creating proxy command with help" $metadata = [System.Management.Automation.ProxyCommand]::Create($cmd,$myHelp) } #nohelp else { Write-Verbose "Creating proxy command" $metadata = [System.Management.Automation.ProxyCommand]::Create($cmd) } Write-Verbose "Cleaning up parameter names" [regex]$rx="[\s+]\$\{\w+\}[,|)]" $metadata = $metadata.split("`n") | foreach { If ($rx.ismatch($_)) { #strip off { } around parameter names $rx.Match($_).Value.Replace("{","").Replace("}","") # "`n" } else { #just write the line $_ } } #foreach #define the text for the new command $text = @" #requires -version $($PSVersionTable.psversion) Function $Name { $metadata } #end function $Name "@ if ($host.Name -match "PowerShell ISE") { #open in a new ISE tab $tab = $psise.CurrentPowerShellTab.Files.Add() Write-Verbose "Opening metadata in a new ISE tab" $tab.editor.InsertText($Text) #jump to the top $tab.Editor.SetCaretPosition(1,1) } else { $Text } } Write-Verbose "Ending $($MyInvocation.MyCommand)" } #end function Set-Alias -Name gcmd -Value Get-CommandMetaData
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/CycleISETabs.ps1
CycleISETabs.ps1
#requires -version 3.0 #cycle through PowerShell Tabs #this needs to be in your PowerShell ISE profile to work properly Function Get-NextISETab { [cmdletbinding()] Param() $iseTabs = $psISE.PowerShellTabs #get current tab for ($i=0; $i -le $iseTabs.count-1; $i++) { Write-Verbose $iseTabs[$i].Displayname if ($iseTabs[$i].Displayname -eq $psISE.CurrentPowerShellTab.DisplayName) { $current = $i } } #check if the next index number if valid if ($current++ -ge $iseTabs.count-1) { $next = 0 } else { $next = $current++ } $nextTab = $iseTabs[$next] $iseTabs.SelectedPowerShellTab = $NextTab }
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-DSCResourceSnippet.ps1
New-DSCResourceSnippet.ps1
#requires -version 4.0 #requires -module PSDesiredStateConfiguration Function New-DSCResourceSnippet { <# .Synopsis Create ISE snippets for DSC Resources .Description This command will convert the syntax for a DSC resource into an ISE snippet. Snippets will be created in the default location. Snippet names will take the name "DSC <resource name>". The snippet description uses the format "<Resource Name> resource from module <module name> <vendor>". You will end up with a description like this: xWinEventLog resource from module xWinEventLog Microsoft Corporation You must run this command in the PowerShell ISE. .Example PS C:\> New-DSCResourceSnippet -name xsmbshare -author "Jeff Hicks" -passthru Directory: C:\Users\Jeff\documents\WindowsPowerShell\Snippets Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 10/20/2014 8:48 AM 1157 DSC xSmbShare Resource.snippets.ps1xml Create a snippet from a single resource. .Example PS C:\> Get-DSCResource | New-DSCResourceSnippet This command will create snippets for every installed DSC resource. Existing snippet files will be overwritten. .Notes Last Updated: October 20, 2014 Version : 1.0 Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/ **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** .Link Get-DSCResource New-ISESnippet #> [cmdletbinding(SupportsShouldProcess=$True,DefaultParameterSetName="Name")] Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter the name of a DSC resource", ParameterSetName="Name")] [ValidateNotNullorEmpty()] [string[]]$Name, [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter the name of a DSC resource", ValueFromPipeline=$True,ParameterSetName="Resource")] [ValidateNotNullorEmpty()] [Microsoft.PowerShell.DesiredStateConfiguration.DscResourceInfo[]] $DSCResource, [ValidateNotNullorEmpty()] [string]$Author = $env:username, [Switch]$Passthru ) Begin { Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" } #begin Process { if ($PSCmdlet.ParameterSetName -eq 'Name') { #get the resource from the name Try { Write-Verbose "Getting DSC Resource $Name" $DSCResource = Get-DscResource -Name $Name -ErrorAction Stop } Catch { Throw } } foreach ($resource in $DSCResource) { #create the entry based on resource properties [string[]]$entry = "`n$($resource.name) <ResourceID> {`n" Write-Verbose "Creating resource entry for $($resource.name)" $entry+= "`t#from module $($resource.module.name)" $entry+= foreach ($item in $resource.Properties) { if ($item.IsMandatory) { $resourcename="`t*$($item.name)" } else { $resourcename = "`t$($item.name)" } if ($item.PropertyType -eq '[bool]') { $possibleValues = "`$True | `$False" } elseif ($item.values) { $possibleValues = "'$($item.Values -join "' | '")'" } else { $possibleValues=$item.PropertyType } "$resourcename = $($possibleValues)" } #foreach $entry+="`n} #end $($resource.name) resource`n`n" $title = "DSC $($resource.name) Resource" $description = "$($resource.name) resource from module $($resource.module) $($resource.CompanyName)" Write-Verbose "Creating snippet $title" Write-Verbose $description Write-Verbose ($entry | Out-String) $paramHash = @{ Title = $Title Description = $description Text = ($Entry | Out-String) Author = $Author Force = $True ErrorAction = "Stop" } Write-Verbose ($paramHash | Out-String) if ($PSCmdlet.ShouldProcess($Resource.name)) { Try { Write-Debug "Creating snippet file" New-IseSnippet @paramHash if ($Passthru) { #build the path $snippath = join-path -path "$env:Userprofile\documents\WindowsPowerShell\Snippets" -ChildPath "$title.snippets.ps1xml" Get-Item -path $snippath } } Catch { Throw } } #if shouldprocess } #foreach resource } #process End { #import the new snippets into the current session. They will #automatically be loaded next time. Write-Verbose "Importing new snippets" Import-IseSnippet -Path "$env:Userprofile\documents\WindowsPowerShell\Snippets" Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" } #end } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/CIMScriptMaker.ps1
CIMScriptMaker.ps1
#requires -version 3.0 <# Version: 3.0 Author : Jeff Hicks @jeffhicks http://jdhitsolutions.com/blog "Those who forget to script are doomed to repeat their work." Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/ **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** #> Function New-CIMCommand { Param([string]$computername = $env:COMPUTERNAME) Function Get-Namespace { #this function will recursively enumerate namespaces Param( [string]$Namespace="Root", [Microsoft.Management.Infrastructure.CimSession]$CimSession ) $nspaces = $cimsession | Get-CimInstance -Namespace $Namespace -ClassName __Namespace foreach ($nspace in $nspaces) { $child = Join-Path -Path $Namespace -ChildPath $nspace.Name $child Get-Namespace $child $CimSession } } #create a CIMSession $cimsess = New-CimSession -ComputerName $computername #browse namespaces Write-Host "Enumerating namspaces on $computername....please wait..." -ForegroundColor Cyan $ns = Get-Namespace -CimSession $cimsess | Sort | Out-GridView -Title "$($cimsess.Computername): Select a namespace" -OutputMode Single if ($ns) { #get classes filtering out system classes Write-Host "Enumerating classes...please wait..." -ForegroundColor Cyan $class = $cimsess | Get-CimClass -Namespace $ns | Where {$_.cimclassname -notmatch "^__" -AND $_.CimClassProperties.Name -notcontains "Antecedent"} | Sort CimClassName | Select CimClassName,CimClassProperties | Out-GridView -Title "$NS : Select a class name" -OutputMode Single } if ($class) { #create a VBScript message box $wshell = New-Object -ComObject "Wscript.Shell" $r = $wshell.Popup("Do you want to test this class?",-1,$class.CimClassname,32+4) if ($r -eq 6) { #Yes $test = $cimsess | Get-CimInstance -Namespace $ns -ClassName $class.CimClassName if ($test) { $test | Out-GridView -Title "$NS\$($Class.cimClassName)" -Wait $prompt="Do you want to continue?" $icon=32+4 } else { $prompt="No results were returned. Do you want to continue?" $icon=16+4 } $r = $wshell.Popup($prompt,-1,$class.CimClassname,$icon) if ($r -eq 7) { Write-Host "Exiting. Please try again later." -ForegroundColor Yellow #bail out Return } } #if r = 6 #define basic command $cmd = "Get-CimInstance @cimParam" #create a filter $filterProperty = $class.CimClassProperties | Select Name,CimType,Flags | Out-GridView -Title "Select a property to filter on or cancel to not filter." -OutputMode Single if ($filterProperty) { $operator = "=","<",">","<>",">=","<=","like" | Out-GridView -Title "Select an operator. Default if you cancel is =" -OutputMode Single #create a VBSCript inputbox Add-Type -AssemblyName "microsoft.visualbasic" -ErrorAction Stop $Prompt = "Enter a value for your filter. If using a string, wrap the value in ''. If using Like, use % as the wildcard character." $title= "-filter ""$($filterproperty.Name) $operator ?""" $value=[microsoft.visualbasic.interaction]::InputBox($Prompt,$Title) $filter = "-filter ""$($filterproperty.Name) $operator $value""" $cmd+=" $filter" } #if filterproperty #show properties Write-Host "Getting class properties" -ForegroundColor Cyan $properties = $class.CimClassProperties | select Name,CimType,Flags | Out-Gridview -Title "$($class.CimClassName) : Select one or more properties. Cancel will select *" -PassThru if ($properties) { $select = $properties.name -join "," $cmd+= @" | Select-Object -property $select,PSComputername "@ } #if properties } #if $class #define a name for the function using the class name #remove _ from class name $cname = $class.CimClassName.Replace("_","") $cmdName = "Get-$cname" #the auto-generated PowerShell code $myScript = @" #Requires -version 3.0 Function $cmdName { <# .Synopsis Get $($Class.CimClassName) information .Description This command uses the CIM cmdlets to query a remote computer for information from the $($Class.CimClassName) class in the $NS namespace. This command requires PowerShell 3.0 or later. .Parameter Computername The name of a computer to query. It should be running PowerShell 3.0 or later. This parameter also supports aliases of CN and Host. .Parameter CimSession A previously created CimSession. Works best when you pipe the CimSession to this command. See examples. .Example PS C:\> $cmdName Run the command defaulting to the local computername. .Example PS C:\> Get-CimSession | $cmdName | Out-Gridview -title $cmdName Get all CIMSessions and pipe them to this command sending results to Out-Gridview. .Notes Version : 1.0 Author : $($env:userdomain)\$($env:username) Last Updated: $((Get-Date).ToShortDateString()) .Inputs String or CimSession .Outputs CIMObject or custom object .Link Get-CimInstance Get-CimSession #> [cmdletbinding(DefaultParameterSetName="Computer")] Param( [Parameter(Position=0,ValueFromPipelinebyPropertyName=`$True, ParameterSetName="Computer")] [ValidateNotNullorEmpty()] [Alias("CN","Host")] [string[]]`$Computername=`$env:Computername, [Parameter(Position=0,ValueFromPipeline=`$True, ParameterSetName="Session")] [string[]]`$CimSession ) Begin { Write-Verbose "Starting command `$(`$MyInvocation.Mycommand)" #create a hashtable of parameters to splat against Get-CimInstance `$cimParam=@{ Namespace = "$NS" ClassName = "$($Class.CimClassName) " ErrorAction = "Stop" } } #begin Process { if (`$computername) { `$cimParam.Computername=`$computername Write-Verbose "Processing `$Computername" } else { #must be a cimsession `$cimParam.CIMSession=`$CimSession Write-Verbose "Processing `$(`$CimSession.ComputerName)" } Try { $cmd } #try Catch { Write-Warning "Failed to retrieve information. `$(`$_.Exception.Message)" } #catch } #Process End { Write-Verbose "Ending command `$(`$MyInvocation.Mycommand)" } #end } #end function "@ $myScript | Out-ISETab #remove the cimsession $cimsess | Remove-CimSession } #end function
PowerShellCorpus/PowerShellGallery/ISEScriptingGeek/3.3.1.3/New-FileHere.ps1
New-FileHere.ps1
#requires -version 4.0 <# #> Function New-FileHere { <# .Synopsis Create a new file in the current path. .Description When you create a new file, the ISE wants to create it in the directory you were in when you started the ISE. I often want to create a new file in the current location. This command has no parameters. You will be prompted for a new file name if you don't specify one. .Parameter Name Enter the name of the new file. If you dont' specify one you will be prompted. #> [cmdletbinding()] Param( [string]$Name = (New-Inputbox -Prompt "Enter a file name" -Title "New File" -Default "MyUntitled.ps1"), [switch]$Open, [switch]$Passthru ) if ($name -match "\w+") { $newpath = Join-path -Path (Get-Location).Path -ChildPath $name if (Test-Path -Path $newpath) { Write-Warning "A file with the name $name already exists. Please try again." } else { write-verbose "Adding $newFile" $head = @" #Requires -version $($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor) <# $Name **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** #> "@ $head | Out-File -FilePath $newPath -NoClobber #give the file a chance to be created start-sleep -Seconds 1 #Open the file if ($Open) { psedit $newpath } if ($Passthru) { Get-Item $newpath } } } else { Write-host "Aborting" -ForegroundColor Yellow } } #end function
PowerShellCorpus/PowerShellGallery/PoShKeePass/2.0.4.0/Test/PSKeePassUsage.Tests.ps1
PSKeePassUsage.Tests.ps1
Get-Module PoShKeePass | Remove-Module Import-Module "$PSScriptRoot\..\PoShKeePass.psm1" -force -ErrorAction Stop InModuleScope "PoShKeePass" { Import-KPLibrary $WarningPreference = 'SilentlyContinue' Describe "New-KPConnection - UnitTest" -Tag UnitTest { Context "Example 1: Open with PSKeePass Credential Object - KeyFile" { It "Example 1.1: Get KeePass Database Connection with KeyFile - Valid" { $KeePassConnection = New-KPConnection -Database "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'KeyFile' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } Context "Example 2: Open with PSKeePass Credential Object - MasterKey" { It "Example 2.1: Get KeePass Database Connection with MasterKey - Valid" { $KeePassConnection = New-KPConnection -Database "$PSScriptRoot\Includes\AuthenticationDatabases\MasterKey.kdbx" -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'MasterKey' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } Context "Example 3: Open with PSKeePass Credential Object - MasterKey and KeyFile" { It "Example 3.1: Get KeePass Database Connection with KeyAndMaster - Valid" { $KeePassConnection = New-KPConnection -Database "$PSScriptRoot\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyAndMaster.key" -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'KeyAndMaster' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } It "Example 3.2: Get KeePass Database Connection with KeyAndMaster - Invalid Key File" { { New-KPConnection -Database "$PSScriptRoot\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) } | Should Throw } } ## Holding off on Network Account Testing until I can script the creation of a database. } Describe "Remove-KPConnection - UnitTest" -Tag UnitTest { Context "Example 1: Close an Open PSKeePass Database Connection" { It "Example 1.1: Closes a KeePass Database Connection" { $KeePassConnection = New-KPConnection -Database "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" $KeePassConnection.IsOpen | Should Be $true Remove-KPConnection -KeePassConnection $KeePassConnection | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } } Describe "New-KPConfigurationFile - UnitTest" -Tag UnitTest { Context "Example 1: Create a new KeePass Database Configuration XML File" { It "Example 1.1: Creates a New Config File - Valid" { if((Test-Path -Path "$($PSScriptRoot)\..\KeePassConfiguration.xml")){ Remove-Item -Path "$($PSScriptRoot)\..\KeePassConfiguration.xml" -Force } New-KPConfigurationFile | Should Be $null Test-Path -Path "$($PSScriptRoot)\..\KeePassConfiguration.xml" } It "Example 1.2: Creates a New Config File - Invalid" { { New-KPConfigurationFile } | Should Throw "A KeePass Configuration File already exists." } It "Example 1.3: Creates a New Config File with OverWrite - Valid" { New-KPConfigurationFile -Force | Should Be $null Test-Path -Path "$($PSScriptRoot)\..\KeePassConfiguration.xml" } } } Describe "New-KeePassDatabaseConfiguration - UnitTest" -Tag UnitTest { Context "Example 1: Create a new KeePass Database Configuration Profile - KeyFile" { New-KPConfigurationFile -Force It "Example 1.1: Database Configuration Profile - KeyFile - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" | Should Be $null } It "Example 1.2: Database Configuration Profile - KeyFile - Invalid Exists" { {New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" } | Should Throw } It "Example 1.3: Database Configuration Profile - KeyFile - Valid with PassThru" { $DatabaseConfiguration = New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileTestPassThru' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyFile.key" -PassThru $DatabaseConfiguration.Name | Should Be 'KeyFileTestPassThru' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyFile.kdbx" $DatabaseConfiguration.KeyPath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyFile.key" $DatabaseConfiguration.UseNetworkAccount | Should Be $false $DatabaseConfiguration.UseMasterKey | Should Be $false $DatabaseConfiguration.AuthenticationType | Should Be 'Key' } break } Context "Example 2: Create a new KeePass Database Configuration Profile - MasterKey" { New-KPConfigurationFile -Force It "Example 2.1: Database Configuration Profile - MasterKey - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'MasterKeyTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseMasterKey | Should Be $null } It "Example 2.2: Database Configuration Profile - MasterKey - Invalid Exists" { {New-KeePassDatabaseConfiguration -DatabaseProfileName 'MasterKeyTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseMasterKey } | Should Throw } It "Example 2.3: Database Configuration Profile - MasterKey - Valid with PassThru" { $DatabaseConfiguration = New-KeePassDatabaseConfiguration -DatabaseProfileName 'MasterKeyTestPassThru' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseMasterKey -PassThru $DatabaseConfiguration.Name | Should Be 'MasterKeyTestPassThru' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" $DatabaseConfiguration.KeyPath | Should Be '' $DatabaseConfiguration.UseNetworkAccount | Should Be 'False' $DatabaseConfiguration.UseMasterKey | Should Be 'True' $DatabaseConfiguration.AuthenticationType | Should Be 'Master' } } Context "Example 3: Create a new KeePass Database Configuration Profile - KeyFile And MasterKey" { New-KPConfigurationFile -Force It "Example 3.1: Database Configuration Profile - KeyFile And MasterKey - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileAndMasterKeyTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" -UseMasterKey | Should Be $null } It "Example 3.2: Database Configuration Profile - KeyFile And MasterKey - Invalid Exists" { {New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileAndMasterKeyTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" -UseMasterKey } | Should Throw } It "Example 3.3: Database Configuration Profile - KeyFile And MasterKey - Valid with PassThru" { $DatabaseConfiguration = New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileAndMasterKeyTestPassThru' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" -UseMasterKey -PassThru $DatabaseConfiguration.Name | Should Be 'KeyFileAndMasterKeyTestPassThru' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" $DatabaseConfiguration.KeyPath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" $DatabaseConfiguration.UseNetworkAccount | Should Be 'False' $DatabaseConfiguration.UseMasterKey | Should Be 'True' $DatabaseConfiguration.AuthenticationType | Should Be 'KeyAndMaster' } It "Example 3.4: Database Configuration Profile - KeyFile And MasterKey with NetworkAccount - Invalid Authentication Combo" { {New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileAndMasterKeyAndNetworkAuthenticationTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" -UseMasterKey -UserNetworkAccount} | Should Throw } } Context "Example 4: Create a new KeePass Database Configuration Profile - Network" { New-KPConfigurationFile -Force It "Example 4.1: Database Configuration Profile - Network - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'NetworkTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null } It "Example 4.2: Database Configuration Profile - Network - Invalid Exists" { {New-KeePassDatabaseConfiguration -DatabaseProfileName 'NetworkTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount } | Should Throw } It "Example 4.3: Database Configuration Profile - Network - Valid with PassThru" { $DatabaseConfiguration = New-KeePassDatabaseConfiguration -DatabaseProfileName 'NetworkTestPassThru' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount -PassThru $DatabaseConfiguration.Name | Should Be 'NetworkTestPassThru' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" $DatabaseConfiguration.KeyPath | Should Be '' $DatabaseConfiguration.UseNetworkAccount | Should Be 'True' $DatabaseConfiguration.UseMasterKey | Should Be 'False' $DatabaseConfiguration.AuthenticationType | Should Be 'Network' } } } Describe "Get-KeePassDatabaseConfiguration - UnitTest" -Tag UnitTest { New-KPConfigurationFile -Force Context "Example 1: Get a KeePass Database Configuration Profile" { It "Example 1.1: Get Database Configuration Profile - Valid - By Name" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null $DatabaseConfiguration = Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' $DatabaseConfiguration.Name | Should Be 'SampleProfile' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" $DatabaseConfiguration.KeyPath | Should Be '' $DatabaseConfiguration.UseNetworkAccount | Should Be 'True' $DatabaseConfiguration.UseMasterKey | Should Be 'False' $DatabaseConfiguration.AuthenticationType | Should Be 'Network' } It "Example 1.2: Get Database Configuration Profile - Valid - All" { $DatabaseConfiguration = Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' $DatabaseConfiguration.Name | Should Be 'SampleProfile' $DatabaseConfiguration.DatabasePath | Should Be "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" $DatabaseConfiguration.KeyPath | Should Be '' $DatabaseConfiguration.UseNetworkAccount | Should Be 'True' $DatabaseConfiguration.UseMasterKey | Should Be 'False' $DatabaseConfiguration.AuthenticationType | Should Be 'Network' } } New-KPConfigurationFile -Force } Describe "Remove-KeePassDatabaseConfiguration - UnitTest" -Tag UnitTest { New-KPConfigurationFile -Force Context "Example 1: Remove a KeePass Database Configuration Profile" { It "Example 1.1: Remove Database Configuration Profile - Valid - By Name" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null # Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' Remove-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -confirm:$false | Should Be $null Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' | Should Be $null } <# ## On Hold until can figure out pipe line for this # It "Example 1.2: Remove Database Configuration Profile - Valid - By Name - Via Pipeline" { # New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null # Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' | Remove-KeePassDatabaseConfiguration -confirm:$false | Should Be $null # Get-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' | Should Be $null # } ## On Hold until can figure out pipe line for this # It "Example 1.3: Remove Database Configuration Profile - Valid - Multiple - Via Pipeline" { # New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null # New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile1' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null # Get-KeePassDatabaseConfiguration | Remove-KeePassDatabaseConfiguration -confirm:$false | Should Be $null # Get-KeePassDatabaseConfiguration | Should Be $null # } #> It "Example 1.2: Remove Database Configuration Profile - Invalid - No Profiles Exist." { {Remove-KeePassDatabaseConfiguration -confirm:$false } | Should Throw "There are Currently No Database Configuration Profiles." Get-KeePassDatabaseConfiguration | Should Be $null } } New-KPConfigurationFile -Force } Describe "New-KPConnection - Profile - UnitTest" -Tag UnitTest { Context "Example 1: Open with PSKeePass Credential Object - KeyFile - Profile" { New-KPConfigurationFile -Force It "Example 1.1: Get KeePass Database Connection with KeyFile from a Profile- Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.kdbx" -KeyPath "$PSScriptRoot\Includes\AuthenticationDatabases\KeyFile.key" | Should Be $null $KeePassConnection = New-KPConnection -DatabaseProfileName 'KeyFileTest' $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'KeyFile' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } Context "Example 2: Open with PSKeePass Credential Object - MasterKey - Profile" { New-KPConfigurationFile -Force It "Example 2.1: Get KeePass Database Connection with MasterKey from a Profile - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'MasterKeyTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseMasterKey | Should Be $null $KeePassConnection = New-KPConnection -DatabaseProfileName 'MasterKeyTest' -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'MasterKey' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } Context "Example 3: Open with PSKeePass Credential Object - MasterKey and KeyFile - Profile" { New-KPConfigurationFile -Force It "Example 3.1: Get KeePass Database Connection with KeyAndMaster from a Profile - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'KeyFileAndMasterKeyTest' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.kdbx" -KeyPath "$($PSScriptRoot)\Includes\AuthenticationDatabases\KeyAndMaster.key" -UseMasterKey | Should Be $null $KeePassConnection = New-KPConnection -DatabaseProfileName 'KeyFileAndMasterKeyTest' -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) $KeePassConnection | Should BeOfType 'KeePassLib.PwDatabase' $KeePassConnection.IsOpen | Should Be $true $KeePassConnection.RootGroup.Name | Should Be 'KeyAndMaster' $KeePassConnection.Close() | Should Be $null $KeePassConnection.IsOpen | Should Be $false } } ## Holding off on Network Account Testing until I can script the creation of a database. } Describe "New-KeePassPassword - UnitTest" -Tag UnitTest { Context "Example 1: Generate a new KeePass Password - Options" { It "Example 1.1: New Password using all basic options - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 1.2: New Password using all basic options + ExcludeLookALike - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 -ExcludeLookALike | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 1.3: New Password using all basic options + NoRepeatingCharacters - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 -NoRepeatingCharacters | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 1.4: New Password using some basic options + NoRepeatingCharacters - Invalid" { { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Length 85 -NoRepeatingCharacters } | Should Throw 'Unabled to generate a password with the specified options.' } It "Example 1.5: New Password using all basic options + ExcludedCharactes - Valid" { $SecurePass = New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 70 -ExcludeCharacters '1,],-a' $SecurePass | Should BeOfType KeePassLib.Security.ProtectedString $SecurePass.ReadString() | Should Not Match ([regex]::Escape("^.*[1\]-a].*$")) } } Context "Example 2: Generate a new KeePass Password - Options - SaveAs" { New-KPConfigurationFile -Force It "Example 2.1: New Password using all basic options - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 -SaveAs 'Basic20' | Should BeOfType KeePassLib.Security.ProtectedString $PassProfile = Get-KPPasswordProfile -PasswordProfileName 'Basic20' $PassProfile.Name | Should Be 'Basic20' $PassProfile.CharacterSet | Should Be 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&''*+,./:;=?@\^`|~-_ []{}()<>' $PassProfile.ExcludeLookAlike | Should Be 'False' $PassProfile.NoRepeatingCharacters | Should Be 'False' $PassProfile.ExcludeCharacters | Should Be '' $PassProfile.Length | Should Be 20 } It "Example 2.2: New Password using all basic options + ExcludeLookALike - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 -ExcludeLookALike -SaveAs 'BasicNoLookAlike20' | Should BeOfType KeePassLib.Security.ProtectedString $PassProfile = Get-KPPasswordProfile -PasswordProfileName 'BasicNoLookAlike20' $PassProfile.Name | Should Be 'BasicNoLookAlike20' $PassProfile.CharacterSet | Should Be 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&''*+,./:;=?@\^`|~-_ []{}()<>' $PassProfile.ExcludeLookAlike | Should Be 'True' $PassProfile.NoRepeatingCharacters | Should Be 'False' $PassProfile.ExcludeCharacters | Should Be '' $PassProfile.Length | Should Be 20 } It "Example 2.3: New Password using all basic options + NoRepeatingCharacters - Valid" { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 20 -NoRepeatingCharacters -SaveAs 'BasicNoRepeat20' | Should BeOfType KeePassLib.Security.ProtectedString $PassProfile = Get-KPPasswordProfile -PasswordProfileName 'BasicNoRepeat20' $PassProfile.Name | Should Be 'BasicNoRepeat20' $PassProfile.CharacterSet | Should Be 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&''*+,./:;=?@\^`|~-_ []{}()<>' $PassProfile.ExcludeLookAlike | Should Be 'False' $PassProfile.NoRepeatingCharacters | Should Be 'True' $PassProfile.ExcludeCharacters | Should Be '' $PassProfile.Length | Should Be 20 } It "Example 2.4: New Password using some basic options + NoRepeatingCharacters - Invalid" { { New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Length 85 -NoRepeatingCharacters -SaveAs 'BasicNoRepeatInvalid' } | Should Throw 'Unabled to generate a password with the specified options.' Get-KPPasswordProfile -PasswordProfileName 'BasicNoRepeatInvalid' | Should Be $null } It "Example 2.5: New Password using all basic options + ExcludedCharactes - Valid" { $SecurePass = New-KeePassPassword -UpperCase -LowerCase -Digits -SpecialCharacters -Minus -UnderScore -Space -Brackets -Length 70 -ExcludeCharacters '1,],-a' -SaveAs 'BasicExcudle1]-a' $SecurePass | Should BeOfType KeePassLib.Security.ProtectedString $SecurePass.ReadString() | Should Not Match ([regex]::Escape("^.*[1\]-a].*$")) $PassProfile = Get-KPPasswordProfile -PasswordProfileName 'BasicExcudle1]-a' $PassProfile.Name | Should Be 'BasicExcudle1]-a' $PassProfile.CharacterSet | Should Be 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"#$%&''*+,./:;=?@\^`|~-_ []{}()<>' $PassProfile.ExcludeLookAlike | Should Be 'False' $PassProfile.NoRepeatingCharacters | Should Be 'False' $PassProfile.ExcludeCharacters | Should Be '1,],-a' $PassProfile.Length | Should Be 70 } } Context "Example 3: Generate a new KeePass Password - Profile" { It "Example 3.1: New Password using Profile Basic20 - Valid" { New-KeePassPassword -PasswordProfileName 'Basic20' | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 3.2: New Password using Profile BasicNoLookAlike20 - Valid" { New-KeePassPassword -PasswordProfileName 'BasicNoLookAlike20' | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 3.3: New Password using Profile BasicNoRepeat20 - Valid" { New-KeePassPassword -PasswordProfileName 'BasicNoRepeat20' | Should BeOfType KeePassLib.Security.ProtectedString } It "Example 3.4: New Password using Profile BasicNoRepeatInvalid - Invalid - Does Not Exist" { { New-KeePassPassword -PasswordProfileName 'BasicNoRepeatInvalid' } | Should Throw } It "Example 3.5: New Password using Profile BasicExcudle1]-a - Valid" { $SecurePass = New-KeePassPassword -PasswordProfileName 'BasicExcudle1]-a' $SecurePass | Should BeOfType KeePassLib.Security.ProtectedString $SecurePass.ReadString() | Should Not Match ([regex]::Escape("^.*[1\]-a].*$")) } } } Describe "New-KeePassEntry - UnitTest" -Tag UnitTest { Context "Example 1: Creates a New KeePass Entry." { New-KPConfigurationFile -Force It "Example 1.1: Creates a New KeePass Entry - Invalid - No Profile" { # New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseNetworkAccount | Should Be $null { New-KeePassEntry -KeePassEntryGroupPath 'database' -Title 'test' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' }| Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Creates a New KeePass Entry - Valid" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null } It "Example 1.3: Creates a New KeePass Entry - Valid - PassThru" { $PassThruResult = New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'testPassThru' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' -PassThru $PassThruResult | Should BeOfType KeePassLib.PwEntry $PassThruResult.ParentGroup.Name | Should BeLike 'PSKeePassTestDatabase' $PassThruResult.Strings.ReadSafe('Title') | Should Be 'testPassThru' $PassThruResult.Strings.ReadSafe('UserName') | Should Be 'testuser' $PassThruResult.Strings.ReadSafe('Notes') | Should Be 'testnotes' $PassThruResult.Strings.ReadSafe('URL') | Should be 'http://url.test.com' } It "Example 1.4: Creates a New KeePass Entry - Invalid - Group Path does not Exist" { { New-KeePassEntry -KeePassEntryGroupPath 'BadPath' -Title 'test' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' } | Should Throw } It "Example 1.5: Creates a New KeePass Entry with manaully specified Password - Valid" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'testPass' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -KeePassPassword $(ConvertTo-SecureString -String 'teststring' -AsPlainText -Force) -DatabaseProfileName 'SampleProfile' | Should Be $null } It "Example 1.6: Creates a New KeePass Entry with a generated Password - Valid" { $GeneratedPassword = New-KeePassPassword -Upper -Lower -Digits -Length 50 New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'testPass' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -KeePassPassword $GeneratedPassword -DatabaseProfileName 'SampleProfile' | Should Be $null } It "Example 1.7: Creates a New KeePass Entry - Valid - PassThru - Icon" { $PassThruResult = New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'testPassThruIcon' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' -IconName Apple -PassThru $PassThruResult | Should BeOfType KeePassLib.PwEntry $PassThruResult.ParentGroup.Name | Should BeLike 'PSKeePassTestDatabase' $PassThruResult.Strings.ReadSafe('Title') | Should Be 'testPassThruIcon' $PassThruResult.Strings.ReadSafe('UserName') | Should Be 'testuser' $PassThruResult.Strings.ReadSafe('Notes') | Should Be 'testnotes' $PassThruResult.Strings.ReadSafe('URL') | Should Be 'http://url.test.com' $PassThruResult.IconId | Should Be 'Apple' } } New-KPConfigurationFile -Force } Describe "Get-KeePassEntry - UnitTest" -Tag UnitTest { Context "Example 1: Gets KeePass Entries." { New-KPConfigurationFile -Force It "Example 1.1: Gets All KeePass Entries - Invalid - No Database Configuration Profiles." { { Get-KeePassEntry -AsPlainText -KeePassEntryGroupPath 'PSKeePassTestDatabase/BadPath' } | Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2 Gets All KeePass Entries - Valid" { $ResultEntries = Get-KeePassEntry -DatabaseProfileName SampleProfile $ResultEntries.Count | Should Be 2 } It "Example 1.2 Gets All KeePass Entries - MasterKey Profile - Valid" { New-KeePassDatabaseConfiguration -DatabaseProfileName 'MasterKeyTest' -DatabasePath "$PSScriptRoot\Includes\AuthenticationDatabases\MasterKey.kdbx" -UseMasterKey | Should Be $null $ResultEntries = Get-KeePassEntry -DatabaseProfileName 'MasterKeyTest' -MasterKey $(ConvertTo-SecureString -String "ATestPassWord" -AsPlainText -Force) $ResultEntries.Count | Should Be 2 } It "Example 1.3 Gets All KeePass Entries - Valid As Plain Text" { $ResultEntries = Get-KeePassEntry -DatabaseProfileName SampleProfile -AsPlainText $ResultEntries.Count | Should Be 2 $ResultEntries[0].Title | Should Be 'Sample Entry' $ResultEntries[1].Title | Should Be 'Sample Entry #2' } It "Example 1.4: Gets All KeePass Entries Of Specific Group - Valid" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase/General' -Title 'SubGroupTest' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $ResultEntries = Get-KeePassEntry -DatabaseProfileName SampleProfile -AsPlainText -KeePassEntryGroupPath 'PSKeePassTestDatabase/General' $ResultEntries.Title | Should Be 'SubGroupTest' } It "Example 1.5: Gets All KeePass Entries Of Specific Group - Invalid - Bad Path" { { Get-KeePassEntry -DatabaseProfileName SampleProfile -AsPlainText -KeePassEntryGroupPath 'PSKeePassTestDatabase/BadPath' } | Should Throw } } New-KPConfigurationFile -Force } Describe "Update-KeePassEntry - UnitTest" -Tag UnitTest { Context "Example 1: Updates a KeePass Entry." { New-KPConfigurationFile -Force It "Example 1.1: Creates a New KeePass Entry - Invalid - No Profile" { { Update-KeePassEntry -KeePassEntry $( New-Object KeePassLib.PwEntry($true, $true)) -KeePassEntryGroupPath 'database' -Title 'test' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' }| Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Updates a KeePass Entry - Valid - Properties" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test1' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test1' } Update-KeePassEntry -KeePassEntry $KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -title 'UpdateTest1' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -DatabaseProfileName 'SampleProfile' -Force | Should Be $null } It "Example 1.3: Updates a KeePass Entry - Valid - Properties - Via Pipeline" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test2' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test2'} | Update-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -title 'UpdateTest2' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -DatabaseProfileName 'SampleProfile' -Force | Should Be $null } It "Example 1.4: Update a KeePass Entry - Valid - Properties - PassThru" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test3' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test3' } $UpdatePassThruResult = Update-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -KeePassEntry $KeePassEntry -title 'UpdateTest3' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -DatabaseProfileName 'SampleProfile' -PassThru -Force $UpdatePassThruResult | Should BeOfType KeePassLib.PwEntry $UpdatePassThruResult.Strings.ReadSafe('Title') | Should Be 'UpdateTest3' $UpdatePassThruResult.Strings.ReadSafe('UserName') | Should Be 'UpdateTestUser' $UpdatePassThruResult.Strings.ReadSafe('Notes') | Should Be 'UpdateTestNotes' $UpdatePassThruResult.Strings.ReadSafe('URL') | Should Be 'http://UpdateURL.Test.com' } It "Example 1.5: Update a KeePass Entry - Valid - Group & Properties - PassThru" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test4' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test4' } $UpdatePassThruResult = Update-KeePassEntry -KeePassEntry $KeePassEntry -title 'UpdateTest4' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -KeePassEntryGroupPath 'PSKeePassTestDatabase/General' -DatabaseProfileName 'SampleProfile' -PassThru -Force $UpdatePassThruResult | Should BeOfType KeePassLib.PwEntry $UpdatePassThruResult.ParentGroup.Name | Should Be 'General' $UpdatePassThruResult.Strings.ReadSafe('Title') | Should Be 'UpdateTest4' $UpdatePassThruResult.Strings.ReadSafe('UserName') | Should Be 'UpdateTestUser' $UpdatePassThruResult.Strings.ReadSafe('Notes') | Should Be 'UpdateTestNotes' $UpdatePassThruResult.Strings.ReadSafe('URL') | Should Be 'http://UpdateURL.Test.com' } It "Example 1.6: Update a KeePass Entry - Invalid - Group & Properties - PassThru - BadPath" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test5' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test5' } { Update-KeePassEntry -KeePassEntry $KeePassEntry -title 'UpdateTest5' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -KeePassEntryGroupPath 'PSKeePassTestDatabase/BadPath' -DatabaseProfileName 'SampleProfile' -PassThru -Force } | Should Throw } It "Example 1.7: Update a KeePass Entry - Valid - Properties - PassThru - Icon" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test6' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test6' } $UpdatePassThruResult = Update-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -KeePassEntry $KeePassEntry -title 'UpdateTest6' -UserName 'UpdateTestUser' -Notes 'UpdateTestNotes' -URL 'http://UpdateURL.Test.com' -DatabaseProfileName 'SampleProfile' -IconName Apple -PassThru -Force $UpdatePassThruResult | Should BeOfType KeePassLib.PwEntry $UpdatePassThruResult.Strings.ReadSafe('Title') | Should Be 'UpdateTest6' $UpdatePassThruResult.Strings.ReadSafe('UserName') | Should Be 'UpdateTestUser' $UpdatePassThruResult.Strings.ReadSafe('Notes') | Should Be 'UpdateTestNotes' $UpdatePassThruResult.Strings.ReadSafe('URL') | Should Be 'http://UpdateURL.Test.com' $UpdatePassThruResult.IconId | Should Be 'Apple' } } New-KPConfigurationFile -Force } Describe "Remove-KeePassEntry - UnitTest" -Tag UnitTest { New-KPConfigurationFile -Force Context "Example 1: Remove a KeePass Entry" { It "Example 1.1: Removes a KeePass Entry - Invalid - No Profile" { { Remove-KeePassEntry -KeePassEntry $( New-Object KeePassLib.PwEntry($true, $true)) }| Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Removes a KeePass Entry - Valid " { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test1' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test1' } Remove-KeePassEntry -KeePassEntry $KeePassEntry -DatabaseProfileName 'SampleProfile' -Force | Should Be $null } It "Example 1.3: Removes a KeePass Entry - Valid - NoRecycle " { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test2' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test2' } Remove-KeePassEntry -KeePassEntry $KeePassEntry -DatabaseProfileName 'SampleProfile' -NoRecycle -Force | Should Be $null } It "Example 1.4: Removes a KeePass Entry - Valid - Pipeline " { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test3' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -AsPlainText -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Title -eq 'test3' } $KeePassEntry | Remove-KeePassEntry -DatabaseProfileName 'SampleProfile' -Force | Should Be $null } It "Example 1.5: Removes a KeePass Entry - Valid - Pipeline - PWEntry" { New-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -Title 'test4' -UserName 'testuser' -Notes 'testnotes' -URL 'http://url.test.com' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassEntry = Get-KeePassEntry -KeePassEntryGroupPath 'PSKeePassTestDatabase' -DatabaseProfileName 'SampleProfile' | Where-Object { $_.Strings.ReadSafe('Title') -eq 'test4' } $KeePassEntry | Remove-KeePassEntry -DatabaseProfileName 'SampleProfile' -Force | Should Be $null } } New-KPConfigurationFile -Force } Describe "New-KeePassGroup - UnitTest" -Tag UnitTest { Context "Example 1: Creates a New KeePass Group." { New-KPConfigurationFile -Force It "Example 1.1: Creates a New KeePass Group - Invalid - No Profile" { { New-KeePassGroup -KeePassGroupParentPath 'database' -KeePassGroupName 'test' } | Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Creates a New KeePass Group - Valid" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test1' -DatabaseProfileName 'SampleProfile' | Should Be $null } It "Example 1.3: Creates a New KeePass Group - Valid - PassThru" { $PassThruResult = New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test2PassThru' -DatabaseProfileName 'SampleProfile' -PassThru $PassThruResult | Should BeOfType KeePassLib.PwGroup $PassThruResult.ParentGroup.Name | Should Be 'PSKeePassTestDatabase' $PassThruResult.Name | Should Be 'test2PassThru' } It "Example 1.4: Creates a New KeePass Entry - Invalid - Group Path does not Exist" { { New-KeePassGroup -KeePassGroupParentPath 'BadPath' -KeePassGroupName 'test3' -DatabaseProfileName 'SampleProfile' } | Should Throw } It "Example 1.5: Creates a New KeePass Group - Valid - PassThru - Icon" { $PassThruResult = New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test4PassThru' -DatabaseProfileName 'SampleProfile' -IconName 'Clock' -PassThru $PassThruResult | Should BeOfType KeePassLib.PwGroup $PassThruResult.ParentGroup.Name | Should Be 'PSKeePassTestDatabase' $PassThruResult.Name | Should Be 'test4PassThru' $PassThruResult.IconId | Should Be 'Clock' } } New-KPConfigurationFile -Force } Describe "Get-KeePassGroup - UnitTest" -Tag UnitTest { Context "Example 1: Gets KeePass Groups." { New-KPConfigurationFile -Force It "Example 1.1: Gets All KeePass Groups - Invalid - No Database Configuration Profiles." { { Get-KeePassGroup -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/BadPath' } | Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2 Gets All KeePass Groups - Valid" { $ResultGroups = Get-KeePassGroup -DatabaseProfileName SampleProfile $ResultGroups.Count | Should Be 7 } It "Example 1.3 Gets All KeePass Groups - Valid As Plain Text" { $ResultGroups = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText $ResultGroups.Count | Should Be 7 } It "Example 1.4: Gets a KeePass Group - Valid" { $ResultGroups = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/General' $ResultGroups.Name | Should Be 'General' $ResultGroups.ParentGroup | Should Be 'PSKeePassTestDatabase' } It "Example 1.5: Gets a KeePass Group - Invalid - Bad Path" { { Get-KeePassEntry -DatabaseProfileName SampleProfile -AsPlainText -KeePassEntryGroupPath 'PSKeePassTestDatabase/BadPath' } | Should Throw } } New-KPConfigurationFile -Force } Describe "Update-KeePassGroup - UnitTest" -Tag UnitTest { Context "Example 1: Updates a KeePass Group." { New-KPConfigurationFile -Force It "Example 1.1: Updates a KeePass Group - Invalid - No Profile" { { Update-KeePassGroup -KeePassGroup $( New-Object KeePassLib.PwGroup($true, $true)) -Force }| Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Updates a KeePass Group - Valid - Name" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test1' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test1' $KeePassGroup.Name | Should Be 'test1' Update-KeePassGroup -KeePassGroup $KeePassGroup -GroupName 'Test1Update' -DatabaseProfileName 'SampleProfile' -Force | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/Test1Update' $KeePassGroup.Name | Should Be 'Test1Update' } It "Example 1.3: Updates a KeePass Group - Valid - Name" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test2' -DatabaseProfileName 'SampleProfile' | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test2' | Update-KeePassGroup -GroupName 'Test2Update' -DatabaseProfileName 'SampleProfile' -Force | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/Test2Update' $KeePassGroup.Name | Should Be 'Test2Update' } It "Example 1.4: Updates a KeePass Group - Valid - Name" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test3' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test3' $KeePassGroup.Name | Should Be 'test3' $KeePassGroup = Update-KeePassGroup -KeePassGroup $KeePassGroup -GroupName 'Test3Update' -DatabaseProfileName 'SampleProfile' -Force -PassThru $KeePassGroup.Name | Should Be 'Test3Update' $KeePassGroup.ParentGroup.Name | Should be 'PSKeePassTestDatabase' } It "Example 1.5: Updates a KeePass Group - Valid - ParentGroup - Pipeline" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test4' -DatabaseProfileName 'SampleProfile' | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test4' | Update-KeePassGroup -DatabaseProfileName 'SampleProfile' -KeePassParentGroupPath 'PSKeePassTestDatabase/General' -Force | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/General/test4' $KeePassGroup.Name | Should Be 'test4' $KeePassGroup.ParentGroup | Should be 'General' } It "Example 1.6: Updates a KeePass Group - Invalid - ParentGroup - BadPath" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test5' -DatabaseProfileName 'SampleProfile' | Should Be $null { Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test5' | Update-KeePassGroup -DatabaseProfileName 'SampleProfile' -KeePassParentGroupPath 'PSKeePassTestDatabase/BadPath' -Force}| Should Throw } It "Example 1.7: Updates a KeePass Group - Valid - Name - PassThru - Icon" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test6' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test6' $KeePassGroup.Name | Should Be 'test6' $KeePassGroup.IconId | Should Be 'Folder' $KeePassGroup = Update-KeePassGroup -KeePassGroup $KeePassGroup -GroupName 'Test6Update' -DatabaseProfileName 'SampleProfile' -IconName 'Clock' -Force -PassThru $KeePassGroup.Name | Should Be 'Test6Update' $KeePassGroup.IconId | Should Be 'Clock' $KeePassGroup.ParentGroup.Name | Should be 'PSKeePassTestDatabase' } } New-KPConfigurationFile -Force } Describe "Remove-KeePassGroup - UnitTest" -Tag UnitTest { New-KPConfigurationFile -Force Context "Example 1: Remove a KeePass Group" { It "Example 1.1: Removes a KeePass Group - Invalid - No Profile" { { Remove-KeePassGroup -KeePassGroup $( New-Object KeePassLib.PwGroup($true, $true)) }| Should Throw 'There are Currently No Database Configuration Profiles.' } ## Create Profile New-KeePassDatabaseConfiguration -DatabaseProfileName 'SampleProfile' -DatabasePath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -KeyPath "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.key" ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" It "Example 1.2: Removes a KeePass Group - Valid " { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test1' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test1' $KeePassGroup.Name | Should Be 'test1' Remove-KeePassGroup -KeePassGroup $KeePassGroup -DatabaseProfileName 'SampleProfile' -Force | Should Be $null $Check = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/RecycleBin/test1' $Check.Name | Should Be 'test1' } It "Example 1.3: Removes a KeePass Group - Valid - NoRecycle " { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test2' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test2' $KeePassGroup.Name | Should Be 'test2' Remove-KeePassGroup -KeePassGroup $KeePassGroup -DatabaseProfileName 'SampleProfile' -NoRecycle -Force | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test2' | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/RecycleBin/test2' | Should Be $null } It "Example 1.4: Removes a KeePass Group - Valid - Pipeline - AsPlainText" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test3' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/test3' $KeePassGroup.Name | Should Be 'test3' $KeePassGroup | Remove-KeePassGroup -DatabaseProfileName 'SampleProfile' -Force | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/RecycleBin/test3' | Should Not Be $null } It "Example 1.4: Removes a KeePass Group - Valid - Pipeline - PwGroup" { New-KeePassGroup -KeePassGroupParentPath 'PSKeePassTestDatabase' -KeePassGroupName 'test4' -DatabaseProfileName 'SampleProfile' | Should Be $null $KeePassGroup = Get-KeePassGroup -DatabaseProfileName SampleProfile -KeePassGroupPath 'PSKeePassTestDatabase/test4' $KeePassGroup.Name | Should Be 'test4' $KeePassGroup | Remove-KeePassGroup -DatabaseProfileName 'SampleProfile' -Force | Should Be $null Get-KeePassGroup -DatabaseProfileName SampleProfile -AsPlainText -KeePassGroupPath 'PSKeePassTestDatabase/RecycleBin/test4' | Should Not Be $null } } New-KPConfigurationFile -Force } ## Reset Test DB Remove-Item -Path "$($PSScriptRoot)\Includes\PSKeePassTestDatabase.kdbx" -Force Copy-Item -Path "$($PSScriptRoot)\Includes\Backup\PSKeePassTestDatabase.kdbx" -Destination "$($PSScriptRoot)\Includes\" } Invoke-Expression -Command "$($PSScriptRoot)\..\bin\AutoVersion.ps1"
PowerShellCorpus/PowerShellGallery/PoShKeePass/2.0.4.0/bin/EncodeKeePassLib.ps1
EncodeKeePassLib.ps1
# $Content = Get-Content -Path "$PSScriptRoot\KeePassLib.dll" -Encoding Byte # $Base64 = [Convert]::ToBase64String($Content) # $Base64 | Out-File -FilePath "$PSScriptRoot\KeePassLib_Encoded.txt" function Out-CompressedDll { [CmdletBinding()] Param ( [Parameter(Mandatory = $True)] [String] $FilePath ) $Path = Resolve-Path $FilePath if (! [IO.File]::Exists($Path)) { Throw "$Path does not exist." } $FileBytes = [System.IO.File]::ReadAllBytes($Path) if (($FileBytes[0..1] | % {[Char]$_}) -join '' -cne 'MZ') { Throw "$Path is not a valid executable." } $Length = $FileBytes.Length $CompressedStream = New-Object IO.MemoryStream $DeflateStream = New-Object IO.Compression.DeflateStream ($CompressedStream, [IO.Compression.CompressionMode]::Compress) $DeflateStream.Write($FileBytes, 0, $FileBytes.Length) $DeflateStream.Dispose() $CompressedFileBytes = $CompressedStream.ToArray() $CompressedStream.Dispose() $EncodedCompressedFile = [Convert]::ToBase64String($CompressedFileBytes) Write-Verbose "Compression ratio: $(($EncodedCompressedFile.Length/$FileBytes.Length).ToString('#%'))" $Output = @" `$EncodedCompressedFile = @' $EncodedCompressedFile '@ `$DeflatedStream = New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String(`$EncodedCompressedFile),[IO.Compression.CompressionMode]::Decompress) `$UncompressedFileBytes = New-Object Byte[]($Length) `$DeflatedStream.Read(`$UncompressedFileBytes, 0, $Length) | Out-Null [Reflection.Assembly]::Load(`$UncompressedFileBytes) "@ Write-Output $Output } Out-CompressedDll -FilePath "$PSScriptRoot\KeePassLib.dll"
PowerShellCorpus/PowerShellGallery/PoShKeePass/2.0.4.0/bin/AutoVersion.ps1
AutoVersion.ps1
## Get psd1 file $RawPSD = Get-Content -Path "$($PSScriptRoot)\..\PoShKeePass.psd1" $ModuleVersion=($RawPSD | ? { $_ -match "^ModuleVersion.*$" }) -replace "^.*=\s|'" [Int[]] $VerArr = $ModuleVersion -split '\.' $NewModuleVersion = '' $CarryValue = 1 $EntryPoint = $($VerArr.Count -1) for($i=$EntryPoint; $i -ge 0; $i--){ $VersionPart = $VerArr[$i] $VersionPart += $CarryValue if($i -eq 0) { $NewModuleVersion = "$VersionPart"+$NewModuleVersion break } else { if($VersionPart -eq 10) { $VersionPart = 0 } else { $CarryValue = 0 } $NewModuleVersion = ".$VersionPart"+$NewModuleVersion } } Write-Verbose -Message "New Version: $NewModuleVersion" $RawPSD | % { $_ -replace "(?<=^ModuleVersion = ')\d+\.\d\.\d\.\d(?=')",$NewModuleVersion } | Out-File -FilePath "$($PSScriptRoot)\..\PoShKeePass.psd1" -Force
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/Core.ps1
Core.ps1
#!/usr/bin/env powershell ## # Core.ps1: Cmdlets common across PoShTeX. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## FUNCTIONS ## function set-extension { param( [Parameter(Mandatory=$true)] [string] $path, [Parameter(Mandatory=$true)] [string] $newExtension ); return [System.IO.Path]::ChangeExtension($path, $newExtension); } function get-extension { param( [Parameter(Mandatory=$true)] [string] $path ) return [System.IO.Path]::GetExtension($path); } function get-fromhashtable { param( [hashtable] $InputObject, [string[]] $Keys ) [string] $found = $null; foreach ($key in $Keys) { if ($InputObject.Contains($key)) { $found = $InputObject[$key]; break } } return $found } function Test-IsPOSIX { if (!(Get-Command uname -ErrorAction SilentlyContinue)) { return $false; } $uname = uname; if ($uname.Trim() -eq "Linux" -or $uname.Trim() -eq "Darwin") { return $true; } return $false; } function Test-CommandExists { param([string] $Name); if (Get-Command -Name $Name -ErrorAction SilentlyContinue) { return $true; } else { return $false; } } function Compress-ArchiveWithSubfolders { [CmdletBinding( DefaultParameterSetName="PSObject" )] param( [Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName="PSObject")] [Alias("Source", "Src")] [string[]] $SourcePath, [Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName="PSObject")] [Alias("Destination", "Dest")] [string[]] $DestinationPath, [Parameter(ValueFromPipeline=$true, ParameterSetName="Hashtable")] [hashtable[]] $Paths, [Parameter(Mandatory=$true)] [string] $ArchivePath ) begin { # Make a temporary directory. $tempDirName = [System.IO.Path]::GetTempFileName(); Remove-Item $tempDirName; New-Item -ItemType Directory -Path $tempDirName | Out-Null; } process { # If we're using hashtables, unpack. switch ($PSCmdlet.ParameterSetName) { "Hashtable" { $Src = (get-fromhashtable -InputObject $Paths[0] -Keys SourcePath, Source, Src) $Dest = (get-fromhashtable -InputObject $Paths[0] -Keys DestinationPath, Destination, Dest) } "PSObject" { $Src = $SourcePath[0]; $Dest = $DestinationPath[0]; } } # Copy items from the pipeline into the temporary directory. # Make sure each target directory exists as we go. $targetPath = Join-Path $tempDirName $Dest; $targetDir = Split-Path $targetPath; # Make the target directory if it doesn't exist. if (!(Get-Item $targetDir -ErrorAction SilentlyContinue)) { New-Item -ItemType Directory $targetDir | Out-Null; } Write-Host "Copying $Src -> $targetPath" Copy-Item $Src $targetPath } end { # Actually make the archive. # We make the final ZIP file using the native zip command # on POSIX in lieu of # https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/26. if (Test-IsPOSIX) { if (Get-ChildItem $ArchivePath -ErrorAction SilentlyContinue) { Remove-Item $ArchivePath } pushd . cd $tempDirName zip -r $ArchivePath . popd mv (Join-Path $tempDirName $ArchivePath) . } else { Compress-Archive -Force -Path (Join-Path $tempDirName "*") -DestinationPath $ArchivePath } # Delete the temporary directory. Remove-Item -Force -Recurse $tempDirName; } } ## COMMANDS ## function Install-Resources { [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='Medium' )] param( [string] $PathAtDestination, [string[]] $ResourcePath, [string] $DestinationRoot, [string] $Prompt = "Install resources?" ) $dest = Join-Path -Path $DestinationRoot -ChildPath $PathAtDestination; if ($PSCmdlet.ShouldProcess($dest, $Prompt)) { # First make sure the destination path exists. New-Item -ItemType Directory -Path $dest -ErrorAction Ignore; # Next, copy the files into the target directory. foreach ($resource in $ResourcePath) { Copy-Item -Path $resource -Destination $dest; } } elseif ($WhatIfPreference.IsPresent) { Write-Host ("Would create directory at {0}." -f $dest); foreach ($resource in $ResourcePath) { Write-Host ("Would install {0} to {1}." -f $resource, $dest); } } }
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/Pandoc.ps1
Pandoc.ps1
#!/usr/bin/env powershell ## # Pandoc.ps1: Cmdlets for interacting with Pandoc installations. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## COMMANDS ## function Get-PandocUserDir { [CmdletBinding()] param( ); if (!(Get-Command pandoc -ErrorAction SilentlyContinue)) { return $null; } $pandocVersionReport = pandoc -v; foreach ($reportLine in $pandocVersionReport.Split([environment]::NewLine)) { if ($reportLine.Contains("Default user data directory:")) { # The [int] here is a workaround for a bug in PowerShell 6.0.0-alpha. $description, $value = $reportLine.Split(":", [int]2); return $value.Trim(); } } } function Install-PandocUserResource { [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='Medium' )] param( [string] $PandocPath = "", [string[]] $ResourcePath, [string] $PandocUserDir = $null ); if (!($PandocUserDir)) { $PandocUserDir = Get-PandocUserDir; } ( Install-Resources ` -PathAtDestination $PandocPath ` -ResourcePath $ResourcePath ` -DestinationRoot $PandocUserDir ` -Prompt "Install Pandoc user resource?" ` ) }
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/CTAN.ps1
CTAN.ps1
#!/usr/bin/env powershell ## # CTAN.ps1: Cmdlets for building CTAN-ready ZIP archives. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## ENUMS ## try { Add-Type -TypeDefinition @" public enum CTANArchiveLayout { Simple, TDS } "@ } catch {} ## COMMANDS ## function Format-CTANManifestItem { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] $Path, [string[]] $Targets = @("CTAN","TDS"), [string] $TDSPath = $null ) [pscustomobject]@{Path=$Path; TDSPath=$TDSPath; Targets=$Targets} | Write-Output; } function Search-TeXCommandTargets { [CmdletBinding()] param( [string] $CmdName, [Parameter(ValueFromPipeline)] [string] $Contents ) begin { $pattern = "\\$CmdName\{([^\\\}]+)\}"; } process { $Contents | Select-String -AllMatches -Pattern $pattern | % { foreach ($match in $_.Matches) { $match.groups[1] } } } } function Search-INSFile { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string[]] $FileName ) process { foreach ($name in $FileName) { # Write out the INS file itself. Format-CTANManifestItem -Path $name -Targets CTAN, TDS $contents = Get-Content $name; # We follow a strategy similar to that of ctanify # and search *.ins files for any \file commands, adding # them to our TDS manifest, similarly adding the # targets of \from commands to both the "outer" and TDS # archives. # Find \from targets. $contents | Search-TeXCommandTargets -CmdName file | % { Format-CTANManifestItem -Path $_ -Targets TDS } $contents | Search-TeXCommandTargets -CmdName from | % { Format-CTANManifestItem -Path $_ -Targets CTAN, TDS } } } } function Format-TDSPath { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] $PackageName, [Parameter(ValueFromPipeline=$true)] [PSCustomObject[]] $TDSManifest ) begin { $doc = "doc/latex/$PackageName"; $src = "source/latex/$PackageName"; $bin = "scripts/$PackageName"; $tex = "tex/latex/$PackageName"; $tdsRootsByExtension = @{ # LaTeX Packages # ".sty" = $tex; # DocStrip Package Sources # ".ins" = $src; ".dtx" = $src; # Compiled and Plain-Text Documentation # ".pdf" = $doc; ".md" = $doc; # Scripts and Executables # ".ps1" = $bin; ".py" = $bin; ".sh" = $bin; ".pl" = $bin; }; } process { foreach ($tdsItem in $TDSManifest) { if (!$tdsItem.TDSPath -and $tdsItem.Targets.Contains("TDS")) { $ext = [IO.Path]::GetExtension($tdsItem.Path); if ($tdsRootsByExtension.ContainsKey($ext)) { $tdsItem.TDSPath = $tdsRootsByExtension[$ext]; } } $tdsItem | Write-Output; } } } function Format-CTANManifest { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0)] [string] $PackageName, [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)] [string[]] $Path ) process { $Path | % { switch -Wildcard ($_) { "*[/\]Install.ps1" { # We want installers to be provided only in the CTAN zip, # not in the TDS folder structure. Format-CTANManifestItem -Path $_ -Targets CTAN | Write-Output; } "*.ins" { Search-INSFile $_ | Write-Output; } default { Format-CTANManifestItem -Path $_ -Targets CTAN, TDS | Write-Output; } } } | Format-TDSPath -PackageName $PackageName | Write-Output } } ## # .SYNOPSIS ## function Export-CTANArchive { # [CmdletBinding()] param( [string] $PackageName, [Parameter(Mandatory=$true)] [CTANArchiveLayout] $ArchiveLayout, [Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)] [string[]] $Path ); begin { # Check if $PackageName is defined, and if not, # default to the base name of the first path argument. if (!$PackageName) { $PackageName = [IO.Path]::GetFileNameWithoutExtension($Path[0]); } } process { # Actually build the manifest. $Manifest = $Path | Format-CTANManifest -PackageName $PackageName; } end { # If the $ArchiveLayout parameter tells us we need to include # a *.tds.zip, then we write that now. if ($ArchiveLayout -eq [CTANArchiveLayout]::TDS) { $tdsZipName = "$PackageName.tds.zip"; # Pack up the TDS ZIP. $Manifest | ? {$_.Targets.Contains("TDS")} | % { @{Src=$_.Path; Dest=Join-Path $_.TDSPath ([IO.Path]::GetFileName($_.Path))} } | Compress-ArchiveWithSubfolders -ArchivePath $tdsZipName; $Manifest = $Manifest + @((Format-CTANManifestItem -Path $tdsZipName -Targets CTAN)); } $ctanZipName = "$PackageName.zip"; # Finally, write the CTAN zip itself. $Manifest | ? {$_.Targets.Contains("CTAN")} | % { @{Src=$_.Path; Dest=Join-Path $PackageName ([IO.Path]::GetFileName($_.Path))} } | Compress-ArchiveWithSubfolders -ArchivePath $ctanZipName; } }
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/ArXiv.ps1
ArXiv.ps1
#!/usr/bin/env powershell ## # ArXiv.ps1: Cmdlets for building arXix-ready ZIP archives. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## COMMANDS ## function Expand-ArXivManifest { # [CmdletBinding()] param( [Parameter(Mandatory=$true)] [hashtable] $Manifest ); # Begin by making a new hashtable to accumulate build files. # Each entry in the hashtable will identify a particular file # and its destination within the eventual ZIP file. $buildFiles = @{}; # Put the TeXMain file in the root by isolating its basename # (that is, without the path) and making that the destination # for the actual file pointed to by TeXMain. $texMain = $Manifest["TeXMain"]; $texMainLocation = Split-Path $texMain; if ($texMainLocation.Length -eq 0) { $texMainLocation = "."; } $texMainBase = Split-Path $texMain -Leaf; $texMainDest = Join-Path "." $texMainBase; $buildFiles[($texMain | Resolve-Path)] = $texMainDest; # Next, add the BBL. $bblBase = set-extension -Path $texMainBase -newExtension "bbl"; $buildFiles[( Join-Path -Path $texMainLocation -ChildPath $bblBase | Resolve-Path )] = Join-Path "." $bblBase; # Next, loop through the AdditionalFiles and add each to # the build files accordingly. $Manifest["AdditionalFiles"].GetEnumerator() | % { $glob = $_.Key; $targetDir = $_.Value; if (!($targetDir)) { # Check if the target is left implicit. If so, resolve # the glob and add each. Resolve-Path $glob -Relative | % { $buildFiles[(Resolve-Path $_)] = $_; } | Out-Null } elseif ($targetDir.EndsWith("/") -or $targetDir.EndsWith("\")) { # Next, check if the target is a directory. If so, each # item matching the glob gets added to the same directory. Resolve-Path $glob -Relative | % { $buildFiles[(Resolve-Path $_)] = (Join-Path $targetDir -ChildPath (Split-Path $_ -Leaf)); } | Out-Null } else { # If we're here, then the target was an explicit name, so we # don't need to glob it up. $buildFiles[$glob] = $targetDir; } } | Out-Null # Add any Notebooks to anc/. We'll possibly rerun them in a later build # stage. $Manifest["Notebooks"] | % { $buildFiles[(Resolve-Path $_)] = Join-Path "./anc" (Split-Path -Leaf $_) } | Out-Null # Finish by attaching the hashtable of build files to the manifest # and returning it. $expandedManifest = $Manifest.Clone(); $expandedManifest["DestinationTeXMain"] = $texMainDest; $expandedManifest["BuildFiles"] = $buildFiles; $expandedManifest } function Copy-ArXivArchive { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [hashtable] $ExpandedManifest ) $tempDirName = [System.IO.Path]::GetTempFileName(); Remove-Item $tempDirName; New-Item -ItemType Directory -Path $tempDirName | Out-Null; Write-Host -ForegroundColor Blue "Copying arXiv build files to $tempDirName." $ExpandedManifest["BuildFiles"].GetEnumerator() | % { $target = Join-Path $tempDirName $_.Value; $targetDir = Split-Path $target; # Make the target directory if it doesn't exist. if (!(Get-Item $targetDir -ErrorAction SilentlyContinue)) { New-Item -ItemType Directory $targetDir } write-host "Copying $($_.Key) -> $target" Copy-Item $_.Key $target } | Out-Null; $tempDirName } function Export-ArXivArchive { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [hashtable] $Manifest, [switch] $RunNotebooks ); $ExpandedManifest = Expand-ArXivManifest $Manifest; # Invoke the default TeX build engine in the main project directory, # so that we can make all required TeX artifacts (e.g. *.bbl) from # files that shouldn't be included in the final arXiv build. Invoke-TeXBuildEngine $ExpandedManifest.TeXMain; if ($RunNotebooks -and $ExpandedManifest.Notebooks.Count -ge 0) { $ExpandedManifest.Notebooks | Update-JupyterNotebook } $tempDir = Copy-ArXivArchive $ExpandedManifest; $tempTexMain = Join-Path $tempDir $ExpandedManifest.DestinationTeXMain if ($ExpandedManifest["RenewCommands"]) { Write-Host -ForegroundColor Blue "Rewriting commands on temporary copy."; Update-LaTeXCommands $tempTexMain $ExpandedManifest["RenewCommands"]; } # Invoke pdfLaTeX in the temporary directory to ensure that the rewritten commands # and copied build artifacts (e.g. *.bbl) are correctly utilized. Write-Host -ForegroundColor Blue "Invoking TeX on temporary copy: $tempTexMain." & "pdflatex" $tempTexMain; $archiveName = "./$($ExpandedManifest["ProjectName"]).zip" # We make the final ZIP file using the native zip command # on POSIX in lieu of # https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/26. if (Test-IsPOSIX) { if (Get-ChildItem $archiveName -ErrorAction SilentlyContinue) { Remove-Item $archiveName } pushd . cd $tempDir zip -r $archiveName . popd mv (Join-Path $tempDir $archiveName) . } else { Compress-Archive -Force -Path (Join-Path $tempDir "*") -DestinationPath $archiveName } Write-Host -ForegroundColor Blue "Wrote arXiv archive to $archiveName." Remove-Item -Force -Recurse $tempDir; } ## EXAMPLE MANIFEST ## $ExampleManifest = @{ ProjectName = "foo"; TeXMain = "tex/foo.tex"; AdditionalFiles = @{ "fig/*.pdf" = $null; "fig/*.png" = $null; "tex/*.sty" = "/"; "fig/*.mp4" = "anc/"; }; }
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/Jupyter.ps1
Jupyter.ps1
#!/usr/bin/env powershell ## # Jupyter.ps1: Cmdlets for working with Jupyter notebooks. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## COMMANDS ## function Invoke-Python { [CmdletBinding()] param( [string] $Source, [hashtable] $Variables = @{}, [hashtable] $Import = @{} ); $headerLines = @( # Set the encoding to match what we'll specify when we # call Out-File below. "# -*- coding: utf-8 -*-", # Future proof to make this cmdlet more 2/3 agnostic. "from __future__ import division, print_function" ) # Possibly handle additional variables. if ($Variables.Count) { # We'll pass variables as JSON. $headerLines += "from json import loads" foreach ($item in $Variables.GetEnumerator()) { $jsonPayload = ($item | ConvertTo-Json); $headerLines += "$($item.Name) = loads(r`'`'`'$jsonPayload`'`'`')['Value']" } # Remove the side effect of having imported json.loads. $headerLines += "del loads" } # Possibly import additional modules. if ($Import.Count) { foreach ($item in $Import.GetEnumerator()) { if ($item.Value -eq $null) { $headerLines += "import $($item.Name)" } else { $headerLines += "import $($item.Name) as $($item.Value)" } } } if ($DebugPreference) { Write-Host ([System.String]::Join("`n", $headerLines)); } $tempFile = [System.IO.Path]::GetTempFileName(); ($headerLines + $Source) | Out-File -FilePath $tempFile -Encoding utf8; python $tempFile | Write-Output; Remove-Item $tempFile | Out-Null; } function Update-JupyterNotebook { [CmdletBinding()] param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true )] [string[]] $Path, $NotebookKernel = $null ) $script = @" from nbconvert.preprocessors import ExecutePreprocessor try: import nb_conda_kernels # Now monkey patch the conda KernelSpecManager into # jupyter_client into jupyter_client.kernelspec, as used by # jupyter_client.manager, as used in turn by nbconvert. import jupyter_client.kernelspec jupyter_client.kernelspec.KernelSpecManager = nb_conda_kernels.CondaKernelSpecManager print("Successfully loaded Anaconda extensions.") except ImportError as ex: print(ex) if notebook_kernel: ep = ExecutePreprocessor(kernel_name=notebook_kernel) else: ep = ExecutePreprocessor() with open(notebook_path, 'r') as notebook_file: nb = nbformat.read(notebook_file, as_version=4) ep.preprocess(nb, {'metadata': { 'path': os.path.split(notebook_path)[0] }}) with open(notebook_path, 'w') as notebook_file: nbformat.write(nb, notebook_file) "@ process { foreach ($notebookPath in $Path) { Invoke-Python -Import @{ "sys" = $null; "os" = $null; "nbformat" = $null; } -Variables @{ notebook_kernel = $NotebookKernel; notebook_path = $notebookPath; } -Source $script } } }
PowerShellCorpus/PowerShellGallery/posh-tex/0.1.5/cmdlets/TeX.ps1
TeX.ps1
#!/usr/bin/env powershell ## # TeX.ps1: Cmdlets for interacting with MiKTeX, TeX Live, etc. ## # © 2017 Christopher Granade (cgranade@cgranade.com) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of PoShTeX nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## ENUMS ## try { Add-Type -TypeDefinition @" public enum TeXDistributions { MiKTeX, TeXLive, Other, None } "@ } catch {} ## COMMANDS ## function Get-TeXDistribution { [CmdletBinding()] param( ); if (Get-Command tex -ErrorAction SilentlyContinue) { $versionOutput = tex --version; $versionHeader = $versionOutput.Split([environment]::NewLine)[0]; if ($versionHeader.Contains("MiKTeX")) { return [TeXDistributions]::MiKTeX; } elseif ($versionHeader.Contains("TeX Live")) { return [TeXDistributions]::TeXLive; } else { return [TeXDistributions]::Other; } } else { return [TeXDistributions]::None; } } function Get-TeXUserDir { [CmdletBinding()] param( [System.Nullable``1[[TeXDistributions]]] $TeXDist = $null ) if (!($TeXDist)) { $TeXDist = Get-TeXDistribution; } switch ($TeXDist) { "MiKTeX" { $MiKTeXReport = initexmf --report; foreach ($reportLine in $MiKTeXReport.Split([environment]::NewLine)) { if ($reportLine.Contains(":")) { # The [int] here is a workaround for a bug in PowerShell 6.0.0-alpha: # https://github.com/PowerShell/PowerShell/issues/3137 $key, $value = $reportLine.Split(":", [int]2); if ($key.ToLower().Trim() -eq "userinstall") { return $value.Trim(); } } } throw [System.IO.FileNotFoundException] "No MiKTeX user install directory found."; } "TeXLive" { return kpsewhich --expand-var='$TEXMFHOME'; } "Other" { # Make a resonable guess if we can't figure out otherwise. return Resolve-Path "~/texmf"; } } } function Update-TeXHash { [CmdletBinding()] param( [System.Nullable``1[[TeXDistributions]]] $TeXDist = $null ) if (!($TeXDist)) { $TeXDist = Get-TeXDistribution; } switch ($TeXDist) { "MiKTeX" { initexmf --update-fndb } "TeXLive" { texhash } "Other" { texhash } } } function Install-TeXUserResource { [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='Medium' )] param( [string] $TDSPath, [string[]] $ResourcePath, [string] $TeXUserDir = $null ) if (!($TeXUserDir)) { $TeXUserDir = Get-TeXUserDir; } ( Install-Resources ` -PathAtDestination $TDSPath ` -ResourcePath $ResourcePath ` -DestinationRoot $TeXUserDir ` -Prompt "Install TeX user resource?" ` ) Update-TeXHash } function Out-TeXStyle { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] $StyleName ); if (get-extension $StyleName) { $insName = set-extension $StyleName "ins"; } else { $insName = "$StyleName.ins"; } if (!(Get-Item $insName -ErrorAction SilentlyContinue)) { Write-Error -Message "INS file $insName not found." -Category ObjectNotFound } latex $insName; } function Out-TeXStyleDocumentation { # FIXME: copypasta with previous cmdlet. [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] $StyleName ); if (get-extension $StyleName) { $dtxName = set-extension $StyleName "dtx"; } else { $dtxName = "$StyleName.dtx"; } if (!(Get-Item $dtxName -ErrorAction SilentlyContinue)) { Write-Error -Message "DocStrip file $dtxName not found." -Category ObjectNotFound } Invoke-TeXBuildEngine $dtxName; } function Update-LaTeXCommands { [CmdletBinding()] param( [string] $Name, [hashtable] $Commands ) # We add content by using piping Get-Content to Set-Content, # and adding extra things to the pipeline when we see \begin{document}. # See http://stackoverflow.com/a/1875662/267841. (Get-Content $Name) | ForEach-Object { if ($_ -match ".*\\begin{document}.*") { "% The following commands were added by PoShTeX. Please do not edit by hand." | Write-Output; $Commands.GetEnumerator() | ForEach-Object { "\renewcommand{\$($_.Key)}{$($_.Value)}" | Write-Output }; "% End autogenerated commands." | Write-Output; } # Echo the original line regardless. $_ | Write-Output } | Set-Content $Name } function Invoke-TeXBuildEngine { # TODO: needs to switch PDF/DVI. [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] $Name, [System.Nullable``1[[TeXDistributions]]] $TeXDist = $null ) if (!($TeXDist)) { $TeXDist = Get-TeXDistribution; } switch ($TeXDist) { "MiKTeX" { $preferredCommand = "texify"; $args = "--pdf"; } "TeXLive" { $preferredCommand = "latexmk"; $args = "-pdf"; } default { $preferredCommand = $null; $args = ""; } } if ($preferredCommand -and (Get-Command $preferredCommand -ErrorAction SilentlyContinue)) { Write-Host -ForegroundColor Blue "Building $Name using $preferredCommand..." & "$preferredCommand" $args $Name } else { Write-Host -ForegroundColor Blue "Building $Name manually using pdflatex and bibtex..." pdflatex $Name pdflatex $Name bibtex $Name pdflatex $Name } }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/MSGraphAPIClasses.ps1
MSGraphAPIClasses.ps1
Class microsoft_graph_entity_v1_0 { [object]$id; [hashtable]$GraphAdditionalProperties = @{}; } Class microsoft_graph_directoryObject_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_device_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$accountEnabled; [object]$operatingSystem; [object]$displayName; [object]$operatingSystemVersion; [object]$deviceVersion; [object]$alternativeSecurityIds; [object]$onPremisesLastSyncDateTime; [object]$approximateLastSignInDateTime; [object]$physicalIds; [object]$isManaged; [object]$deviceMetadata; [object]$trustType; [object]$deviceId; [object]$onPremisesSyncEnabled; [object]$isCompliant; [object]Get_registeredOwners() { return (Invoke-GraphMethod -Version 'v1.0' -Query "devices/$($this.Id)/registeredOwners") } [object]Get_registeredUsers() { return (Invoke-GraphMethod -Version 'v1.0' -Query "devices/$($this.Id)/registeredUsers") } } Class microsoft_graph_directoryRole_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$description; [object]$displayName; [object]$roleTemplateId; [object]Get_members() { return (Invoke-GraphMethod -Version 'v1.0' -Query "directoryRoles/$($this.Id)/members") } } Class microsoft_graph_directoryRoleTemplate_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$displayName; [object]$description; } Class microsoft_graph_group_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$onPremisesSyncEnabled; [object]$description; [object]$displayName; [object]$allowExternalSenders; [object]$unseenCount; [object]$onPremisesSecurityIdentifier; [object]$securityEnabled; [object]$groupTypes; [object]$proxyAddresses; [object]$onPremisesLastSyncDateTime; [object]$mail; [object]$isSubscribedByMail; [object]$visibility; [object]$autoSubscribeNewMembers; [object]$mailEnabled; [object]$mailNickname; [object]Get_members() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/members") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/memberOf") } [object]Get_createdOnBehalfOf() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/createdOnBehalfOf") } [object]Get_owners() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/owners") } [object]Get_threads() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/threads") } [object]Get_calendar() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/calendar") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/calendarView") } [object]Get_events() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/events") } [object]Get_conversations() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/conversations") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/photo") } [object]Get_acceptedSenders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/acceptedSenders") } [object]Get_rejectedSenders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/rejectedSenders") } [object]Get_drive() { return (Invoke-GraphMethod -Version 'v1.0' -Query "groups/$($this.Id)/drive") } } Class microsoft_graph_conversationThread_v1_0 : microsoft_graph_entity_v1_0 { [object]$lastDeliveredDateTime; [object]$toRecipients; [object]$hasAttachments; [object]$isLocked; [object]$topic; [object]$uniqueSenders; [object]$preview; [object]$ccRecipients; [object]Get_posts() { return (Invoke-GraphMethod -Version 'v1.0' -Query "conversationThreads/$($this.Id)/posts") } } Class microsoft_graph_calendar_v1_0 : microsoft_graph_entity_v1_0 { [object]$changeKey; [object]$color; [object]$name; [object]Get_events() { return (Invoke-GraphMethod -Version 'v1.0' -Query "calendars/$($this.Id)/events") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'v1.0' -Query "calendars/$($this.Id)/calendarView") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "calendars/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "calendars/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_outlookItem_v1_0 : microsoft_graph_entity_v1_0 { [object]$changeKey; [object]$lastModifiedDateTime; [object]$createdDateTime; [object]$categories; } Class microsoft_graph_event_v1_0 : microsoft_graph_outlookItem_v1_0 { [object]$onlineMeetingUrl; [object]$isReminderOn; [object]$subject; [object]$webLink; [object]$originalStart; [object]$isCancelled; [object]$sensitivity; [object]$start; [object]$location; [object]$attendees; [object]$originalStartTimeZone; [object]$responseStatus; [object]$showAs; [object]$isOrganizer; [object]$originalEndTimeZone; [object]$isAllDay; [object]$end; [object]$responseRequested; [object]$bodyPreview; [object]$recurrence; [object]$hasAttachments; [object]$body; [object]$type; [object]$importance; [object]$seriesMasterId; [object]$organizer; [object]$iCalUId; [object]$reminderMinutesBeforeStart; [object]Get_calendar() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/calendar") } [object]Get_instances() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/instances") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/extensions") } [object]Get_attachments() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/attachments") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "events/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_conversation_v1_0 : microsoft_graph_entity_v1_0 { [object]$lastDeliveredDateTime; [object]$preview; [object]$uniqueSenders; [object]$hasAttachments; [object]$topic; [object]Get_threads() { return (Invoke-GraphMethod -Version 'v1.0' -Query "conversations/$($this.Id)/threads") } } Class microsoft_graph_profilePhoto_v1_0 : microsoft_graph_entity_v1_0 { [object]$height; [object]$width; } Class microsoft_graph_drive_v1_0 : microsoft_graph_entity_v1_0 { [object]$driveType; [object]$quota; [object]$owner; [object]Get_items() { return (Invoke-GraphMethod -Version 'v1.0' -Query "drives/$($this.Id)/items") } [object]Get_special() { return (Invoke-GraphMethod -Version 'v1.0' -Query "drives/$($this.Id)/special") } [object]Get_root() { return (Invoke-GraphMethod -Version 'v1.0' -Query "drives/$($this.Id)/root") } } Class microsoft_graph_subscribedSku_v1_0 : microsoft_graph_entity_v1_0 { [object]$skuPartNumber; [object]$appliesTo; [object]$prepaidUnits; [object]$skuId; [object]$servicePlans; [object]$capabilityStatus; [object]$consumedUnits; } Class microsoft_graph_organization_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$onPremisesSyncEnabled; [object]$country; [object]$verifiedDomains; [object]$displayName; [object]$assignedPlans; [object]$securityComplianceNotificationPhones; [object]$marketingNotificationEmails; [object]$businessPhones; [object]$street; [object]$onPremisesLastSyncDateTime; [object]$technicalNotificationMails; [object]$countryLetterCode; [object]$preferredLanguage; [object]$state; [object]$provisionedPlans; [object]$city; [object]$postalCode; [object]$securityComplianceNotificationMails; } Class microsoft_graph_user_v1_0 : microsoft_graph_directoryObject_v1_0 { [object]$postalCode; [object]$preferredName; [object]$accountEnabled; [object]$mailNickname; [object]$department; [object]$interests; [object]$displayName; [object]$jobTitle; [object]$officeLocation; [object]$passwordPolicies; [object]$birthday; [object]$mailboxSettings; [object]$userType; [object]$preferredLanguage; [object]$state; [object]$mobilePhone; [object]$mySite; [object]$responsibilities; [object]$assignedPlans; [object]$assignedLicenses; [object]$schools; [object]$country; [object]$givenName; [object]$passwordProfile; [object]$pastProjects; [object]$aboutMe; [object]$hireDate; [object]$streetAddress; [object]$city; [object]$proxyAddresses; [object]$onPremisesImmutableId; [object]$provisionedPlans; [object]$companyName; [object]$usageLocation; [object]$surname; [object]$userPrincipalName; [object]$mail; [object]$businessPhones; [object]$onPremisesSyncEnabled; [object]$skills; [object]$onPremisesSecurityIdentifier; [object]$onPremisesLastSyncDateTime; [object]Get_ownedDevices() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/ownedDevices") } [object]Get_registeredDevices() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/registeredDevices") } [object]Get_manager() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/manager") } [object]Get_directReports() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/directReports") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/memberOf") } [object]Get_createdObjects() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/createdObjects") } [object]Get_ownedObjects() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/ownedObjects") } [object]Get_messages() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/messages") } [object]Get_mailFolders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/mailFolders") } [object]Get_calendar() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/calendar") } [object]Get_calendars() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/calendars") } [object]Get_calendarGroups() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/calendarGroups") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/calendarView") } [object]Get_events() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/events") } [object]Get_contacts() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/contacts") } [object]Get_contactFolders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/contactFolders") } [object]Get_inferenceClassification() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/inferenceClassification") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/photo") } [object]Get_drive() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/drive") } [object]Get_drives() { return (Invoke-GraphMethod -Version 'v1.0' -Query "users/$($this.Id)/drives") } } Class microsoft_graph_message_v1_0 : microsoft_graph_outlookItem_v1_0 { [object]$internetMessageId; [object]$uniqueBody; [object]$body; [object]$subject; [object]$importance; [object]$isDraft; [object]$conversationId; [object]$sentDateTime; [object]$bccRecipients; [object]$isRead; [object]$isReadReceiptRequested; [object]$isDeliveryReceiptRequested; [object]$replyTo; [object]$sender; [object]$webLink; [object]$ccRecipients; [object]$bodyPreview; [object]$hasAttachments; [object]$inferenceClassification; [object]$from; [object]$receivedDateTime; [object]$parentFolderId; [object]$toRecipients; [object]Get_attachments() { return (Invoke-GraphMethod -Version 'v1.0' -Query "messages/$($this.Id)/attachments") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "messages/$($this.Id)/extensions") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "messages/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "messages/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_mailFolder_v1_0 : microsoft_graph_entity_v1_0 { [object]$totalItemCount; [object]$childFolderCount; [object]$displayName; [object]$parentFolderId; [object]$unreadItemCount; [object]Get_messages() { return (Invoke-GraphMethod -Version 'v1.0' -Query "mailFolders/$($this.Id)/messages") } [object]Get_childFolders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "mailFolders/$($this.Id)/childFolders") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "mailFolders/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "mailFolders/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_calendarGroup_v1_0 : microsoft_graph_entity_v1_0 { [object]$changeKey; [object]$classId; [object]$name; [object]Get_calendars() { return (Invoke-GraphMethod -Version 'v1.0' -Query "calendarGroups/$($this.Id)/calendars") } } Class microsoft_graph_contact_v1_0 : microsoft_graph_outlookItem_v1_0 { [object]$middleName; [object]$yomiCompanyName; [object]$generation; [object]$businessAddress; [object]$imAddresses; [object]$department; [object]$yomiSurname; [object]$displayName; [object]$jobTitle; [object]$nickName; [object]$businessHomePage; [object]$birthday; [object]$fileAs; [object]$otherAddress; [object]$homeAddress; [object]$mobilePhone; [object]$givenName; [object]$title; [object]$assistantName; [object]$personalNotes; [object]$profession; [object]$homePhones; [object]$initials; [object]$surname; [object]$spouseName; [object]$manager; [object]$children; [object]$officeLocation; [object]$parentFolderId; [object]$companyName; [object]$businessPhones; [object]$emailAddresses; [object]$yomiGivenName; [object]Get_extensions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contacts/$($this.Id)/extensions") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contacts/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contacts/$($this.Id)/multiValueExtendedProperties") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contacts/$($this.Id)/photo") } } Class microsoft_graph_contactFolder_v1_0 : microsoft_graph_entity_v1_0 { [object]$parentFolderId; [object]$displayName; [object]Get_contacts() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contactFolders/$($this.Id)/contacts") } [object]Get_childFolders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contactFolders/$($this.Id)/childFolders") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contactFolders/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "contactFolders/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_inferenceClassification_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_overrides() { return (Invoke-GraphMethod -Version 'v1.0' -Query "inferenceClassifications/$($this.Id)/overrides") } } Class microsoft_graph_attachment_v1_0 : microsoft_graph_entity_v1_0 { [object]$contentType; [object]$lastModifiedDateTime; [object]$isInline; [object]$name; [object]$size; } Class microsoft_graph_singleValueLegacyExtendedProperty_v1_0 : microsoft_graph_entity_v1_0 { [object]$value; } Class microsoft_graph_multiValueLegacyExtendedProperty_v1_0 : microsoft_graph_entity_v1_0 { [object]$value; } Class microsoft_graph_extension_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_fileAttachment_v1_0 : microsoft_graph_attachment_v1_0 { [object]$contentId; [object]$contentLocation; [object]$contentBytes; } Class microsoft_graph_itemAttachment_v1_0 : microsoft_graph_attachment_v1_0 { [object]Get_item() { return (Invoke-GraphMethod -Version 'v1.0' -Query "itemAttachments/$($this.Id)/item") } } Class microsoft_graph_eventMessage_v1_0 : microsoft_graph_message_v1_0 { [object]$meetingMessageType; [object]Get_event() { return (Invoke-GraphMethod -Version 'v1.0' -Query "eventMessages/$($this.Id)/event") } } Class microsoft_graph_referenceAttachment_v1_0 : microsoft_graph_attachment_v1_0 { } Class microsoft_graph_openTypeExtension_v1_0 : microsoft_graph_extension_v1_0 { [object]$extensionName; } Class microsoft_graph_post_v1_0 : microsoft_graph_outlookItem_v1_0 { [object]$hasAttachments; [object]$receivedDateTime; [object]$conversationThreadId; [object]$sender; [object]$newParticipants; [object]$body; [object]$from; [object]$conversationId; [object]Get_extensions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "posts/$($this.Id)/extensions") } [object]Get_inReplyTo() { return (Invoke-GraphMethod -Version 'v1.0' -Query "posts/$($this.Id)/inReplyTo") } [object]Get_attachments() { return (Invoke-GraphMethod -Version 'v1.0' -Query "posts/$($this.Id)/attachments") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "posts/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'v1.0' -Query "posts/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_inferenceClassificationOverride_v1_0 : microsoft_graph_entity_v1_0 { [object]$senderEmailAddress; [object]$classifyAs; } Class microsoft_graph_driveItem_v1_0 : microsoft_graph_entity_v1_0 { [object]$lastModifiedBy; [object]$lastModifiedDateTime; [object]$video; [object]$cTag; [object]$createdDateTime; [object]$content; [object]$folder; [object]$location; [object]$size; [object]$remoteItem; [object]$image; [object]$eTag; [object]$parentReference; [object]$createdBy; [object]$file; [object]$photo; [object]$deleted; [object]$package; [object]$description; [object]$searchResult; [object]$fileSystemInfo; [object]$audio; [object]$webDavUrl; [object]$webUrl; [object]$shared; [object]$root; [object]$specialFolder; [object]$name; [object]$sharepointIds; [object]Get_createdByUser() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/createdByUser") } [object]Get_workbook() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/workbook") } [object]Get_lastModifiedByUser() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/lastModifiedByUser") } [object]Get_children() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/children") } [object]Get_permissions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/permissions") } [object]Get_thumbnails() { return (Invoke-GraphMethod -Version 'v1.0' -Query "driveItems/$($this.Id)/thumbnails") } } Class microsoft_graph_workbook_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_application() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbooks/$($this.Id)/application") } [object]Get_names() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbooks/$($this.Id)/names") } [object]Get_tables() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbooks/$($this.Id)/tables") } [object]Get_worksheets() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbooks/$($this.Id)/worksheets") } [object]Get_functions() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbooks/$($this.Id)/functions") } } Class microsoft_graph_permission_v1_0 : microsoft_graph_entity_v1_0 { [object]$link; [object]$roles; [object]$shareId; [object]$inheritedFrom; [object]$grantedTo; [object]$invitation; } Class microsoft_graph_thumbnailSet_v1_0 : microsoft_graph_entity_v1_0 { [object]$source; [object]$large; [object]$small; [object]$medium; } Class microsoft_graph_sharedDriveItem_v1_0 : microsoft_graph_entity_v1_0 { [object]$name; [object]$owner; [object]Get_root() { return (Invoke-GraphMethod -Version 'v1.0' -Query "sharedDriveItems/$($this.Id)/root") } [object]Get_items() { return (Invoke-GraphMethod -Version 'v1.0' -Query "sharedDriveItems/$($this.Id)/items") } } Class microsoft_graph_sharePoint_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_site_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_list_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_workbookApplication_v1_0 : microsoft_graph_entity_v1_0 { [object]$calculationMode; } Class microsoft_graph_workbookNamedItem_v1_0 : microsoft_graph_entity_v1_0 { [object]$comment; [object]$type; [object]$visible; [object]$value; [object]$name; [object]$scope; [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookNamedItems/$($this.Id)/worksheet") } } Class microsoft_graph_workbookTable_v1_0 : microsoft_graph_entity_v1_0 { [object]$showBandedColumns; [object]$showTotals; [object]$showBandedRows; [object]$showFilterButton; [object]$name; [object]$showHeaders; [object]$highlightFirstColumn; [object]$style; [object]$highlightLastColumn; [object]Get_columns() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookTables/$($this.Id)/columns") } [object]Get_rows() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookTables/$($this.Id)/rows") } [object]Get_sort() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookTables/$($this.Id)/sort") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookTables/$($this.Id)/worksheet") } } Class microsoft_graph_workbookWorksheet_v1_0 : microsoft_graph_entity_v1_0 { [object]$position; [object]$visibility; [object]$name; [object]Get_charts() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookWorksheets/$($this.Id)/charts") } [object]Get_names() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookWorksheets/$($this.Id)/names") } [object]Get_pivotTables() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookWorksheets/$($this.Id)/pivotTables") } [object]Get_protection() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookWorksheets/$($this.Id)/protection") } [object]Get_tables() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookWorksheets/$($this.Id)/tables") } } Class microsoft_graph_workbookFunctions_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_workbookChart_v1_0 : microsoft_graph_entity_v1_0 { [object]$left; [object]$width; [object]$name; [object]$height; [object]$top; [object]Get_axes() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/axes") } [object]Get_dataLabels() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/dataLabels") } [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/format") } [object]Get_legend() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/legend") } [object]Get_series() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/series") } [object]Get_title() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/title") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookCharts/$($this.Id)/worksheet") } } Class microsoft_graph_workbookChartAxes_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_categoryAxis() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxess/$($this.Id)/categoryAxis") } [object]Get_seriesAxis() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxess/$($this.Id)/seriesAxis") } [object]Get_valueAxis() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxess/$($this.Id)/valueAxis") } } Class microsoft_graph_workbookChartDataLabels_v1_0 : microsoft_graph_entity_v1_0 { [object]$position; [object]$showLegendKey; [object]$showSeriesName; [object]$showPercentage; [object]$separator; [object]$showBubbleSize; [object]$showValue; [object]$showCategoryName; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartDataLabelss/$($this.Id)/format") } } Class microsoft_graph_workbookChartAreaFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAreaFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAreaFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartLegend_v1_0 : microsoft_graph_entity_v1_0 { [object]$position; [object]$overlay; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartLegends/$($this.Id)/format") } } Class microsoft_graph_workbookChartSeries_v1_0 : microsoft_graph_entity_v1_0 { [object]$name; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartSeriess/$($this.Id)/format") } [object]Get_points() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartSeriess/$($this.Id)/points") } } Class microsoft_graph_workbookChartTitle_v1_0 : microsoft_graph_entity_v1_0 { [object]$overlay; [object]$text; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartTitles/$($this.Id)/format") } } Class microsoft_graph_workbookChartFill_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_workbookChartFont_v1_0 : microsoft_graph_entity_v1_0 { [object]$underline; [object]$italic; [object]$color; [object]$name; [object]$size; [object]$bold; } Class microsoft_graph_workbookChartAxis_v1_0 : microsoft_graph_entity_v1_0 { [object]$minimum; [object]$majorUnit; [object]$minorUnit; [object]$maximum; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxiss/$($this.Id)/format") } [object]Get_majorGridlines() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxiss/$($this.Id)/majorGridlines") } [object]Get_minorGridlines() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxiss/$($this.Id)/minorGridlines") } [object]Get_title() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxiss/$($this.Id)/title") } } Class microsoft_graph_workbookChartAxisFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxisFormats/$($this.Id)/font") } [object]Get_line() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxisFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartGridlines_v1_0 : microsoft_graph_entity_v1_0 { [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartGridliness/$($this.Id)/format") } } Class microsoft_graph_workbookChartAxisTitle_v1_0 : microsoft_graph_entity_v1_0 { [object]$text; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxisTitles/$($this.Id)/format") } } Class microsoft_graph_workbookChartLineFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]$color; } Class microsoft_graph_workbookChartAxisTitleFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartAxisTitleFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartDataLabelFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartDataLabelFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartDataLabelFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartGridlinesFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_line() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartGridlinesFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartLegendFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartLegendFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartLegendFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartPoint_v1_0 : microsoft_graph_entity_v1_0 { [object]$value; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartPoints/$($this.Id)/format") } } Class microsoft_graph_workbookChartPointFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartPointFormats/$($this.Id)/fill") } } Class microsoft_graph_workbookChartSeriesFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartSeriesFormats/$($this.Id)/fill") } [object]Get_line() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartSeriesFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartTitleFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartTitleFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookChartTitleFormats/$($this.Id)/font") } } Class microsoft_graph_workbookFilter_v1_0 : microsoft_graph_entity_v1_0 { [object]$criteria; } Class microsoft_graph_workbookFormatProtection_v1_0 : microsoft_graph_entity_v1_0 { [object]$formulaHidden; [object]$locked; } Class microsoft_graph_workbookFunctionResult_v1_0 : microsoft_graph_entity_v1_0 { [object]$error; [object]$value; } Class microsoft_graph_workbookPivotTable_v1_0 : microsoft_graph_entity_v1_0 { [object]$name; [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookPivotTables/$($this.Id)/worksheet") } } Class microsoft_graph_workbookRange_v1_0 : microsoft_graph_entity_v1_0 { [object]$cellCount; [object]$columnHidden; [object]$addressLocal; [object]$rowIndex; [object]$rowHidden; [object]$valueTypes; [object]$values; [object]$hidden; [object]$formulasR1C1; [object]$address; [object]$columnIndex; [object]$formulas; [object]$numberFormat; [object]$formulasLocal; [object]$columnCount; [object]$text; [object]$rowCount; [object]Get_format() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRanges/$($this.Id)/format") } [object]Get_sort() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRanges/$($this.Id)/sort") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRanges/$($this.Id)/worksheet") } } Class microsoft_graph_workbookRangeFormat_v1_0 : microsoft_graph_entity_v1_0 { [object]$verticalAlignment; [object]$horizontalAlignment; [object]$columnWidth; [object]$rowHeight; [object]$wrapText; [object]Get_borders() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRangeFormats/$($this.Id)/borders") } [object]Get_fill() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRangeFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRangeFormats/$($this.Id)/font") } [object]Get_protection() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRangeFormats/$($this.Id)/protection") } } Class microsoft_graph_workbookRangeSort_v1_0 : microsoft_graph_entity_v1_0 { } Class microsoft_graph_workbookRangeBorder_v1_0 : microsoft_graph_entity_v1_0 { [object]$sideIndex; [object]$color; [object]$style; [object]$weight; } Class microsoft_graph_workbookRangeFill_v1_0 : microsoft_graph_entity_v1_0 { [object]$color; } Class microsoft_graph_workbookRangeFont_v1_0 : microsoft_graph_entity_v1_0 { [object]$underline; [object]$italic; [object]$color; [object]$name; [object]$size; [object]$bold; } Class microsoft_graph_workbookRangeView_v1_0 : microsoft_graph_entity_v1_0 { [object]$numberFormat; [object]$text; [object]$cellAddresses; [object]$formulas; [object]$formulasLocal; [object]$rowCount; [object]$index; [object]$values; [object]$valueTypes; [object]$formulasR1C1; [object]$columnCount; [object]Get_rows() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookRangeViews/$($this.Id)/rows") } } Class microsoft_graph_workbookTableColumn_v1_0 : microsoft_graph_entity_v1_0 { [object]$values; [object]$name; [object]$index; [object]Get_filter() { return (Invoke-GraphMethod -Version 'v1.0' -Query "workbookTableColumns/$($this.Id)/filter") } } Class microsoft_graph_workbookTableRow_v1_0 : microsoft_graph_entity_v1_0 { [object]$values; [object]$index; } Class microsoft_graph_workbookTableSort_v1_0 : microsoft_graph_entity_v1_0 { [object]$method; [object]$fields; [object]$matchCase; } Class microsoft_graph_workbookWorksheetProtection_v1_0 : microsoft_graph_entity_v1_0 { [object]$options; [object]$protected; } Class microsoft_graph_subscription_v1_0 : microsoft_graph_entity_v1_0 { [object]$clientState; [object]$resource; [object]$changeType; [object]$expirationDateTime; [object]$notificationUrl; } Class microsoft_graph_invitation_v1_0 : microsoft_graph_entity_v1_0 { [object]$invitedUserMessageInfo; [object]$invitedUserType; [object]$sendInvitationMessage; [object]$invitedUserEmailAddress; [object]$inviteRedeemUrl; [object]$invitedUserDisplayName; [object]$status; [object]$inviteRedirectUrl; [object]Get_invitedUser() { return (Invoke-GraphMethod -Version 'v1.0' -Query "invitations/$($this.Id)/invitedUser") } } Class microsoft_graph_entity_beta { [object]$id; [hashtable]$GraphAdditionalProperties = @{}; } Class microsoft_graph_directory_beta : microsoft_graph_entity_beta { [object]Get_deletedItems() { return (Invoke-GraphMethod -Version 'beta' -Query "directorys/$($this.Id)/deletedItems") } } Class microsoft_graph_directoryObject_beta : microsoft_graph_entity_beta { } Class microsoft_graph_extensionProperty_beta : microsoft_graph_directoryObject_beta { [object]$targetObjects; [object]$isSyncedFromOnPremises; [object]$appDisplayName; [object]$name; [object]$dataType; } Class microsoft_graph_endpoint_beta : microsoft_graph_directoryObject_beta { [object]$providerResourceId; [object]$capability; [object]$providerId; [object]$providerName; [object]$uri; } Class microsoft_graph_application_beta : microsoft_graph_directoryObject_beta { [object]$logoutUrl; [object]$oauth2Permissions; [object]$identifierUris; [object]$replyUrls; [object]$displayName; [object]$appId; [object]$publicClient; [object]$errorUrl; [object]$recordConsentConditions; [object]$onPremisesPublishing; [object]$keyCredentials; [object]$oauth2AllowImplicitFlow; [object]$knownClientApplications; [object]$oauth2RequirePostResponse; [object]$passwordCredentials; [object]$groupMembershipClaims; [object]$addIns; [object]$mainLogo; [object]$samlMetadataUrl; [object]$availableToOtherOrganizations; [object]$homepage; [object]$appRoles; [object]$oauth2AllowUrlPathMatching; [object]$requiredResourceAccess; [object]Get_extensionProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "applications/$($this.Id)/extensionProperties") } [object]Get_createdOnBehalfOf() { return (Invoke-GraphMethod -Version 'beta' -Query "applications/$($this.Id)/createdOnBehalfOf") } [object]Get_owners() { return (Invoke-GraphMethod -Version 'beta' -Query "applications/$($this.Id)/owners") } [object]Get_policies() { return (Invoke-GraphMethod -Version 'beta' -Query "applications/$($this.Id)/policies") } [object]Get_connectorGroup() { return (Invoke-GraphMethod -Version 'beta' -Query "applications/$($this.Id)/connectorGroup") } } Class microsoft_graph_connectorGroup_beta : microsoft_graph_entity_beta { [object]$isDefault; [object]$name; [object]$connectorGroupType; [object]Get_members() { return (Invoke-GraphMethod -Version 'beta' -Query "connectorGroups/$($this.Id)/members") } [object]Get_applications() { return (Invoke-GraphMethod -Version 'beta' -Query "connectorGroups/$($this.Id)/applications") } } Class microsoft_graph_appRoleAssignment_beta : microsoft_graph_entity_beta { [object]$resourceId; [object]$principalType; [object]$creationTimestamp; [object]$resourceDisplayName; [object]$principalId; [object]$principalDisplayName; } Class microsoft_graph_orgContact_beta : microsoft_graph_directoryObject_beta { [object]$onPremisesSyncEnabled; [object]$country; [object]$displayName; [object]$companyName; [object]$givenName; [object]$officeLocation; [object]$businessPhones; [object]$surname; [object]$department; [object]$proxyAddresses; [object]$onPremisesLastSyncDateTime; [object]$mail; [object]$streetAddress; [object]$postalCode; [object]$mobilePhone; [object]$state; [object]$mailNickname; [object]$jobTitle; [object]$city; [object]Get_manager() { return (Invoke-GraphMethod -Version 'beta' -Query "orgContacts/$($this.Id)/manager") } [object]Get_directReports() { return (Invoke-GraphMethod -Version 'beta' -Query "orgContacts/$($this.Id)/directReports") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'beta' -Query "orgContacts/$($this.Id)/memberOf") } } Class microsoft_graph_device_beta : microsoft_graph_directoryObject_beta { [object]$accountEnabled; [object]$operatingSystem; [object]$displayName; [object]$operatingSystemVersion; [object]$deviceVersion; [object]$alternativeSecurityIds; [object]$onPremisesLastSyncDateTime; [object]$approximateLastSignInDateTime; [object]$physicalIds; [object]$isManaged; [object]$deviceMetadata; [object]$trustType; [object]$deviceId; [object]$onPremisesSyncEnabled; [object]$isCompliant; [object]Get_registeredOwners() { return (Invoke-GraphMethod -Version 'beta' -Query "devices/$($this.Id)/registeredOwners") } [object]Get_registeredUsers() { return (Invoke-GraphMethod -Version 'beta' -Query "devices/$($this.Id)/registeredUsers") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "devices/$($this.Id)/extensions") } } Class microsoft_graph_extension_beta : microsoft_graph_entity_beta { } Class microsoft_graph_directoryRole_beta : microsoft_graph_directoryObject_beta { [object]$description; [object]$displayName; [object]$roleTemplateId; [object]Get_members() { return (Invoke-GraphMethod -Version 'beta' -Query "directoryRoles/$($this.Id)/members") } [object]Get_scopedAdministrators() { return (Invoke-GraphMethod -Version 'beta' -Query "directoryRoles/$($this.Id)/scopedAdministrators") } } Class microsoft_graph_scopedRoleMembership_beta : microsoft_graph_entity_beta { [object]$roleMemberInfo; [object]$administrativeUnitId; [object]$roleId; } Class microsoft_graph_directoryRoleTemplate_beta : microsoft_graph_directoryObject_beta { [object]$displayName; [object]$description; } Class microsoft_graph_directorySetting_beta : microsoft_graph_entity_beta { [object]$templateId; [object]$displayName; [object]$values; } Class microsoft_graph_directorySettingTemplate_beta : microsoft_graph_directoryObject_beta { [object]$values; [object]$description; [object]$displayName; } Class microsoft_graph_domain_beta : microsoft_graph_entity_beta { [object]$isAdminManaged; [object]$isInitial; [object]$availabilityStatus; [object]$supportedServices; [object]$isRoot; [object]$state; [object]$authenticationType; [object]$isVerified; [object]$isDefault; [object]Get_serviceConfigurationRecords() { return (Invoke-GraphMethod -Version 'beta' -Query "domains/$($this.Id)/serviceConfigurationRecords") } [object]Get_verificationDnsRecords() { return (Invoke-GraphMethod -Version 'beta' -Query "domains/$($this.Id)/verificationDnsRecords") } [object]Get_domainNameReferences() { return (Invoke-GraphMethod -Version 'beta' -Query "domains/$($this.Id)/domainNameReferences") } } Class microsoft_graph_domainDnsRecord_beta : microsoft_graph_entity_beta { [object]$label; [object]$ttl; [object]$isOptional; [object]$supportedService; [object]$recordType; } Class microsoft_graph_domainDnsCnameRecord_beta : microsoft_graph_domainDnsRecord_beta { [object]$canonicalName; } Class microsoft_graph_domainDnsMxRecord_beta : microsoft_graph_domainDnsRecord_beta { [object]$preference; [object]$mailExchange; } Class microsoft_graph_domainDnsSrvRecord_beta : microsoft_graph_domainDnsRecord_beta { [object]$weight; [object]$nameTarget; [object]$port; [object]$service; [object]$priority; [object]$protocol; } Class microsoft_graph_domainDnsTxtRecord_beta : microsoft_graph_domainDnsRecord_beta { [object]$text; } Class microsoft_graph_domainDnsUnavailableRecord_beta : microsoft_graph_domainDnsRecord_beta { [object]$description; } Class microsoft_graph_group_beta : microsoft_graph_directoryObject_beta { [object]$onPremisesSyncEnabled; [object]$membershipRule; [object]$description; [object]$displayName; [object]$mailEnabled; [object]$unseenCount; [object]$createdDateTime; [object]$onPremisesSecurityIdentifier; [object]$theme; [object]$allowExternalSenders; [object]$securityEnabled; [object]$groupTypes; [object]$accessType; [object]$proxyAddresses; [object]$onPremisesLastSyncDateTime; [object]$mail; [object]$renewedDateTime; [object]$preferredLanguage; [object]$visibility; [object]$autoSubscribeNewMembers; [object]$classification; [object]$mailNickname; [object]$membershipRuleProcessingState; [object]$isSubscribedByMail; [object]$isFavorite; [object]Get_members() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/members") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/memberOf") } [object]Get_createdOnBehalfOf() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/createdOnBehalfOf") } [object]Get_owners() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/owners") } [object]Get_settings() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/settings") } [object]Get_endpoints() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/endpoints") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/extensions") } [object]Get_threads() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/threads") } [object]Get_calendar() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/calendar") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/calendarView") } [object]Get_events() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/events") } [object]Get_conversations() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/conversations") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/photo") } [object]Get_photos() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/photos") } [object]Get_acceptedSenders() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/acceptedSenders") } [object]Get_rejectedSenders() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/rejectedSenders") } [object]Get_drive() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/drive") } [object]Get_sharepoint() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/sharepoint") } [object]Get_plans() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/plans") } [object]Get_planner() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/planner") } [object]Get_notes() { return (Invoke-GraphMethod -Version 'beta' -Query "groups/$($this.Id)/notes") } } Class microsoft_graph_conversationThread_beta : microsoft_graph_entity_beta { [object]$lastDeliveredDateTime; [object]$toRecipients; [object]$hasAttachments; [object]$isLocked; [object]$topic; [object]$uniqueSenders; [object]$preview; [object]$ccRecipients; [object]Get_posts() { return (Invoke-GraphMethod -Version 'beta' -Query "conversationThreads/$($this.Id)/posts") } } Class microsoft_graph_calendar_beta : microsoft_graph_entity_beta { [object]$canViewPrivateItems; [object]$changeKey; [object]$color; [object]$canShare; [object]$isDefaultCalendar; [object]$isSharedWithMe; [object]$isShared; [object]$owner; [object]$name; [object]$canEdit; [object]Get_events() { return (Invoke-GraphMethod -Version 'beta' -Query "calendars/$($this.Id)/events") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'beta' -Query "calendars/$($this.Id)/calendarView") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "calendars/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "calendars/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_outlookItem_beta : microsoft_graph_entity_beta { [object]$changeKey; [object]$lastModifiedDateTime; [object]$createdDateTime; [object]$categories; } Class microsoft_graph_event_beta : microsoft_graph_outlookItem_beta { [object]$onlineMeetingUrl; [object]$isReminderOn; [object]$subject; [object]$webLink; [object]$originalStart; [object]$isCancelled; [object]$sensitivity; [object]$start; [object]$location; [object]$attendees; [object]$originalStartTimeZone; [object]$responseStatus; [object]$showAs; [object]$isOrganizer; [object]$originalEndTimeZone; [object]$isAllDay; [object]$end; [object]$responseRequested; [object]$bodyPreview; [object]$recurrence; [object]$hasAttachments; [object]$body; [object]$type; [object]$importance; [object]$seriesMasterId; [object]$organizer; [object]$iCalUId; [object]$reminderMinutesBeforeStart; [object]Get_calendar() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/calendar") } [object]Get_instances() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/instances") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/extensions") } [object]Get_attachments() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/attachments") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "events/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_conversation_beta : microsoft_graph_entity_beta { [object]$lastDeliveredDateTime; [object]$preview; [object]$uniqueSenders; [object]$hasAttachments; [object]$topic; [object]Get_threads() { return (Invoke-GraphMethod -Version 'beta' -Query "conversations/$($this.Id)/threads") } } Class microsoft_graph_profilePhoto_beta : microsoft_graph_entity_beta { [object]$height; [object]$width; } Class microsoft_graph_drive_beta : microsoft_graph_entity_beta { [object]$driveType; [object]$quota; [object]$owner; [object]Get_items() { return (Invoke-GraphMethod -Version 'beta' -Query "drives/$($this.Id)/items") } [object]Get_special() { return (Invoke-GraphMethod -Version 'beta' -Query "drives/$($this.Id)/special") } [object]Get_root() { return (Invoke-GraphMethod -Version 'beta' -Query "drives/$($this.Id)/root") } } Class microsoft_graph_sharePoint_beta : microsoft_graph_entity_beta { [object]Get_site() { return (Invoke-GraphMethod -Version 'beta' -Query "sharePoints/$($this.Id)/site") } [object]Get_sites() { return (Invoke-GraphMethod -Version 'beta' -Query "sharePoints/$($this.Id)/sites") } } Class microsoft_graph_plan_beta : microsoft_graph_entity_beta { [object]$createdBy; [object]$title; [object]$createdDateTime; [object]$owner; [object]$isVisibleInPlannerWebClient; [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/tasks") } [object]Get_buckets() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/buckets") } [object]Get_details() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/details") } [object]Get_assignedToTaskBoard() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/assignedToTaskBoard") } [object]Get_progressTaskBoard() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/progressTaskBoard") } [object]Get_bucketTaskBoard() { return (Invoke-GraphMethod -Version 'beta' -Query "plans/$($this.Id)/bucketTaskBoard") } } Class microsoft_graph_plannerGroup_beta : microsoft_graph_entity_beta { [object]Get_plans() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerGroups/$($this.Id)/plans") } } Class microsoft_graph_notes_beta : microsoft_graph_entity_beta { [object]Get_notebooks() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/notebooks") } [object]Get_sections() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/sections") } [object]Get_sectionGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/sectionGroups") } [object]Get_pages() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/pages") } [object]Get_resources() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/resources") } [object]Get_operations() { return (Invoke-GraphMethod -Version 'beta' -Query "notess/$($this.Id)/operations") } } Class microsoft_graph_licenseDetails_beta : microsoft_graph_entity_beta { [object]$skuPartNumber; [object]$skuId; [object]$servicePlans; } Class microsoft_graph_oAuth2PermissionGrant_beta : microsoft_graph_entity_beta { [object]$resourceId; [object]$clientId; [object]$expiryTime; [object]$consentType; [object]$scope; [object]$principalId; [object]$startTime; } Class microsoft_graph_policy_beta : microsoft_graph_directoryObject_beta { [object]$isOrganizationDefault; [object]$displayName; [object]$definition; [object]$alternativeIdentifier; [object]$type; [object]$keyCredentials; [object]Get_appliesTo() { return (Invoke-GraphMethod -Version 'beta' -Query "policys/$($this.Id)/appliesTo") } } Class microsoft_graph_servicePrincipal_beta : microsoft_graph_directoryObject_beta { [object]$accountEnabled; [object]$oauth2Permissions; [object]$tags; [object]$replyUrls; [object]$preferredTokenSigningKeyThumbprint; [object]$displayName; [object]$appId; [object]$errorUrl; [object]$keyCredentials; [object]$appDisplayName; [object]$appRoleAssignmentRequired; [object]$appOwnerOrganizationId; [object]$addIns; [object]$logoutUrl; [object]$samlMetadataUrl; [object]$homepage; [object]$appRoles; [object]$passwordCredentials; [object]$publisherName; [object]$servicePrincipalNames; [object]Get_appRoleAssignedTo() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/appRoleAssignedTo") } [object]Get_appRoleAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/appRoleAssignments") } [object]Get_oauth2PermissionGrants() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/oauth2PermissionGrants") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/memberOf") } [object]Get_createdObjects() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/createdObjects") } [object]Get_licenseDetails() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/licenseDetails") } [object]Get_owners() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/owners") } [object]Get_ownedObjects() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/ownedObjects") } [object]Get_policies() { return (Invoke-GraphMethod -Version 'beta' -Query "servicePrincipals/$($this.Id)/policies") } } Class microsoft_graph_subscribedSku_beta : microsoft_graph_entity_beta { [object]$skuPartNumber; [object]$appliesTo; [object]$prepaidUnits; [object]$skuId; [object]$servicePlans; [object]$capabilityStatus; [object]$consumedUnits; } Class microsoft_graph_organization_beta : microsoft_graph_directoryObject_beta { [object]$onPremisesSyncEnabled; [object]$country; [object]$defaultDeviceEnrollmentWindowsHelloForBusinessSettings; [object]$verifiedDomains; [object]$displayName; [object]$mobileDeviceManagementAuthority; [object]$assignedPlans; [object]$securityComplianceNotificationPhones; [object]$marketingNotificationEmails; [object]$businessPhones; [object]$applePushNotificationCertificateSetting; [object]$street; [object]$defaultDeviceEnrollmentRestrictions; [object]$onPremisesLastSyncDateTime; [object]$technicalNotificationMails; [object]$countryLetterCode; [object]$preferredLanguage; [object]$state; [object]$provisionedPlans; [object]$defaultDeviceEnrollmentLimit; [object]$city; [object]$postalCode; [object]$securityComplianceNotificationMails; [object]$intuneBrand; [object]$certificateConnectorSetting; [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "organizations/$($this.Id)/extensions") } [object]Get_depOnboardingSettings() { return (Invoke-GraphMethod -Version 'beta' -Query "organizations/$($this.Id)/depOnboardingSettings") } [object]Get_appleVolumePurchaseProgramTokens() { return (Invoke-GraphMethod -Version 'beta' -Query "organizations/$($this.Id)/appleVolumePurchaseProgramTokens") } } Class microsoft_graph_depOnboardingSetting_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$tokenExpirationDateTime; [object]$shareTokenWithSchoolDataSyncService; [object]$lastSyncErrorCode; [object]$lastSuccessfulSyncDateTime; [object]$appleIdentifier; [object]$lastSyncTriggeredDateTime; } Class microsoft_graph_appleVolumePurchaseProgramToken_beta : microsoft_graph_entity_beta { [object]$lastSyncDateTime; [object]$lastSyncStatus; [object]$token; [object]$state; [object]$appleId; [object]$expirationDateTime; [object]$organizationName; [object]$lastModifiedDateTime; [object]$volumePurchaseProgramTokenAccountType; } Class microsoft_graph_user_beta : microsoft_graph_directoryObject_beta { [object]$postalCode; [object]$preferredName; [object]$accountEnabled; [object]$mailNickname; [object]$showInAddressList; [object]$department; [object]$interests; [object]$displayName; [object]$jobTitle; [object]$officeLocation; [object]$passwordPolicies; [object]$birthday; [object]$mailboxSettings; [object]$userType; [object]$identityUserRisk; [object]$preferredLanguage; [object]$state; [object]$mobilePhone; [object]$mySite; [object]$responsibilities; [object]$assignedPlans; [object]$assignedLicenses; [object]$schools; [object]$country; [object]$givenName; [object]$passwordProfile; [object]$pastProjects; [object]$aboutMe; [object]$hireDate; [object]$streetAddress; [object]$refreshTokensValidFromDateTime; [object]$city; [object]$proxyAddresses; [object]$onPremisesImmutableId; [object]$provisionedPlans; [object]$companyName; [object]$usageLocation; [object]$surname; [object]$userPrincipalName; [object]$mail; [object]$businessPhones; [object]$deviceEnrollmentLimit; [object]$onPremisesSyncEnabled; [object]$skills; [object]$onPremisesSecurityIdentifier; [object]$onPremisesLastSyncDateTime; [object]Get_ownedDevices() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/ownedDevices") } [object]Get_registeredDevices() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/registeredDevices") } [object]Get_manager() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/manager") } [object]Get_directReports() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/directReports") } [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/memberOf") } [object]Get_createdObjects() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/createdObjects") } [object]Get_ownedObjects() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/ownedObjects") } [object]Get_scopedAdministratorOf() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/scopedAdministratorOf") } [object]Get_licenseDetails() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/licenseDetails") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/extensions") } [object]Get_messages() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/messages") } [object]Get_joinedGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/joinedGroups") } [object]Get_mailFolders() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/mailFolders") } [object]Get_calendar() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/calendar") } [object]Get_calendars() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/calendars") } [object]Get_calendarGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/calendarGroups") } [object]Get_calendarView() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/calendarView") } [object]Get_events() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/events") } [object]Get_people() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/people") } [object]Get_contacts() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/contacts") } [object]Get_contactFolders() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/contactFolders") } [object]Get_inferenceClassification() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/inferenceClassification") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/photo") } [object]Get_photos() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/photos") } [object]Get_drive() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/drive") } [object]Get_drives() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/drives") } [object]Get_sharepoint() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/sharepoint") } [object]Get_insights() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/insights") } [object]Get_trendingAround() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/trendingAround") } [object]Get_workingWith() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/workingWith") } [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/tasks") } [object]Get_plans() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/plans") } [object]Get_planner() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/planner") } [object]Get_notes() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/notes") } [object]Get_managedDevices() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/managedDevices") } [object]Get_managedAppRegistrations() { return (Invoke-GraphMethod -Version 'beta' -Query "users/$($this.Id)/managedAppRegistrations") } } Class microsoft_graph_message_beta : microsoft_graph_outlookItem_beta { [object]$sender; [object]$unsubscribeEnabled; [object]$mentionsPreview; [object]$webLink; [object]$isRead; [object]$inferenceClassification; [object]$subject; [object]$uniqueBody; [object]$bccRecipients; [object]$receivedDateTime; [object]$isDeliveryReceiptRequested; [object]$internetMessageId; [object]$toRecipients; [object]$ccRecipients; [object]$conversationIndex; [object]$isDraft; [object]$from; [object]$bodyPreview; [object]$sentDateTime; [object]$hasAttachments; [object]$replyTo; [object]$body; [object]$unsubscribeData; [object]$importance; [object]$parentFolderId; [object]$isReadReceiptRequested; [object]$conversationId; [object]$flag; [object]Get_attachments() { return (Invoke-GraphMethod -Version 'beta' -Query "messages/$($this.Id)/attachments") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "messages/$($this.Id)/extensions") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "messages/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "messages/$($this.Id)/multiValueExtendedProperties") } [object]Get_mentions() { return (Invoke-GraphMethod -Version 'beta' -Query "messages/$($this.Id)/mentions") } } Class microsoft_graph_mailFolder_beta : microsoft_graph_entity_beta { [object]$unreadItemCount; [object]$parentFolderId; [object]$totalItemCount; [object]$wellKnownName; [object]$childFolderCount; [object]$displayName; [object]Get_messages() { return (Invoke-GraphMethod -Version 'beta' -Query "mailFolders/$($this.Id)/messages") } [object]Get_childFolders() { return (Invoke-GraphMethod -Version 'beta' -Query "mailFolders/$($this.Id)/childFolders") } [object]Get_userConfigurations() { return (Invoke-GraphMethod -Version 'beta' -Query "mailFolders/$($this.Id)/userConfigurations") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "mailFolders/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "mailFolders/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_calendarGroup_beta : microsoft_graph_entity_beta { [object]$changeKey; [object]$classId; [object]$name; [object]Get_calendars() { return (Invoke-GraphMethod -Version 'beta' -Query "calendarGroups/$($this.Id)/calendars") } } Class microsoft_graph_person_beta : microsoft_graph_entity_beta { [object]$mailboxType; [object]$sources; [object]$userPrincipalName; [object]$displayName; [object]$personNotes; [object]$companyName; [object]$givenName; [object]$officeLocation; [object]$postalAddresses; [object]$personType; [object]$department; [object]$title; [object]$birthday; [object]$profession; [object]$phones; [object]$emailAddresses; [object]$surname; [object]$websites; [object]$yomiCompany; [object]$isFavorite; } Class microsoft_graph_contact_beta : microsoft_graph_outlookItem_beta { [object]$middleName; [object]$gender; [object]$yomiCompanyName; [object]$generation; [object]$imAddresses; [object]$department; [object]$yomiSurname; [object]$isFavorite; [object]$displayName; [object]$postalAddresses; [object]$jobTitle; [object]$nickName; [object]$birthday; [object]$phones; [object]$fileAs; [object]$givenName; [object]$title; [object]$assistantName; [object]$personalNotes; [object]$profession; [object]$initials; [object]$spouseName; [object]$surname; [object]$manager; [object]$children; [object]$weddingAnniversary; [object]$officeLocation; [object]$parentFolderId; [object]$websites; [object]$companyName; [object]$emailAddresses; [object]$yomiGivenName; [object]$flag; [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "contacts/$($this.Id)/extensions") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "contacts/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "contacts/$($this.Id)/multiValueExtendedProperties") } [object]Get_photo() { return (Invoke-GraphMethod -Version 'beta' -Query "contacts/$($this.Id)/photo") } } Class microsoft_graph_contactFolder_beta : microsoft_graph_entity_beta { [object]$wellKnownName; [object]$displayName; [object]$parentFolderId; [object]Get_contacts() { return (Invoke-GraphMethod -Version 'beta' -Query "contactFolders/$($this.Id)/contacts") } [object]Get_childFolders() { return (Invoke-GraphMethod -Version 'beta' -Query "contactFolders/$($this.Id)/childFolders") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "contactFolders/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "contactFolders/$($this.Id)/multiValueExtendedProperties") } } Class microsoft_graph_inferenceClassification_beta : microsoft_graph_entity_beta { [object]Get_overrides() { return (Invoke-GraphMethod -Version 'beta' -Query "inferenceClassifications/$($this.Id)/overrides") } } Class microsoft_graph_officeGraphInsights_beta : microsoft_graph_entity_beta { [object]Get_trending() { return (Invoke-GraphMethod -Version 'beta' -Query "officeGraphInsightss/$($this.Id)/trending") } } Class microsoft_graph_driveItem_beta : microsoft_graph_entity_beta { [object]$lastModifiedBy; [object]$lastModifiedDateTime; [object]$video; [object]$cTag; [object]$createdDateTime; [object]$content; [object]$folder; [object]$location; [object]$size; [object]$remoteItem; [object]$image; [object]$eTag; [object]$parentReference; [object]$createdBy; [object]$file; [object]$photo; [object]$deleted; [object]$package; [object]$description; [object]$searchResult; [object]$fileSystemInfo; [object]$audio; [object]$webDavUrl; [object]$webUrl; [object]$shared; [object]$root; [object]$specialFolder; [object]$name; [object]$sharepointIds; [object]Get_workbook() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/workbook") } [object]Get_createdByUser() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/createdByUser") } [object]Get_lastModifiedByUser() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/lastModifiedByUser") } [object]Get_children() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/children") } [object]Get_permissions() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/permissions") } [object]Get_thumbnails() { return (Invoke-GraphMethod -Version 'beta' -Query "driveItems/$($this.Id)/thumbnails") } } Class microsoft_graph_task_beta : microsoft_graph_entity_beta { [object]$planId; [object]$assignedTo; [object]$startDateTime; [object]$completedDateTime; [object]$appliedCategories; [object]$dueDateTime; [object]$createdDateTime; [object]$assignedBy; [object]$hasDescription; [object]$assigneePriority; [object]$percentComplete; [object]$title; [object]$bucketId; [object]$orderHint; [object]$assignedDateTime; [object]$previewType; [object]$conversationThreadId; [object]$createdBy; [object]Get_details() { return (Invoke-GraphMethod -Version 'beta' -Query "tasks/$($this.Id)/details") } [object]Get_assignedToTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "tasks/$($this.Id)/assignedToTaskBoardFormat") } [object]Get_progressTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "tasks/$($this.Id)/progressTaskBoardFormat") } [object]Get_bucketTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "tasks/$($this.Id)/bucketTaskBoardFormat") } } Class microsoft_graph_plannerUser_beta : microsoft_graph_entity_beta { [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerUsers/$($this.Id)/tasks") } [object]Get_plans() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerUsers/$($this.Id)/plans") } } Class microsoft_graph_managedDevice_beta : microsoft_graph_entity_beta { [object]$aadRegistered; [object]$deviceCategoryDisplayName; [object]$userId; [object]$lastSyncDateTime; [object]$exchangeAccessStateReason; [object]$managementAgent; [object]$complianceState; [object]$osVersion; [object]$enrollmentType; [object]$deviceRegistrationState; [object]$hardwareInformation; [object]$emailAddress; [object]$enrolledDateTime; [object]$activationLockBypassCode; [object]$isSupervised; [object]$managementAgents; [object]$azureActiveDirectoryDeviceId; [object]$operatingSystem; [object]$easActivated; [object]$chassisType; [object]$easDeviceId; [object]$managementState; [object]$lostModeState; [object]$deviceName; [object]$deviceType; [object]$easActivationDateTime; [object]$exchangeLastSuccessfulSyncDateTime; [object]$ownerType; [object]$deviceActionResults; [object]$exchangeAccessState; [object]$jailBroken; [object]Get_deviceConfigurationStates() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDevices/$($this.Id)/deviceConfigurationStates") } [object]Get_detectedApps() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDevices/$($this.Id)/detectedApps") } [object]Get_deviceCategory() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDevices/$($this.Id)/deviceCategory") } [object]Get_deviceCompliancePolicyStates() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDevices/$($this.Id)/deviceCompliancePolicyStates") } } Class microsoft_graph_managedAppRegistration_beta : microsoft_graph_entity_beta { [object]$lastSyncDateTime; [object]$managementSdkVersion; [object]$deviceTag; [object]$platformVersion; [object]$version; [object]$deviceName; [object]$createdDateTime; [object]$userId; [object]$deviceType; [object]$applicationVersion; [object]$flaggedReasons; [object]$appIdentifier; [object]Get_appliedPolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "managedAppRegistrations/$($this.Id)/appliedPolicies") } [object]Get_intendedPolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "managedAppRegistrations/$($this.Id)/intendedPolicies") } [object]Get_operations() { return (Invoke-GraphMethod -Version 'beta' -Query "managedAppRegistrations/$($this.Id)/operations") } } Class microsoft_graph_administrativeUnit_beta : microsoft_graph_directoryObject_beta { [object]$description; [object]$displayName; [object]$visibility; [object]Get_members() { return (Invoke-GraphMethod -Version 'beta' -Query "administrativeUnits/$($this.Id)/members") } [object]Get_scopedAdministrators() { return (Invoke-GraphMethod -Version 'beta' -Query "administrativeUnits/$($this.Id)/scopedAdministrators") } [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "administrativeUnits/$($this.Id)/extensions") } } Class microsoft_graph_contract_beta : microsoft_graph_directoryObject_beta { [object]$contractType; [object]$customerId; [object]$displayName; [object]$defaultDomainName; } Class microsoft_graph_schemaExtension_beta : microsoft_graph_entity_beta { [object]$targetTypes; [object]$description; [object]$status; [object]$properties; [object]$owner; } Class microsoft_graph_baseItem_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$description; [object]$createdBy; [object]$lastModifiedBy; [object]$eTag; [object]$name; [object]$createdDateTime; [object]$webUrl; [object]Get_createdByUser() { return (Invoke-GraphMethod -Version 'beta' -Query "baseItems/$($this.Id)/createdByUser") } [object]Get_lastModifiedByUser() { return (Invoke-GraphMethod -Version 'beta' -Query "baseItems/$($this.Id)/lastModifiedByUser") } } Class microsoft_graph_site_beta : microsoft_graph_baseItem_beta { [object]$root; [object]$siteId; [object]$siteCollection; [object]$siteCollectionId; [object]Get_drive() { return (Invoke-GraphMethod -Version 'beta' -Query "sites/$($this.Id)/drive") } [object]Get_drives() { return (Invoke-GraphMethod -Version 'beta' -Query "sites/$($this.Id)/drives") } [object]Get_items() { return (Invoke-GraphMethod -Version 'beta' -Query "sites/$($this.Id)/items") } [object]Get_lists() { return (Invoke-GraphMethod -Version 'beta' -Query "sites/$($this.Id)/lists") } [object]Get_sites() { return (Invoke-GraphMethod -Version 'beta' -Query "sites/$($this.Id)/sites") } } Class microsoft_graph_list_beta : microsoft_graph_baseItem_beta { [object]$fields; [object]$list; [object]Get_drive() { return (Invoke-GraphMethod -Version 'beta' -Query "lists/$($this.Id)/drive") } [object]Get_items() { return (Invoke-GraphMethod -Version 'beta' -Query "lists/$($this.Id)/items") } } Class microsoft_graph_listItem_beta : microsoft_graph_baseItem_beta { [object]$listItemId; [object]Get_columnSet() { return (Invoke-GraphMethod -Version 'beta' -Query "listItems/$($this.Id)/columnSet") } [object]Get_driveItem() { return (Invoke-GraphMethod -Version 'beta' -Query "listItems/$($this.Id)/driveItem") } } Class microsoft_graph_workbook_beta : microsoft_graph_entity_beta { [object]Get_application() { return (Invoke-GraphMethod -Version 'beta' -Query "workbooks/$($this.Id)/application") } [object]Get_names() { return (Invoke-GraphMethod -Version 'beta' -Query "workbooks/$($this.Id)/names") } [object]Get_tables() { return (Invoke-GraphMethod -Version 'beta' -Query "workbooks/$($this.Id)/tables") } [object]Get_worksheets() { return (Invoke-GraphMethod -Version 'beta' -Query "workbooks/$($this.Id)/worksheets") } [object]Get_functions() { return (Invoke-GraphMethod -Version 'beta' -Query "workbooks/$($this.Id)/functions") } } Class microsoft_graph_permission_beta : microsoft_graph_entity_beta { [object]$link; [object]$roles; [object]$shareId; [object]$inheritedFrom; [object]$grantedTo; [object]$invitation; } Class microsoft_graph_thumbnailSet_beta : microsoft_graph_entity_beta { [object]$source; [object]$large; [object]$small; [object]$medium; } Class microsoft_graph_workbookApplication_beta : microsoft_graph_entity_beta { [object]$calculationMode; } Class microsoft_graph_workbookNamedItem_beta : microsoft_graph_entity_beta { [object]$comment; [object]$type; [object]$visible; [object]$value; [object]$name; [object]$scope; [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookNamedItems/$($this.Id)/worksheet") } } Class microsoft_graph_workbookTable_beta : microsoft_graph_entity_beta { [object]$showBandedColumns; [object]$showTotals; [object]$showBandedRows; [object]$showFilterButton; [object]$name; [object]$showHeaders; [object]$highlightFirstColumn; [object]$style; [object]$highlightLastColumn; [object]Get_columns() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookTables/$($this.Id)/columns") } [object]Get_rows() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookTables/$($this.Id)/rows") } [object]Get_sort() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookTables/$($this.Id)/sort") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookTables/$($this.Id)/worksheet") } } Class microsoft_graph_workbookWorksheet_beta : microsoft_graph_entity_beta { [object]$position; [object]$visibility; [object]$name; [object]Get_charts() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookWorksheets/$($this.Id)/charts") } [object]Get_names() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookWorksheets/$($this.Id)/names") } [object]Get_pivotTables() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookWorksheets/$($this.Id)/pivotTables") } [object]Get_protection() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookWorksheets/$($this.Id)/protection") } [object]Get_tables() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookWorksheets/$($this.Id)/tables") } } Class microsoft_graph_workbookFunctions_beta : microsoft_graph_entity_beta { } Class microsoft_graph_workbookChart_beta : microsoft_graph_entity_beta { [object]$left; [object]$width; [object]$name; [object]$height; [object]$top; [object]Get_axes() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/axes") } [object]Get_dataLabels() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/dataLabels") } [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/format") } [object]Get_legend() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/legend") } [object]Get_series() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/series") } [object]Get_title() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/title") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookCharts/$($this.Id)/worksheet") } } Class microsoft_graph_workbookChartAxes_beta : microsoft_graph_entity_beta { [object]Get_categoryAxis() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxess/$($this.Id)/categoryAxis") } [object]Get_seriesAxis() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxess/$($this.Id)/seriesAxis") } [object]Get_valueAxis() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxess/$($this.Id)/valueAxis") } } Class microsoft_graph_workbookChartDataLabels_beta : microsoft_graph_entity_beta { [object]$position; [object]$showLegendKey; [object]$showSeriesName; [object]$showPercentage; [object]$separator; [object]$showBubbleSize; [object]$showValue; [object]$showCategoryName; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartDataLabelss/$($this.Id)/format") } } Class microsoft_graph_workbookChartAreaFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAreaFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAreaFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartLegend_beta : microsoft_graph_entity_beta { [object]$position; [object]$overlay; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartLegends/$($this.Id)/format") } } Class microsoft_graph_workbookChartSeries_beta : microsoft_graph_entity_beta { [object]$name; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartSeriess/$($this.Id)/format") } [object]Get_points() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartSeriess/$($this.Id)/points") } } Class microsoft_graph_workbookChartTitle_beta : microsoft_graph_entity_beta { [object]$overlay; [object]$text; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartTitles/$($this.Id)/format") } } Class microsoft_graph_workbookChartFill_beta : microsoft_graph_entity_beta { } Class microsoft_graph_workbookChartFont_beta : microsoft_graph_entity_beta { [object]$underline; [object]$italic; [object]$color; [object]$name; [object]$size; [object]$bold; } Class microsoft_graph_workbookChartAxis_beta : microsoft_graph_entity_beta { [object]$minimum; [object]$majorUnit; [object]$minorUnit; [object]$maximum; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxiss/$($this.Id)/format") } [object]Get_majorGridlines() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxiss/$($this.Id)/majorGridlines") } [object]Get_minorGridlines() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxiss/$($this.Id)/minorGridlines") } [object]Get_title() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxiss/$($this.Id)/title") } } Class microsoft_graph_workbookChartAxisFormat_beta : microsoft_graph_entity_beta { [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxisFormats/$($this.Id)/font") } [object]Get_line() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxisFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartGridlines_beta : microsoft_graph_entity_beta { [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartGridliness/$($this.Id)/format") } } Class microsoft_graph_workbookChartAxisTitle_beta : microsoft_graph_entity_beta { [object]$text; [object]$visible; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxisTitles/$($this.Id)/format") } } Class microsoft_graph_workbookChartLineFormat_beta : microsoft_graph_entity_beta { [object]$color; } Class microsoft_graph_workbookChartAxisTitleFormat_beta : microsoft_graph_entity_beta { [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartAxisTitleFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartDataLabelFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartDataLabelFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartDataLabelFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartGridlinesFormat_beta : microsoft_graph_entity_beta { [object]Get_line() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartGridlinesFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartLegendFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartLegendFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartLegendFormats/$($this.Id)/font") } } Class microsoft_graph_workbookChartPoint_beta : microsoft_graph_entity_beta { [object]$value; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartPoints/$($this.Id)/format") } } Class microsoft_graph_workbookChartPointFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartPointFormats/$($this.Id)/fill") } } Class microsoft_graph_workbookChartSeriesFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartSeriesFormats/$($this.Id)/fill") } [object]Get_line() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartSeriesFormats/$($this.Id)/line") } } Class microsoft_graph_workbookChartTitleFormat_beta : microsoft_graph_entity_beta { [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartTitleFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookChartTitleFormats/$($this.Id)/font") } } Class microsoft_graph_workbookFilter_beta : microsoft_graph_entity_beta { [object]$criteria; } Class microsoft_graph_workbookFormatProtection_beta : microsoft_graph_entity_beta { [object]$formulaHidden; [object]$locked; } Class microsoft_graph_workbookFunctionResult_beta : microsoft_graph_entity_beta { [object]$error; [object]$value; } Class microsoft_graph_workbookPivotTable_beta : microsoft_graph_entity_beta { [object]$name; [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookPivotTables/$($this.Id)/worksheet") } } Class microsoft_graph_workbookRange_beta : microsoft_graph_entity_beta { [object]$cellCount; [object]$columnHidden; [object]$addressLocal; [object]$rowIndex; [object]$rowHidden; [object]$valueTypes; [object]$values; [object]$hidden; [object]$formulasR1C1; [object]$address; [object]$columnIndex; [object]$formulas; [object]$numberFormat; [object]$formulasLocal; [object]$columnCount; [object]$text; [object]$rowCount; [object]Get_format() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRanges/$($this.Id)/format") } [object]Get_sort() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRanges/$($this.Id)/sort") } [object]Get_worksheet() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRanges/$($this.Id)/worksheet") } } Class microsoft_graph_workbookRangeFormat_beta : microsoft_graph_entity_beta { [object]$verticalAlignment; [object]$horizontalAlignment; [object]$columnWidth; [object]$rowHeight; [object]$wrapText; [object]Get_borders() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRangeFormats/$($this.Id)/borders") } [object]Get_fill() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRangeFormats/$($this.Id)/fill") } [object]Get_font() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRangeFormats/$($this.Id)/font") } [object]Get_protection() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRangeFormats/$($this.Id)/protection") } } Class microsoft_graph_workbookRangeSort_beta : microsoft_graph_entity_beta { } Class microsoft_graph_workbookRangeBorder_beta : microsoft_graph_entity_beta { [object]$sideIndex; [object]$color; [object]$style; [object]$weight; } Class microsoft_graph_workbookRangeFill_beta : microsoft_graph_entity_beta { [object]$color; } Class microsoft_graph_workbookRangeFont_beta : microsoft_graph_entity_beta { [object]$underline; [object]$italic; [object]$color; [object]$name; [object]$size; [object]$bold; } Class microsoft_graph_workbookRangeView_beta : microsoft_graph_entity_beta { [object]$numberFormat; [object]$text; [object]$cellAddresses; [object]$formulas; [object]$formulasLocal; [object]$rowCount; [object]$index; [object]$values; [object]$valueTypes; [object]$formulasR1C1; [object]$columnCount; [object]Get_rows() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookRangeViews/$($this.Id)/rows") } } Class microsoft_graph_workbookTableColumn_beta : microsoft_graph_entity_beta { [object]$values; [object]$name; [object]$index; [object]Get_filter() { return (Invoke-GraphMethod -Version 'beta' -Query "workbookTableColumns/$($this.Id)/filter") } } Class microsoft_graph_workbookTableRow_beta : microsoft_graph_entity_beta { [object]$values; [object]$index; } Class microsoft_graph_workbookTableSort_beta : microsoft_graph_entity_beta { [object]$method; [object]$fields; [object]$matchCase; } Class microsoft_graph_workbookWorksheetProtection_beta : microsoft_graph_entity_beta { [object]$options; [object]$protected; } Class microsoft_graph_attachment_beta : microsoft_graph_entity_beta { [object]$contentType; [object]$lastModifiedDateTime; [object]$isInline; [object]$name; [object]$size; } Class microsoft_graph_userConfiguration_beta : microsoft_graph_entity_beta { [object]$binaryData; } Class microsoft_graph_singleValueLegacyExtendedProperty_beta : microsoft_graph_entity_beta { [object]$value; } Class microsoft_graph_multiValueLegacyExtendedProperty_beta : microsoft_graph_entity_beta { [object]$value; } Class microsoft_graph_mention_beta : microsoft_graph_entity_beta { [object]$createdBy; [object]$mentionText; [object]$createdDateTime; [object]$deepLink; [object]$clientReference; [object]$application; [object]$serverCreatedDateTime; [object]$mentioned; } Class microsoft_graph_fileAttachment_beta : microsoft_graph_attachment_beta { [object]$contentId; [object]$contentLocation; [object]$contentBytes; } Class microsoft_graph_itemAttachment_beta : microsoft_graph_attachment_beta { [object]Get_item() { return (Invoke-GraphMethod -Version 'beta' -Query "itemAttachments/$($this.Id)/item") } } Class microsoft_graph_eventMessage_beta : microsoft_graph_message_beta { [object]$startDateTime; [object]$type; [object]$isOutOfDate; [object]$recurrence; [object]$meetingMessageType; [object]$endDateTime; [object]$location; [object]$isAllDay; [object]Get_event() { return (Invoke-GraphMethod -Version 'beta' -Query "eventMessages/$($this.Id)/event") } } Class microsoft_graph_eventMessageRequest_beta : microsoft_graph_eventMessage_beta { [object]$previousEndDateTime; [object]$previousStartDateTime; [object]$responseRequested; [object]$previousLocation; } Class microsoft_graph_referenceAttachment_beta : microsoft_graph_attachment_beta { [object]$thumbnailUrl; [object]$permission; [object]$providerType; [object]$sourceUrl; [object]$isFolder; [object]$previewUrl; } Class microsoft_graph_openTypeExtension_beta : microsoft_graph_extension_beta { [object]$extensionName; } Class microsoft_graph_post_beta : microsoft_graph_outlookItem_beta { [object]$hasAttachments; [object]$receivedDateTime; [object]$conversationThreadId; [object]$sender; [object]$newParticipants; [object]$body; [object]$from; [object]$conversationId; [object]Get_extensions() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/extensions") } [object]Get_inReplyTo() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/inReplyTo") } [object]Get_attachments() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/attachments") } [object]Get_singleValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/singleValueExtendedProperties") } [object]Get_multiValueExtendedProperties() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/multiValueExtendedProperties") } [object]Get_mentions() { return (Invoke-GraphMethod -Version 'beta' -Query "posts/$($this.Id)/mentions") } } Class microsoft_graph_inferenceClassificationOverride_beta : microsoft_graph_entity_beta { [object]$senderEmailAddress; [object]$classifyAs; } Class microsoft_graph_sharedDriveItem_beta : microsoft_graph_entity_beta { [object]$name; [object]$owner; [object]Get_root() { return (Invoke-GraphMethod -Version 'beta' -Query "sharedDriveItems/$($this.Id)/root") } [object]Get_items() { return (Invoke-GraphMethod -Version 'beta' -Query "sharedDriveItems/$($this.Id)/items") } } Class microsoft_graph_fieldValueSet_beta : microsoft_graph_entity_beta { } Class microsoft_graph_trending_beta : microsoft_graph_entity_beta { [object]$resourceReference; [object]$weight; [object]$resourceVisualization; [object]$lastModifiedDateTime; [object]Get_resource() { return (Invoke-GraphMethod -Version 'beta' -Query "trendings/$($this.Id)/resource") } } Class microsoft_graph_plannerTask_beta : microsoft_graph_entity_beta { [object]$planId; [object]$startDateTime; [object]$activeChecklistItemCount; [object]$bucketId; [object]$completedDateTime; [object]$appliedCategories; [object]$createdDateTime; [object]$hasDescription; [object]$assigneePriority; [object]$percentComplete; [object]$title; [object]$dueDateTime; [object]$completedBy; [object]$referenceCount; [object]$orderHint; [object]$assignments; [object]$previewType; [object]$checklistItemCount; [object]$conversationThreadId; [object]$createdBy; [object]Get_details() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerTasks/$($this.Id)/details") } [object]Get_assignedToTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerTasks/$($this.Id)/assignedToTaskBoardFormat") } [object]Get_progressTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerTasks/$($this.Id)/progressTaskBoardFormat") } [object]Get_bucketTaskBoardFormat() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerTasks/$($this.Id)/bucketTaskBoardFormat") } } Class microsoft_graph_plannerPlan_beta : microsoft_graph_entity_beta { [object]$createdBy; [object]$title; [object]$createdDateTime; [object]$owner; [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerPlans/$($this.Id)/tasks") } [object]Get_buckets() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerPlans/$($this.Id)/buckets") } [object]Get_details() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerPlans/$($this.Id)/details") } } Class microsoft_graph_planner_beta : microsoft_graph_entity_beta { [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "planners/$($this.Id)/tasks") } [object]Get_plans() { return (Invoke-GraphMethod -Version 'beta' -Query "planners/$($this.Id)/plans") } [object]Get_buckets() { return (Invoke-GraphMethod -Version 'beta' -Query "planners/$($this.Id)/buckets") } } Class microsoft_graph_plannerBucket_beta : microsoft_graph_entity_beta { [object]$orderHint; [object]$name; [object]$planId; [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "plannerBuckets/$($this.Id)/tasks") } } Class microsoft_graph_plannerTaskDetails_beta : microsoft_graph_entity_beta { [object]$checklist; [object]$description; [object]$previewType; [object]$references; } Class microsoft_graph_plannerAssignedToTaskBoardTaskFormat_beta : microsoft_graph_entity_beta { [object]$unassignedOrderHint; [object]$orderHintsByAssignee; } Class microsoft_graph_plannerProgressTaskBoardTaskFormat_beta : microsoft_graph_entity_beta { [object]$orderHint; } Class microsoft_graph_plannerBucketTaskBoardTaskFormat_beta : microsoft_graph_entity_beta { [object]$orderHint; } Class microsoft_graph_plannerPlanDetails_beta : microsoft_graph_entity_beta { [object]$sharedWith; [object]$categoryDescriptions; } Class microsoft_graph_taskDetails_beta : microsoft_graph_entity_beta { [object]$checklist; [object]$description; [object]$completedBy; [object]$previewType; [object]$references; } Class microsoft_graph_taskBoardTaskFormat_beta : microsoft_graph_entity_beta { [object]$orderHint; [object]$type; } Class microsoft_graph_bucket_beta : microsoft_graph_entity_beta { [object]$orderHint; [object]$name; [object]$planId; [object]Get_tasks() { return (Invoke-GraphMethod -Version 'beta' -Query "buckets/$($this.Id)/tasks") } } Class microsoft_graph_planDetails_beta : microsoft_graph_entity_beta { [object]$category3Description; [object]$category2Description; [object]$category4Description; [object]$category5Description; [object]$category0Description; [object]$category1Description; [object]$sharedWith; } Class microsoft_graph_planTaskBoard_beta : microsoft_graph_entity_beta { [object]$type; } Class microsoft_graph_notebook_beta : microsoft_graph_entity_beta { [object]$lastModifiedTime; [object]$createdTime; [object]$name; [object]$lastModifiedBy; [object]$lastModifiedByIdentity; [object]$createdBy; [object]$self; [object]$sectionGroupsUrl; [object]$userRole; [object]$createdByIdentity; [object]$sectionsUrl; [object]$links; [object]$isShared; [object]$isDefault; [object]Get_sections() { return (Invoke-GraphMethod -Version 'beta' -Query "notebooks/$($this.Id)/sections") } [object]Get_sectionGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "notebooks/$($this.Id)/sectionGroups") } } Class microsoft_graph_section_beta : microsoft_graph_entity_beta { [object]$createdBy; [object]$lastModifiedByIdentity; [object]$lastModifiedBy; [object]$lastModifiedTime; [object]$createdByIdentity; [object]$name; [object]$pagesUrl; [object]$self; [object]$isDefault; [object]$createdTime; [object]Get_parentNotebook() { return (Invoke-GraphMethod -Version 'beta' -Query "sections/$($this.Id)/parentNotebook") } [object]Get_parentSectionGroup() { return (Invoke-GraphMethod -Version 'beta' -Query "sections/$($this.Id)/parentSectionGroup") } [object]Get_pages() { return (Invoke-GraphMethod -Version 'beta' -Query "sections/$($this.Id)/pages") } } Class microsoft_graph_sectionGroup_beta : microsoft_graph_entity_beta { [object]$createdBy; [object]$lastModifiedByIdentity; [object]$sectionGroupsUrl; [object]$sectionsUrl; [object]$createdByIdentity; [object]$name; [object]$lastModifiedBy; [object]$self; [object]$createdTime; [object]$lastModifiedTime; [object]Get_parentNotebook() { return (Invoke-GraphMethod -Version 'beta' -Query "sectionGroups/$($this.Id)/parentNotebook") } [object]Get_parentSectionGroup() { return (Invoke-GraphMethod -Version 'beta' -Query "sectionGroups/$($this.Id)/parentSectionGroup") } [object]Get_sections() { return (Invoke-GraphMethod -Version 'beta' -Query "sectionGroups/$($this.Id)/sections") } [object]Get_sectionGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "sectionGroups/$($this.Id)/sectionGroups") } } Class microsoft_graph_page_beta : microsoft_graph_entity_beta { [object]$contentUrl; [object]$level; [object]$createdByAppId; [object]$self; [object]$content; [object]$lastModifiedTime; [object]$createdTime; [object]$links; [object]$order; [object]$title; [object]Get_parentSection() { return (Invoke-GraphMethod -Version 'beta' -Query "pages/$($this.Id)/parentSection") } [object]Get_parentNotebook() { return (Invoke-GraphMethod -Version 'beta' -Query "pages/$($this.Id)/parentNotebook") } } Class microsoft_graph_resource_beta : microsoft_graph_entity_beta { [object]$contentUrl; [object]$content; [object]$self; } Class microsoft_graph_notesOperation_beta : microsoft_graph_entity_beta { [object]$resourceId; [object]$error; [object]$createdDateTime; [object]$status; [object]$resourceLocation; [object]$lastActionDateTime; } Class microsoft_graph_subscription_beta : microsoft_graph_entity_beta { [object]$clientState; [object]$resource; [object]$changeType; [object]$expirationDateTime; [object]$notificationUrl; } Class microsoft_graph_identityRiskEvent_beta : microsoft_graph_entity_beta { [object]$userDisplayName; [object]$riskEventDateTime; [object]$userPrincipalName; [object]$riskLevel; [object]$riskEventStatus; [object]$userId; [object]$riskEventType; [object]$closedDateTime; [object]$createdDateTime; [object]Get_impactedUser() { return (Invoke-GraphMethod -Version 'beta' -Query "identityRiskEvents/$($this.Id)/impactedUser") } } Class microsoft_graph_locatedRiskEvent_beta : microsoft_graph_identityRiskEvent_beta { [object]$ipAddress; [object]$location; } Class microsoft_graph_impossibleTravelRiskEvent_beta : microsoft_graph_locatedRiskEvent_beta { [object]$previousLocation; [object]$userAgent; [object]$isAtypicalLocation; [object]$previousIpAddress; [object]$previousSigninDateTime; [object]$deviceInformation; } Class microsoft_graph_leakedCredentialsRiskEvent_beta : microsoft_graph_identityRiskEvent_beta { } Class microsoft_graph_anonymousIpRiskEvent_beta : microsoft_graph_locatedRiskEvent_beta { } Class microsoft_graph_suspiciousIpRiskEvent_beta : microsoft_graph_locatedRiskEvent_beta { } Class microsoft_graph_unfamiliarLocationRiskEvent_beta : microsoft_graph_locatedRiskEvent_beta { } Class microsoft_graph_malwareRiskEvent_beta : microsoft_graph_locatedRiskEvent_beta { [object]$deviceInformation; [object]$malwareName; } Class microsoft_graph_privilegedRole_beta : microsoft_graph_entity_beta { [object]$name; [object]Get_settings() { return (Invoke-GraphMethod -Version 'beta' -Query "privilegedRoles/$($this.Id)/settings") } [object]Get_assignments() { return (Invoke-GraphMethod -Version 'beta' -Query "privilegedRoles/$($this.Id)/assignments") } [object]Get_summary() { return (Invoke-GraphMethod -Version 'beta' -Query "privilegedRoles/$($this.Id)/summary") } } Class microsoft_graph_privilegedRoleSettings_beta : microsoft_graph_entity_beta { [object]$ticketingInfoOnElevation; [object]$isMfaOnElevationConfigurable; [object]$maxElavationDuration; [object]$lastGlobalAdmin; [object]$notificationToUserOnElevation; [object]$minElevationDuration; [object]$mfaOnElevation; [object]$elevationDuration; } Class microsoft_graph_privilegedRoleAssignment_beta : microsoft_graph_entity_beta { [object]$isElevated; [object]$resultMessage; [object]$userId; [object]$expirationDateTime; [object]$roleId; [object]Get_roleInfo() { return (Invoke-GraphMethod -Version 'beta' -Query "privilegedRoleAssignments/$($this.Id)/roleInfo") } } Class microsoft_graph_privilegedRoleSummary_beta : microsoft_graph_entity_beta { [object]$status; [object]$usersCount; [object]$mfaEnabled; [object]$elevatedCount; [object]$managedCount; } Class microsoft_graph_privilegedOperationEvent_beta : microsoft_graph_entity_beta { [object]$requestorName; [object]$tenantId; [object]$additionalInformation; [object]$requestorId; [object]$creationDateTime; [object]$userName; [object]$referenceSystem; [object]$userId; [object]$requestType; [object]$referenceKey; [object]$expirationDateTime; [object]$roleName; [object]$roleId; [object]$userMail; } Class microsoft_graph_privilegedSignupStatus_beta : microsoft_graph_entity_beta { [object]$isRegistered; [object]$status; } Class microsoft_graph_tenantSetupInfo_beta : microsoft_graph_entity_beta { [object]$relevantRolesSettings; [object]$skipSetup; [object]$userRolesActions; [object]$firstTimeSetup; [object]$setupStatus; [object]Get_defaultRolesSettings() { return (Invoke-GraphMethod -Version 'beta' -Query "tenantSetupInfos/$($this.Id)/defaultRolesSettings") } } Class microsoft_graph_connector_beta : microsoft_graph_entity_beta { [object]$status; [object]$machineName; [object]$externalIp; [object]Get_memberOf() { return (Invoke-GraphMethod -Version 'beta' -Query "connectors/$($this.Id)/memberOf") } } Class microsoft_graph_invitation_beta : microsoft_graph_entity_beta { [object]$invitedUserMessageInfo; [object]$invitedUserType; [object]$sendInvitationMessage; [object]$invitedUserEmailAddress; [object]$inviteRedeemUrl; [object]$invitedUserDisplayName; [object]$status; [object]$inviteRedirectUrl; [object]Get_invitedUser() { return (Invoke-GraphMethod -Version 'beta' -Query "invitations/$($this.Id)/invitedUser") } } Class microsoft_graph_deviceManagement_beta : microsoft_graph_entity_beta { [object]$subscriptionState; [object]$settings; [object]Get_termsAndConditions() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/termsAndConditions") } [object]Get_androidForWorkSettings() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/androidForWorkSettings") } [object]Get_androidForWorkAppConfigurationSchemas() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/androidForWorkAppConfigurationSchemas") } [object]Get_enrollmentProfiles() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/enrollmentProfiles") } [object]Get_importedDeviceIdentities() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/importedDeviceIdentities") } [object]Get_importedAppleDeviceIdentities() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/importedAppleDeviceIdentities") } [object]Get_remoteActionAudits() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/remoteActionAudits") } [object]Get_applePushNotificationCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/applePushNotificationCertificate") } [object]Get_deviceConfigurations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/deviceConfigurations") } [object]Get_deviceCompliancePolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/deviceCompliancePolicies") } [object]Get_softwareUpdateStatusSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/softwareUpdateStatusSummary") } [object]Get_deviceCompliancePolicyDeviceStateSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/deviceCompliancePolicyDeviceStateSummary") } [object]Get_complianceSettingStateSummaries() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/complianceSettingStateSummaries") } [object]Get_deviceConfigurationDeviceStateSummaries() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/deviceConfigurationDeviceStateSummaries") } [object]Get_deviceCategories() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/deviceCategories") } [object]Get_exchangeConnectors() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/exchangeConnectors") } [object]Get_exchangeOnPremisesPolicy() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/exchangeOnPremisesPolicy") } [object]Get_mobileThreatDefenseConnectors() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/mobileThreatDefenseConnectors") } [object]Get_notificationMessageTemplates() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/notificationMessageTemplates") } [object]Get_roleDefinitions() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/roleDefinitions") } [object]Get_roleAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/roleAssignments") } [object]Get_resourceOperations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/resourceOperations") } [object]Get_telecomExpenseManagementPartners() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagements/$($this.Id)/telecomExpenseManagementPartners") } } Class microsoft_graph_termsAndConditions_beta : microsoft_graph_entity_beta { [object]$description; [object]$acceptanceStatement; [object]$modifiedDateTime; [object]$createdDateTime; [object]$bodyText; [object]$version; [object]$title; [object]$displayName; [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "termsAndConditionss/$($this.Id)/groupAssignments") } [object]Get_acceptanceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "termsAndConditionss/$($this.Id)/acceptanceStatuses") } } Class microsoft_graph_androidForWorkSettings_beta : microsoft_graph_entity_beta { [object]$lastAppSyncStatus; [object]$bindStatus; [object]$targetGroupIds; [object]$lastAppSyncDateTime; [object]$ownerOrganizationName; [object]$lastModifiedDateTime; [object]$enrollmentTarget; [object]$ownerUserPrincipalName; } Class microsoft_graph_androidForWorkAppConfigurationSchema_beta : microsoft_graph_entity_beta { [object]$exampleJson; [object]$schemaItems; } Class microsoft_graph_enrollmentProfile_beta : microsoft_graph_entity_beta { [object]$description; [object]$displayName; [object]$configurationEndpointUrl; [object]$requiresUserAuthentication; } Class microsoft_graph_importedDeviceIdentity_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$importedDeviceIdentifier; [object]$description; [object]$platform; [object]$lastContactedDateTime; [object]$enrollmentState; [object]$createdDateTime; [object]$importedDeviceIdentityType; } Class microsoft_graph_importedAppleDeviceIdentity_beta : microsoft_graph_entity_beta { [object]$requestedEnrollmentProfileId; [object]$description; [object]$isSupervised; [object]$discoverySource; [object]$lastContactedDateTime; [object]$serialNumber; [object]$requestedEnrollmentProfileAssignmentDateTime; [object]$createdDateTime; [object]$platform; [object]$enrollmentState; } Class microsoft_graph_remoteActionAudit_beta : microsoft_graph_entity_beta { [object]$action; [object]$userName; [object]$deviceDisplayName; [object]$initiatedByUserPrincipalName; [object]$deviceOwnerUserPrincipalName; [object]$requestDateTime; [object]$actionState; [object]$deviceIMEI; } Class microsoft_graph_applePushNotificationCertificate_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$certificateUploadStatus; [object]$topicIdentifier; [object]$certificate; [object]$expirationDateTime; [object]$appleIdentifier; [object]$certificateUploadFailureReason; } Class microsoft_graph_deviceConfiguration_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$description; [object]$createdDateTime; [object]$version; [object]$displayName; [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/groupAssignments") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/deviceStatuses") } [object]Get_userStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/userStatuses") } [object]Get_deviceStatusOverview() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/deviceStatusOverview") } [object]Get_userStatusOverview() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/userStatusOverview") } [object]Get_deviceSettingStateSummaries() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurations/$($this.Id)/deviceSettingStateSummaries") } } Class microsoft_graph_deviceCompliancePolicy_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$description; [object]$createdDateTime; [object]$version; [object]$displayName; [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/groupAssignments") } [object]Get_scheduledActionsForRule() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/scheduledActionsForRule") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/deviceStatuses") } [object]Get_userStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/userStatuses") } [object]Get_deviceStatusOverview() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/deviceStatusOverview") } [object]Get_userStatusOverview() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/userStatusOverview") } [object]Get_deviceSettingStateSummaries() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicys/$($this.Id)/deviceSettingStateSummaries") } } Class microsoft_graph_softwareUpdateStatusSummary_beta : microsoft_graph_entity_beta { [object]$conflictDeviceCount; [object]$notApplicableDeviceCount; [object]$remediatedDeviceCount; [object]$errorDeviceCount; [object]$compliantDeviceCount; [object]$unknownDeviceCount; [object]$nonCompliantDeviceCount; [object]$displayName; } Class microsoft_graph_deviceCompliancePolicyDeviceStateSummary_beta : microsoft_graph_entity_beta { [object]$conflictDeviceCount; [object]$notApplicableDeviceCount; [object]$remediatedDeviceCount; [object]$errorDeviceCount; [object]$compliantDeviceCount; [object]$unknownDeviceCount; [object]$nonCompliantDeviceCount; } Class microsoft_graph_complianceSettingStateSummary_beta : microsoft_graph_entity_beta { [object]$settingPlatform; [object]$notApplicableDeviceCount; [object]$instanceDisplayName; [object]$conflictDeviceCount; [object]$remediatedDeviceCount; [object]$settingName; [object]$compliantDeviceCount; [object]$unknownDeviceCount; [object]$nonCompliantDeviceCount; [object]$errorDeviceCount; } Class microsoft_graph_deviceConfigurationDeviceStateSummary_beta : microsoft_graph_entity_beta { [object]$conflictDeviceCount; [object]$notApplicableDeviceCount; [object]$remediatedDeviceCount; [object]$errorDeviceCount; [object]$compliantDeviceCount; [object]$unknownDeviceCount; [object]$nonCompliantDeviceCount; } Class microsoft_graph_deviceCategory_beta : microsoft_graph_entity_beta { [object]$displayName; [object]$description; } Class microsoft_graph_deviceManagementExchangeConnector_beta : microsoft_graph_entity_beta { [object]$exchangeConnectorType; [object]$status; [object]$serverName; [object]$primarySmtpAddress; [object]$lastSyncDateTime; } Class microsoft_graph_deviceManagementExchangeOnPremisesPolicy_beta : microsoft_graph_entity_beta { [object]$knownDeviceClasses; [object]$accessRules; [object]$notificationContent; [object]$defaultAccessLevel; [object]Get_conditionalAccessSettings() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceManagementExchangeOnPremisesPolicys/$($this.Id)/conditionalAccessSettings") } } Class microsoft_graph_mobileThreatDefenseConnector_beta : microsoft_graph_entity_beta { [object]$androidEnabled; [object]$partnerUnresponsivenessThresholdInDays; [object]$partnerUnsupportedOsVersionBlocked; [object]$partnerState; [object]$iosEnabled; [object]$iosDeviceBlockedOnMissingPartnerData; [object]$lastHeartbeatDateTime; [object]$androidDeviceBlockedOnMissingPartnerData; } Class microsoft_graph_notificationMessageTemplate_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$brandingOptions; [object]$displayName; [object]$fromEmailAddress; [object]$defaultLocale; [object]Get_localizedNotificationMessages() { return (Invoke-GraphMethod -Version 'beta' -Query "notificationMessageTemplates/$($this.Id)/localizedNotificationMessages") } } Class microsoft_graph_roleDefinition_beta : microsoft_graph_entity_beta { [object]$description; [object]$displayName; [object]$isBuiltInRoleDefinition; [object]$permissions; [object]Get_roleAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "roleDefinitions/$($this.Id)/roleAssignments") } } Class microsoft_graph_roleAssignment_beta : microsoft_graph_entity_beta { [object]$description; [object]$displayName; [object]$members; [object]$scopeMembers; [object]Get_roleDefinition() { return (Invoke-GraphMethod -Version 'beta' -Query "roleAssignments/$($this.Id)/roleDefinition") } } Class microsoft_graph_resourceOperation_beta : microsoft_graph_entity_beta { [object]$resourceName; [object]$description; [object]$actionName; } Class microsoft_graph_telecomExpenseManagementPartner_beta : microsoft_graph_entity_beta { [object]$url; [object]$displayName; [object]$lastConnectionDateTime; [object]$enabled; [object]$appAuthorized; } Class microsoft_graph_deviceAppManagement_beta : microsoft_graph_entity_beta { [object]$windowsStoreForBusinessLanguage; [object]$windowsStoreForBusinessLastCompletedApplicationSyncTime; [object]$windowsStoreForBusinessLastSuccessfulSyncDateTime; [object]$isEnabledForWindowsStoreForBusiness; [object]Get_mobileApps() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/mobileApps") } [object]Get_mobileAppCategories() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/mobileAppCategories") } [object]Get_enterpriseCodeSigningCertificates() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/enterpriseCodeSigningCertificates") } [object]Get_iosLobAppProvisioningConfigurations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/iosLobAppProvisioningConfigurations") } [object]Get_symantecCodeSigningCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/symantecCodeSigningCertificate") } [object]Get_sideLoadingKeys() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/sideLoadingKeys") } [object]Get_managedAppPolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/managedAppPolicies") } [object]Get_iosManagedAppProtections() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/iosManagedAppProtections") } [object]Get_androidManagedAppProtections() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/androidManagedAppProtections") } [object]Get_defaultManagedAppProtections() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/defaultManagedAppProtections") } [object]Get_targetedManagedAppConfigurations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/targetedManagedAppConfigurations") } [object]Get_mdmWindowsInformationProtectionPolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/mdmWindowsInformationProtectionPolicies") } [object]Get_windowsInformationProtectionPolicies() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/windowsInformationProtectionPolicies") } [object]Get_managedAppRegistrations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/managedAppRegistrations") } [object]Get_managedAppStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceAppManagements/$($this.Id)/managedAppStatuses") } } Class microsoft_graph_mobileApp_beta : microsoft_graph_entity_beta { [object]$developer; [object]$displayName; [object]$lastModifiedDateTime; [object]$createdDateTime; [object]$privacyInformationUrl; [object]$notes; [object]$informationUrl; [object]$owner; [object]$publisher; [object]$largeIcon; [object]$description; [object]$uploadState; [object]$isFeatured; [object]Get_categories() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileApps/$($this.Id)/categories") } [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileApps/$($this.Id)/groupAssignments") } [object]Get_installSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileApps/$($this.Id)/installSummary") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileApps/$($this.Id)/deviceStatuses") } [object]Get_userStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileApps/$($this.Id)/userStatuses") } } Class microsoft_graph_mobileAppCategory_beta : microsoft_graph_entity_beta { [object]$displayName; [object]$lastModifiedDateTime; } Class microsoft_graph_enterpriseCodeSigningCertificate_beta : microsoft_graph_entity_beta { [object]$subjectName; [object]$issuer; [object]$content; [object]$issuerName; [object]$expirationDateTime; [object]$subject; [object]$uploadDateTime; [object]$status; } Class microsoft_graph_iosLobAppProvisioningConfiguration_beta : microsoft_graph_entity_beta { [object]$payloadFileName; [object]$description; [object]$payload; [object]$version; [object]$createdDateTime; [object]$expirationDateTime; [object]$lastModifiedDateTime; [object]$displayName; [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "iosLobAppProvisioningConfigurations/$($this.Id)/groupAssignments") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "iosLobAppProvisioningConfigurations/$($this.Id)/deviceStatuses") } [object]Get_userStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "iosLobAppProvisioningConfigurations/$($this.Id)/userStatuses") } } Class microsoft_graph_symantecCodeSigningCertificate_beta : microsoft_graph_entity_beta { [object]$subjectName; [object]$issuer; [object]$uploadDateTime; [object]$password; [object]$issuerName; [object]$expirationDateTime; [object]$subject; [object]$content; [object]$status; } Class microsoft_graph_sideLoadingKey_beta : microsoft_graph_entity_beta { [object]$lastUpdatedDateTime; [object]$totalActivation; [object]$description; [object]$displayName; [object]$value; } Class microsoft_graph_managedAppPolicy_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$description; [object]$version; [object]$lastModifiedTime; [object]$createdDateTime; [object]$deployedAppCount; [object]$displayName; [object]Get_mobileAppIdentifierDeployments() { return (Invoke-GraphMethod -Version 'beta' -Query "managedAppPolicys/$($this.Id)/mobileAppIdentifierDeployments") } [object]Get_deploymentSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "managedAppPolicys/$($this.Id)/deploymentSummary") } } Class microsoft_graph_managedAppProtection_beta : microsoft_graph_managedAppPolicy_beta { [object]$simplePinBlocked; [object]$saveAsBlocked; [object]$periodOnlineBeforeAccessCheck; [object]$managedBrowserToOpenLinksRequired; [object]$printBlocked; [object]$dataBackupBlocked; [object]$contactSyncBlocked; [object]$allowedInboundDataTransferSources; [object]$fingerprintBlocked; [object]$pinRequired; [object]$organizationalCredentialsRequired; [object]$pinCharacterSet; [object]$maximumPinRetries; [object]$allowedOutboundDataTransferDestinations; [object]$deviceComplianceRequired; [object]$allowedDataStorageLocations; [object]$periodOfflineBeforeAccessCheck; [object]$minimumPinLength; [object]$allowedOutboundClipboardSharingLevel; [object]$periodOfflineBeforeWipeIsEnforced; } Class microsoft_graph_targetedManagedAppProtection_beta : microsoft_graph_managedAppProtection_beta { [object]$targetedSecurityGroupIds; [object]$targetedSecurityGroupsCount; [object]Get_targetedSecurityGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "targetedManagedAppProtections/$($this.Id)/targetedSecurityGroups") } } Class microsoft_graph_iosManagedAppProtection_beta : microsoft_graph_targetedManagedAppProtection_beta { [object]$appDataEncryptionType; } Class microsoft_graph_androidManagedAppProtection_beta : microsoft_graph_targetedManagedAppProtection_beta { [object]$encryptAppData; [object]$screenCaptureBlocked; } Class microsoft_graph_defaultManagedAppProtection_beta : microsoft_graph_managedAppProtection_beta { [object]$appDataEncryptionType; [object]$screenCaptureBlocked; [object]$customSettings; [object]$encryptAppData; } Class microsoft_graph_managedAppConfiguration_beta : microsoft_graph_managedAppPolicy_beta { [object]$customSettings; } Class microsoft_graph_targetedManagedAppConfiguration_beta : microsoft_graph_managedAppConfiguration_beta { [object]$targetedSecurityGroupIds; [object]$targetedSecurityGroupsCount; [object]Get_targetedSecurityGroups() { return (Invoke-GraphMethod -Version 'beta' -Query "targetedManagedAppConfigurations/$($this.Id)/targetedSecurityGroups") } } Class microsoft_graph_windowsInformationProtection_beta : microsoft_graph_managedAppPolicy_beta { [object]$enterpriseNetworkDomainNames; [object]$exemptApps; [object]$enterpriseProxyServers; [object]$protectionUnderLockConfigRequired; [object]$azureRightsManagementServicesAllowed; [object]$enforcementLevel; [object]$allowedApps; [object]$targetedSecurityGroupIds; [object]$enterpriseDomain; [object]$enterpriseIPRanges; [object]$enterpriseProxyServersAreAuthoritative; [object]$dataRecoveryCertificate; [object]$iconsVisible; [object]$enterpriseCloudResources; [object]$enterpriseInternalProxyServers; [object]$enterpriseProtectedDomainNames; [object]$rightsManagementServicesTemplateId; [object]$enterpriseIPRangesAreAuthoritative; [object]$revokeOnUnenrollDisabled; [object]$neutralDomainResources; [object]Get_allowedAppLockerFiles() { return (Invoke-GraphMethod -Version 'beta' -Query "windowsInformationProtections/$($this.Id)/allowedAppLockerFiles") } [object]Get_exemptAppLockerFiles() { return (Invoke-GraphMethod -Version 'beta' -Query "windowsInformationProtections/$($this.Id)/exemptAppLockerFiles") } } Class microsoft_graph_mdmWindowsInformationProtectionPolicy_beta : microsoft_graph_windowsInformationProtection_beta { } Class microsoft_graph_windowsInformationProtectionPolicy_beta : microsoft_graph_windowsInformationProtection_beta { [object]$numberOfPastPinsRemembered; [object]$mdmEnrollmentUrl; [object]$pinExpirationDays; [object]$minutesOfInactivityBeforeDeviceLock; [object]$windowsHelloForBusinessBlocked; [object]$pinMinimumLength; [object]$pinLowercaseLetters; [object]$pinUppercaseLetters; [object]$pinSpecialCharacters; [object]$revokeOnMdmHandoffDisabled; [object]$passwordMaximumAttemptCount; } Class microsoft_graph_managedAppStatus_beta : microsoft_graph_entity_beta { [object]$displayName; [object]$version; } Class microsoft_graph_managedDeviceMobileAppConfiguration_beta : microsoft_graph_entity_beta { [object]$targetedMobileApps; [object]$description; [object]$version; [object]$settingXml; [object]$createdDateTime; [object]$lastModifiedDateTime; [object]$settings; [object]$displayName; [object]Get_groupAssignments() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDeviceMobileAppConfigurations/$($this.Id)/groupAssignments") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDeviceMobileAppConfigurations/$($this.Id)/deviceStatuses") } [object]Get_userStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDeviceMobileAppConfigurations/$($this.Id)/userStatuses") } [object]Get_deviceStatusSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDeviceMobileAppConfigurations/$($this.Id)/deviceStatusSummary") } [object]Get_userStatusSummary() { return (Invoke-GraphMethod -Version 'beta' -Query "managedDeviceMobileAppConfigurations/$($this.Id)/userStatusSummary") } } Class microsoft_graph_mdmAppConfigGroupAssignment_beta : microsoft_graph_entity_beta { [object]$appConfiguration; [object]$targetGroupId; } Class microsoft_graph_managedDeviceMobileAppConfigurationDeviceStatus_beta : microsoft_graph_entity_beta { [object]$status; [object]$deviceDisplayName; [object]$userPrincipalName; [object]$lastReportedDateTime; } Class microsoft_graph_managedDeviceMobileAppConfigurationUserStatus_beta : microsoft_graph_entity_beta { [object]$userDisplayName; [object]$devicesCount; [object]$status; [object]$lastReportedDateTime; [object]$userPrincipalName; } Class microsoft_graph_managedDeviceMobileAppConfigurationDeviceSummary_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_managedDeviceMobileAppConfigurationUserSummary_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_mobileAppGroupAssignment_beta : microsoft_graph_entity_beta { [object]$installIntent; [object]$targetGroupId; [object]Get_app() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileAppGroupAssignments/$($this.Id)/app") } } Class microsoft_graph_mobileAppInstallSummary_beta : microsoft_graph_entity_beta { [object]$notInstalledDeviceCount; [object]$installedUserCount; [object]$failedUserCount; [object]$failedDeviceCount; [object]$notInstalledUserCount; [object]$installedDeviceCount; } Class microsoft_graph_mobileAppInstallStatus_beta : microsoft_graph_entity_beta { [object]$lastSyncDateTime; [object]$userName; [object]$mobileAppInstallStatusValue; [object]$deviceName; [object]$osVersion; [object]$errorCode; [object]$deviceId; [object]$osDescription; [object]Get_app() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileAppInstallStatuss/$($this.Id)/app") } } Class microsoft_graph_userAppInstallStatus_beta : microsoft_graph_entity_beta { [object]$userName; [object]$failedDeviceCount; [object]$notInstalledDeviceCount; [object]$installedDeviceCount; [object]Get_app() { return (Invoke-GraphMethod -Version 'beta' -Query "userAppInstallStatuss/$($this.Id)/app") } [object]Get_deviceStatuses() { return (Invoke-GraphMethod -Version 'beta' -Query "userAppInstallStatuss/$($this.Id)/deviceStatuses") } } Class microsoft_graph_mobileAppContentFile_beta : microsoft_graph_entity_beta { [object]$uploadState; [object]$azureStorageUriExpirationDateTime; [object]$size; [object]$isCommitted; [object]$azureStorageUri; [object]$createdDateTime; [object]$name; [object]$manifest; [object]$sizeEncrypted; } Class microsoft_graph_mobileAppProvisioningConfigGroupAssignment_beta : microsoft_graph_entity_beta { [object]$targetGroupId; } Class microsoft_graph_mobileAppVppGroupAssignment_beta : microsoft_graph_mobileAppGroupAssignment_beta { [object]$useDeviceLicensing; } Class microsoft_graph_officeSuiteApp_beta : microsoft_graph_mobileApp_beta { [object]$excludedOfficeApps; [object]$productIds; [object]$autoAcceptEula; } Class microsoft_graph_managedApp_beta : microsoft_graph_mobileApp_beta { [object]$appAvailability; [object]$version; } Class microsoft_graph_managedAndroidStoreApp_beta : microsoft_graph_managedApp_beta { [object]$packageId; } Class microsoft_graph_managedIOSStoreApp_beta : microsoft_graph_managedApp_beta { [object]$bundleId; } Class microsoft_graph_managedMobileLobApp_beta : microsoft_graph_managedApp_beta { [object]$committedContentVersion; [object]$identityVersion; [object]$fileName; [object]$size; [object]Get_contentVersions() { return (Invoke-GraphMethod -Version 'beta' -Query "managedMobileLobApps/$($this.Id)/contentVersions") } } Class microsoft_graph_mobileAppContent_beta : microsoft_graph_entity_beta { [object]Get_files() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileAppContents/$($this.Id)/files") } } Class microsoft_graph_managedAndroidLobApp_beta : microsoft_graph_managedMobileLobApp_beta { [object]$identityName; [object]$minimumSupportedOperatingSystem; } Class microsoft_graph_managedIOSLobApp_beta : microsoft_graph_managedMobileLobApp_beta { [object]$bundleId; [object]$minimumSupportedOperatingSystem; [object]$applicableDeviceType; [object]$expirationDateTime; } Class microsoft_graph_mobileLobApp_beta : microsoft_graph_mobileApp_beta { [object]$committedContentVersion; [object]$identityVersion; [object]$fileName; [object]$size; [object]Get_contentVersions() { return (Invoke-GraphMethod -Version 'beta' -Query "mobileLobApps/$($this.Id)/contentVersions") } } Class microsoft_graph_windowsMobileMSI_beta : microsoft_graph_mobileLobApp_beta { [object]$commandLine; [object]$productCode; } Class microsoft_graph_windowsPhone81AppX_beta : microsoft_graph_mobileLobApp_beta { [object]$minimumSupportedOperatingSystem; [object]$identityPublisherHash; [object]$identityResourceIdentifier; [object]$identityName; [object]$phoneProductIdentifier; [object]$applicableArchitectures; [object]$phonePublisherId; } Class microsoft_graph_windowsPhone81AppXBundle_beta : microsoft_graph_windowsPhone81AppX_beta { [object]$appXPackageInformationList; } Class microsoft_graph_windowsUniversalAppX_beta : microsoft_graph_mobileLobApp_beta { [object]$minimumSupportedOperatingSystem; [object]$applicableDeviceTypes; [object]$identityPublisherHash; [object]$isBundle; [object]$identityResourceIdentifier; [object]$identityName; [object]$applicableArchitectures; } Class microsoft_graph_windowsAppX_beta : microsoft_graph_mobileLobApp_beta { [object]$minimumSupportedOperatingSystem; [object]$identityPublisherHash; [object]$isBundle; [object]$identityResourceIdentifier; [object]$identityName; [object]$applicableArchitectures; } Class microsoft_graph_windowsPhoneXAP_beta : microsoft_graph_mobileLobApp_beta { [object]$minimumSupportedOperatingSystem; [object]$productIdentifier; } Class microsoft_graph_androidLobApp_beta : microsoft_graph_mobileLobApp_beta { [object]$identityName; [object]$minimumSupportedOperatingSystem; } Class microsoft_graph_iosLobApp_beta : microsoft_graph_mobileLobApp_beta { [object]$bundleId; [object]$minimumSupportedOperatingSystem; [object]$applicableDeviceType; [object]$expirationDateTime; } Class microsoft_graph_androidForWorkApp_beta : microsoft_graph_mobileApp_beta { [object]$appStoreUrl; [object]$usedLicenseCount; [object]$appIdentifier; [object]$totalLicenseCount; } Class microsoft_graph_webApp_beta : microsoft_graph_mobileApp_beta { [object]$appUrl; [object]$useManagedBrowser; } Class microsoft_graph_windowsPhone81StoreApp_beta : microsoft_graph_mobileApp_beta { [object]$appStoreUrl; } Class microsoft_graph_windowsStoreApp_beta : microsoft_graph_mobileApp_beta { [object]$appStoreUrl; } Class microsoft_graph_androidStoreApp_beta : microsoft_graph_mobileApp_beta { [object]$minimumSupportedOperatingSystem; [object]$appStoreUrl; [object]$appIdentifier; } Class microsoft_graph_iosVppApp_beta : microsoft_graph_mobileApp_beta { [object]$appStoreUrl; [object]$releaseDateTime; [object]$licensingType; [object]$usedLicenseCount; [object]$applicableDeviceType; [object]$totalLicenseCount; [object]Get_vppToken() { return (Invoke-GraphMethod -Version 'beta' -Query "iosVppApps/$($this.Id)/vppToken") } } Class microsoft_graph_iosStoreApp_beta : microsoft_graph_mobileApp_beta { [object]$bundleId; [object]$appStoreUrl; [object]$minimumSupportedOperatingSystem; [object]$applicableDeviceType; } Class microsoft_graph_windowsStoreForBusinessApp_beta : microsoft_graph_mobileApp_beta { [object]$usedLicenseCount; [object]$totalLicenseCount; } Class microsoft_graph_appReportingOverviewStatus_beta : microsoft_graph_entity_beta { } Class microsoft_graph_iosMobileAppConfiguration_beta : microsoft_graph_managedDeviceMobileAppConfiguration_beta { } Class microsoft_graph_termsAndConditionsGroupAssignment_beta : microsoft_graph_entity_beta { [object]$targetGroupId; [object]Get_termsAndConditions() { return (Invoke-GraphMethod -Version 'beta' -Query "termsAndConditionsGroupAssignments/$($this.Id)/termsAndConditions") } } Class microsoft_graph_termsAndConditionsAcceptanceStatus_beta : microsoft_graph_entity_beta { [object]$userDisplayName; [object]$acceptedVersion; [object]$acceptedDateTime; [object]Get_termsAndConditions() { return (Invoke-GraphMethod -Version 'beta' -Query "termsAndConditionsAcceptanceStatuss/$($this.Id)/termsAndConditions") } } Class microsoft_graph_importedDeviceIdentityResult_beta : microsoft_graph_importedDeviceIdentity_beta { [object]$status; } Class microsoft_graph_importedAppleDeviceIdentityResult_beta : microsoft_graph_importedAppleDeviceIdentity_beta { [object]$status; } Class microsoft_graph_depEnrollmentProfile_beta : microsoft_graph_enrollmentProfile_beta { [object]$restoreFromAndroidDisabled; [object]$macOSFileVaultDisabled; [object]$restoreBlocked; [object]$supervisedModeEnabled; [object]$sharedIPadMaximumUserCount; [object]$zoomDisabled; [object]$enableSharedIPad; [object]$touchIdDisabled; [object]$iTunesPairingMode; [object]$supportPhoneNumber; [object]$termsAndConditionsDisabled; [object]$diagnosticsDisabled; [object]$isMandatory; [object]$locationDisabled; [object]$passCodeDisabled; [object]$supportDepartment; [object]$applePayDisabled; [object]$macOSRegistrationDisabled; [object]$managementCertificates; [object]$awaitDeviceConfiguredConfirmation; [object]$appleIdDisabled; [object]$profileRemovalDisabled; [object]$siriDisabled; } Class microsoft_graph_deviceConfigurationState_beta : microsoft_graph_entity_beta { [object]$version; [object]$settingStates; [object]$platformType; [object]$state; [object]$settingCount; [object]$displayName; } Class microsoft_graph_detectedApp_beta : microsoft_graph_entity_beta { [object]$sizeInByte; [object]$displayName; [object]$version; [object]$deviceCount; [object]Get_managedDevices() { return (Invoke-GraphMethod -Version 'beta' -Query "detectedApps/$($this.Id)/managedDevices") } } Class microsoft_graph_deviceCompliancePolicyState_beta : microsoft_graph_entity_beta { [object]$version; [object]$settingStates; [object]$platformType; [object]$state; [object]$settingCount; [object]$displayName; } Class microsoft_graph_managedDeviceOverview_beta : microsoft_graph_entity_beta { [object]$deviceOperatingSystemSummary; [object]$dualEnrolledDeviceCount; [object]$deviceExchangeAccessStateSummary; [object]$mdmEnrolledCount; [object]$enrolledDeviceCount; } Class microsoft_graph_cloudPkiSubscription_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$description; [object]$syncStatus; [object]$cloudPkiProvider; [object]$lastSyncDateTime; [object]$createdDateTime; [object]$trustedRootCertificate; [object]$version; [object]$lastSyncError; [object]$credentials; [object]$displayName; } Class microsoft_graph_deviceConfigurationAssignment_beta : microsoft_graph_entity_beta { [object]Get_deviceConfiguration() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceConfigurationAssignments/$($this.Id)/deviceConfiguration") } } Class microsoft_graph_deviceConfigurationGroupAssignment_beta : microsoft_graph_deviceConfigurationAssignment_beta { [object]$targetGroupId; } Class microsoft_graph_deviceConfigurationDeviceStatus_beta : microsoft_graph_entity_beta { [object]$status; [object]$deviceDisplayName; [object]$userPrincipalName; [object]$lastReportedDateTime; } Class microsoft_graph_deviceConfigurationUserStatus_beta : microsoft_graph_entity_beta { [object]$userDisplayName; [object]$devicesCount; [object]$status; [object]$lastReportedDateTime; [object]$userPrincipalName; } Class microsoft_graph_deviceConfigurationDeviceOverview_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_deviceConfigurationUserOverview_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_settingStateDeviceSummary_beta : microsoft_graph_entity_beta { [object]$conflictDeviceCount; [object]$notApplicableDeviceCount; [object]$instancePath; [object]$remediatedDeviceCount; [object]$settingName; [object]$compliantDeviceCount; [object]$unknownDeviceCount; [object]$nonCompliantDeviceCount; [object]$errorDeviceCount; } Class microsoft_graph_deviceCompliancePolicyAssignment_beta : microsoft_graph_entity_beta { [object]Get_deviceCompliancePolicy() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceCompliancePolicyAssignments/$($this.Id)/deviceCompliancePolicy") } } Class microsoft_graph_deviceCompliancePolicyGroupAssignment_beta : microsoft_graph_deviceCompliancePolicyAssignment_beta { [object]$targetGroupId; } Class microsoft_graph_deviceComplianceScheduledActionForRule_beta : microsoft_graph_entity_beta { [object]$ruleName; [object]Get_scheduledActionConfigurations() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceComplianceScheduledActionForRules/$($this.Id)/scheduledActionConfigurations") } } Class microsoft_graph_deviceComplianceDeviceStatus_beta : microsoft_graph_entity_beta { [object]$status; [object]$deviceDisplayName; [object]$userPrincipalName; [object]$lastReportedDateTime; } Class microsoft_graph_deviceComplianceUserStatus_beta : microsoft_graph_entity_beta { [object]$userDisplayName; [object]$devicesCount; [object]$status; [object]$lastReportedDateTime; [object]$userPrincipalName; } Class microsoft_graph_deviceComplianceDeviceOverview_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_deviceComplianceUserOverview_beta : microsoft_graph_entity_beta { [object]$configurationVersion; [object]$failedCount; [object]$errorCount; [object]$pendingCount; [object]$lastUpdateDateTime; [object]$successCount; } Class microsoft_graph_deviceComplianceActionItem_beta : microsoft_graph_entity_beta { [object]$actionType; [object]$gracePeriodHours; [object]Get_notificationMessageTemplate() { return (Invoke-GraphMethod -Version 'beta' -Query "deviceComplianceActionItems/$($this.Id)/notificationMessageTemplate") } } Class microsoft_graph_androidForWorkEasEmailProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$authenticationMethod; [object]$hostName; [object]$usernameSource; [object]$requireSsl; [object]$emailAddressSource; [object]$durationOfEmailToSync; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkEasEmailProfileBases/$($this.Id)/identityCertificate") } } Class microsoft_graph_androidForWorkCertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$subjectAlternativeNameType; [object]$certificateValidityPeriodScale; [object]$certificateValidityPeriodValue; [object]$subjectNameFormat; [object]$renewalThresholdPercentage; [object]$extendedKeyUsages; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkCertificateProfileBases/$($this.Id)/rootCertificate") } } Class microsoft_graph_androidForWorkTrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$certFileName; [object]$trustedRootCertificate; } Class microsoft_graph_androidForWorkPkcsCertificateProfile_beta : microsoft_graph_androidForWorkCertificateProfileBase_beta { [object]$certificateTemplateName; [object]$certificationAuthority; [object]$certificationAuthorityName; } Class microsoft_graph_androidForWorkScepCertificateProfile_beta : microsoft_graph_androidForWorkCertificateProfileBase_beta { [object]$keySize; [object]$scepServerUrls; [object]$keyUsage; [object]$hashAlgorithm; [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkScepCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_managedDeviceCertificateState_beta : microsoft_graph_entity_beta { [object]$serverUrl; [object]$userDisplayName; [object]$certificateIssuer; [object]$devicePlatform; [object]$lastCertificateStateChangeDateTime; [object]$certificateKeyUsage; [object]$certificateProfileDisplayName; [object]$enhancedKeyUsage; [object]$certificateSerialNumber; [object]$certificateKeyLength; [object]$certificateThumbprint; [object]$deviceDisplayName; [object]$certificateExpirationDateTime; } Class microsoft_graph_androidForWorkGmailEasConfiguration_beta : microsoft_graph_androidForWorkEasEmailProfileBase_beta { } Class microsoft_graph_androidForWorkNineWorkEasConfiguration_beta : microsoft_graph_androidForWorkEasEmailProfileBase_beta { [object]$syncCalendar; [object]$syncContacts; [object]$syncTasks; } Class microsoft_graph_androidCertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$subjectAlternativeNameType; [object]$certificateValidityPeriodScale; [object]$certificateValidityPeriodValue; [object]$subjectNameFormat; [object]$renewalThresholdPercentage; [object]$extendedKeyUsages; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidCertificateProfileBases/$($this.Id)/rootCertificate") } } Class microsoft_graph_androidTrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$certFileName; [object]$trustedRootCertificate; } Class microsoft_graph_androidPkcsCertificateProfile_beta : microsoft_graph_androidCertificateProfileBase_beta { [object]$certificateTemplateName; [object]$certificationAuthority; [object]$certificationAuthorityName; } Class microsoft_graph_androidScepCertificateProfile_beta : microsoft_graph_androidCertificateProfileBase_beta { [object]$keySize; [object]$scepServerUrls; [object]$keyUsage; [object]$hashAlgorithm; [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "androidScepCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_androidCustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$omaSettings; } Class microsoft_graph_androidEasEmailProfileConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$syncCalendar; [object]$requireSsl; [object]$emailSyncSchedule; [object]$usernameSource; [object]$authenticationMethod; [object]$emailAddressSource; [object]$syncTasks; [object]$requireSmime; [object]$hostName; [object]$durationOfEmailToSync; [object]$syncNotes; [object]$syncContacts; [object]$accountName; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidEasEmailProfileConfigurations/$($this.Id)/identityCertificate") } [object]Get_smimeSigningCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidEasEmailProfileConfigurations/$($this.Id)/smimeSigningCertificate") } } Class microsoft_graph_androidForWorkCustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$omaSettings; } Class microsoft_graph_androidForWorkGeneralDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$workProfileDataSharingType; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$passwordBlockTrustAgents; [object]$passwordPreviousPasswordBlockCount; [object]$workProfileDefaultAppPermissionPolicy; [object]$passwordSignInFailureCountBeforeFactoryReset; [object]$passwordExpirationDays; [object]$passwordBlockFingerprintUnlock; [object]$passwordRequiredType; [object]$passwordMinimumLength; [object]$workProfileBlockNotificationsWhileDeviceLocked; } Class microsoft_graph_androidForWorkVpnConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$authenticationMethod; [object]$servers; [object]$enableSplitTunneling; [object]$connectionName; [object]$role; [object]$fingerprint; [object]$customData; [object]$connectionType; [object]$realm; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkVpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_androidForWorkWiFiConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$connectAutomatically; [object]$ssid; [object]$networkName; [object]$connectWhenNetworkNameIsHidden; [object]$wiFiSecurityType; } Class microsoft_graph_androidForWorkEnterpriseWiFiConfiguration_beta : microsoft_graph_androidForWorkWiFiConfiguration_beta { [object]$authenticationMethod; [object]$nonEapAuthenticationMethodForEapTtls; [object]$enableOuterIdentityPrivacy; [object]$nonEapAuthenticationMethodForPeap; [object]$eapType; [object]Get_rootCertificateForServerValidation() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkEnterpriseWiFiConfigurations/$($this.Id)/rootCertificateForServerValidation") } [object]Get_identityCertificateForClientAuthentication() { return (Invoke-GraphMethod -Version 'beta' -Query "androidForWorkEnterpriseWiFiConfigurations/$($this.Id)/identityCertificateForClientAuthentication") } } Class microsoft_graph_androidGeneralDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$appsBlockCopyPaste; [object]$googlePlayStoreBlocked; [object]$cellularBlockWiFiTethering; [object]$storageRequireDeviceEncryption; [object]$nfcBlocked; [object]$diagnosticDataBlockSubmission; [object]$cellularBlockDataRoaming; [object]$passwordBlockTrustAgents; [object]$deviceSharingBlocked; [object]$storageBlockGoogleBackup; [object]$cameraBlocked; [object]$compliantAppsList; [object]$googleAccountBlockAutoSync; [object]$voiceDialingBlocked; [object]$compliantAppListType; [object]$appsBlockClipboardSharing; [object]$webBrowserBlockPopups; [object]$voiceAssistantBlocked; [object]$bluetoothBlocked; [object]$cellularBlockMessaging; [object]$webBrowserCookieSettings; [object]$wiFiBlocked; [object]$passwordExpirationDays; [object]$storageBlockRemovableStorage; [object]$powerOffBlocked; [object]$kioskModeBlockSleepButton; [object]$screenCaptureBlocked; [object]$kioskModeManagedAppId; [object]$passwordMinimumLength; [object]$passwordRequired; [object]$kioskModeBlockVolumeButtons; [object]$passwordSignInFailureCountBeforeFactoryReset; [object]$webBrowserBlocked; [object]$webBrowserBlockJavaScript; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$factoryResetBlocked; [object]$locationServicesBlocked; [object]$webBrowserBlockAutofill; [object]$passwordPreviousPasswordBlockCount; [object]$passwordRequiredType; [object]$storageRequireRemovableStorageEncryption; [object]$appsBlockYouTube; [object]$passwordBlockFingerprintUnlock; [object]$cellularBlockVoiceRoaming; } Class microsoft_graph_androidVpnConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$authenticationMethod; [object]$servers; [object]$connectionName; [object]$role; [object]$fingerprint; [object]$customData; [object]$connectionType; [object]$realm; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "androidVpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_androidWiFiConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$connectAutomatically; [object]$ssid; [object]$networkName; [object]$connectWhenNetworkNameIsHidden; [object]$wiFiSecurityType; } Class microsoft_graph_androidEnterpriseWiFiConfiguration_beta : microsoft_graph_androidWiFiConfiguration_beta { [object]$authenticationMethod; [object]$nonEapAuthenticationMethodForEapTtls; [object]$enableOuterIdentityPrivacy; [object]$nonEapAuthenticationMethodForPeap; [object]$eapType; [object]Get_rootCertificateForServerValidation() { return (Invoke-GraphMethod -Version 'beta' -Query "androidEnterpriseWiFiConfigurations/$($this.Id)/rootCertificateForServerValidation") } [object]Get_identityCertificateForClientAuthentication() { return (Invoke-GraphMethod -Version 'beta' -Query "androidEnterpriseWiFiConfigurations/$($this.Id)/identityCertificateForClientAuthentication") } } Class microsoft_graph_iosCertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$certificateValidityPeriodValue; [object]$subjectAlternativeNameType; [object]$renewalThresholdPercentage; [object]$certificateValidityPeriodScale; [object]$subjectNameFormat; } Class microsoft_graph_iosPkcsCertificateProfile_beta : microsoft_graph_iosCertificateProfileBase_beta { [object]$certificateTemplateName; [object]$certificationAuthority; [object]$certificationAuthorityName; } Class microsoft_graph_iosScepCertificateProfile_beta : microsoft_graph_iosCertificateProfileBase_beta { [object]$keySize; [object]$extendedKeyUsages; [object]$scepServerUrls; [object]$keyUsage; [object]$subjectNameFormatString; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "iosScepCertificateProfiles/$($this.Id)/rootCertificate") } [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "iosScepCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_iosTrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$certFileName; [object]$trustedRootCertificate; } Class microsoft_graph_iosCustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$payloadFileName; [object]$payloadName; [object]$payload; } Class microsoft_graph_iosEasEmailProfileConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$authenticationMethod; [object]$hostName; [object]$accountName; [object]$blockSyncingRecentlyUsedEmailAddresses; [object]$blockMovingMessagesToOtherEmailAccounts; [object]$emailAddressSource; [object]$usernameSource; [object]$requireSmime; [object]$blockSendingEmailFromThirdPartyApps; [object]$requireSsl; [object]$durationOfEmailToSync; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "iosEasEmailProfileConfigurations/$($this.Id)/identityCertificate") } [object]Get_smimeSigningCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "iosEasEmailProfileConfigurations/$($this.Id)/smimeSigningCertificate") } } Class microsoft_graph_iosEduDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$deviceCertificateSettings; [object]$teacherCertificateSettings; [object]$studentCertificateSettings; } Class microsoft_graph_iosEducationDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { } Class microsoft_graph_iosGeneralDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$kioskModeAllowTouchscreen; [object]$iCloudBlockActivityContinuation; [object]$lockScreenBlockNotificationView; [object]$configurationProfileBlockChanges; [object]$kioskModeAllowVoiceOverSettings; [object]$keyboardBlockPredictive; [object]$accountBlockModification; [object]$iTunesBlockRadio; [object]$iTunesBlockExplicitContent; [object]$cameraBlocked; [object]$notificationsBlockSettingsModification; [object]$iTunesBlockMusicService; [object]$screenCaptureBlocked; [object]$appStoreBlockInAppPurchases; [object]$kioskModeManagedAppId; [object]$iCloudBlockPhotoLibrary; [object]$safariBlockAutofill; [object]$kioskModeRequireVoiceOver; [object]$kioskModeAppStoreUrl; [object]$mediaContentRatingAustralia; [object]$appsVisibilityList; [object]$gameCenterBlocked; [object]$deviceBlockEraseContentAndSettings; [object]$gamingBlockMultiplayer; [object]$siriRequireProfanityFilter; [object]$kioskModeAllowRingerSwitch; [object]$lockScreenBlockPassbook; [object]$deviceBlockEnableRestrictions; [object]$appleWatchBlockPairing; [object]$kioskModeAllowSleepButton; [object]$passcodeMinimumLength; [object]$safariBlocked; [object]$mediaContentRatingApps; [object]$appStoreRequirePassword; [object]$passcodeBlockSimple; [object]$siriBlockUserGeneratedContent; [object]$iCloudBlockSharedPhotoStream; [object]$compliantAppListType; [object]$findMyFriendsBlocked; [object]$kioskModeRequireZoom; [object]$emailInDomainSuffixes; [object]$voiceDialingBlocked; [object]$classroomAppBlockRemoteScreenObservation; [object]$iCloudBlockManagedAppsSync; [object]$iCloudBlockBackup; [object]$cellularBlockGlobalBackgroundFetchWhileRoaming; [object]$siriBlockedWhenLocked; [object]$iCloudBlockPhotoStreamSync; [object]$diagnosticDataBlockSubmission; [object]$lockScreenBlockControlCenter; [object]$passcodeBlockFingerprintUnlock; [object]$appStoreBlockUIAppInstallation; [object]$iCloudBlockDocumentSync; [object]$iBooksStoreBlocked; [object]$diagnosticDataBlockSubmissionModification; [object]$documentsBlockManagedDocumentsInUnmanagedApps; [object]$safariManagedDomains; [object]$siriBlocked; [object]$passcodeSignInFailureCountBeforeWipe; [object]$appleWatchForceWristDetection; [object]$kioskModeAllowScreenRotation; [object]$iBooksStoreBlockErotica; [object]$safariPasswordAutoFillDomains; [object]$kioskModeAllowAssistiveSpeak; [object]$appleNewsBlocked; [object]$documentsBlockUnmanagedDocumentsInManagedApps; [object]$messagesBlocked; [object]$compliantAppsList; [object]$keyboardBlockShortcuts; [object]$appsSingleAppModeList; [object]$mediaContentRatingFrance; [object]$safariBlockJavaScript; [object]$deviceBlockNameModification; [object]$airDropBlocked; [object]$faceTimeBlocked; [object]$mediaContentRatingIreland; [object]$mediaContentRatingCanada; [object]$passcodeMinutesOfInactivityBeforeLock; [object]$hostPairingBlocked; [object]$cellularBlockPerAppDataModification; [object]$podcastsBlocked; [object]$keyboardBlockSpellCheck; [object]$mediaContentRatingUnitedStates; [object]$passcodeExpirationDays; [object]$appsVisibilityListType; [object]$appStoreBlockAutomaticDownloads; [object]$safariRequireFraudWarning; [object]$passcodeMinutesOfInactivityBeforeScreenTimeout; [object]$airDropForceUnmanagedDropTarget; [object]$kioskModeAllowColorInversionSettings; [object]$kioskModeAllowVolumeButtons; [object]$enterpriseAppBlockTrust; [object]$activationLockAllowWhenSupervised; [object]$mediaContentRatingUnitedKingdom; [object]$appStoreBlocked; [object]$iCloudRequireEncryptedBackup; [object]$mediaContentRatingJapan; [object]$kioskModeAllowAssistiveTouchSettings; [object]$airPlayForcePairingPasswordForOutgoingRequests; [object]$passcodeRequired; [object]$kioskModeAllowZoomSettings; [object]$kioskModeRequireAssistiveTouch; [object]$kioskModeAllowAutoLock; [object]$wallpaperBlockModification; [object]$passcodeRequiredType; [object]$mediaContentRatingGermany; [object]$certificatesBlockUntrustedTlsCertificates; [object]$gamingBlockGameCenterFriends; [object]$passcodeBlockModification; [object]$kioskModeRequireColorInversion; [object]$kioskModeRequireMonoAudio; [object]$lockScreenBlockTodayView; [object]$safariBlockPopups; [object]$cellularBlockVoiceRoaming; [object]$cellularBlockDataRoaming; [object]$keyboardBlockAutoCorrect; [object]$bluetoothBlockModification; [object]$safariCookieSettings; [object]$passcodePreviousPasscodeBlockCount; [object]$spotlightBlockInternetResults; [object]$passcodeMinimumCharacterSetCount; [object]$enterpriseAppBlockTrustModification; [object]$mediaContentRatingNewZealand; [object]$definitionLookupBlocked; } Class microsoft_graph_iosWiFiConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$proxyManualPort; [object]$networkName; [object]$wiFiSecurityType; [object]$proxyAutomaticConfigurationUrl; [object]$proxyManualAddress; [object]$connectWhenNetworkNameIsHidden; [object]$proxySettings; [object]$ssid; [object]$connectAutomatically; } Class microsoft_graph_iosEnterpriseWiFiConfiguration_beta : microsoft_graph_iosWiFiConfiguration_beta { [object]$authenticationMethod; [object]$eapFastConfiguration; [object]$trustedServerCertificateNames; [object]$nonEapAuthenticationMethodForEapTtls; [object]$eapType; [object]$enableOuterIdentityPrivacy; [object]Get_rootCertificatesForServerValidation() { return (Invoke-GraphMethod -Version 'beta' -Query "iosEnterpriseWiFiConfigurations/$($this.Id)/rootCertificatesForServerValidation") } [object]Get_identityCertificateForClientAuthentication() { return (Invoke-GraphMethod -Version 'beta' -Query "iosEnterpriseWiFiConfigurations/$($this.Id)/identityCertificateForClientAuthentication") } } Class microsoft_graph_macOSCertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$certificateValidityPeriodValue; [object]$subjectAlternativeNameType; [object]$renewalThresholdPercentage; [object]$certificateValidityPeriodScale; [object]$subjectNameFormat; } Class microsoft_graph_macOSScepCertificateProfile_beta : microsoft_graph_macOSCertificateProfileBase_beta { [object]$subjectNameFormatString; [object]$scepServerUrls; [object]$hashAlgorithm; [object]$keyUsage; [object]$extendedKeyUsages; [object]$keySize; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "macOSScepCertificateProfiles/$($this.Id)/rootCertificate") } [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "macOSScepCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_macOSTrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$certFileName; [object]$trustedRootCertificate; } Class microsoft_graph_macOSCustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$payloadFileName; [object]$payloadName; [object]$payload; } Class microsoft_graph_macOSGeneralDeviceConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$passwordRequired; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$compliantAppsList; [object]$passwordMinutesOfInactivityBeforeLock; [object]$passwordPreviousPasswordBlockCount; [object]$passwordMinimumCharacterSetCount; [object]$passwordBlockSimple; [object]$compliantAppListType; [object]$passwordExpirationDays; [object]$passwordRequiredType; [object]$emailInDomainSuffixes; [object]$passwordMinimumLength; } Class microsoft_graph_macOSWiFiConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$proxyManualPort; [object]$networkName; [object]$wiFiSecurityType; [object]$proxyAutomaticConfigurationUrl; [object]$proxyManualAddress; [object]$connectWhenNetworkNameIsHidden; [object]$proxySettings; [object]$ssid; [object]$connectAutomatically; } Class microsoft_graph_macOSEnterpriseWiFiConfiguration_beta : microsoft_graph_macOSWiFiConfiguration_beta { [object]$authenticationMethod; [object]$eapFastConfiguration; [object]$trustedServerCertificateNames; [object]$nonEapAuthenticationMethodForEapTtls; [object]$eapType; [object]$enableOuterIdentityPrivacy; [object]Get_rootCertificateForServerValidation() { return (Invoke-GraphMethod -Version 'beta' -Query "macOSEnterpriseWiFiConfigurations/$($this.Id)/rootCertificateForServerValidation") } [object]Get_identityCertificateForClientAuthentication() { return (Invoke-GraphMethod -Version 'beta' -Query "macOSEnterpriseWiFiConfigurations/$($this.Id)/identityCertificateForClientAuthentication") } } Class microsoft_graph_appleDeviceFeaturesConfigurationBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$airPrintDestinations; } Class microsoft_graph_iosDeviceFeaturesConfiguration_beta : microsoft_graph_appleDeviceFeaturesConfigurationBase_beta { [object]$homeScreenPages; [object]$homeScreenDockIcons; [object]$assetTagTemplate; [object]$notificationSettings; [object]$lockScreenFootnote; } Class microsoft_graph_macOSDeviceFeaturesConfiguration_beta : microsoft_graph_appleDeviceFeaturesConfigurationBase_beta { } Class microsoft_graph_appleVpnConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$onDemandRules; [object]$server; [object]$connectionName; [object]$connectionType; [object]$authenticationMethod; [object]$enablePerApp; [object]$loginGroupOrDomain; [object]$realm; [object]$identifier; [object]$customData; [object]$enableSplitTunneling; [object]$proxyServer; [object]$role; [object]$safariDomains; } Class microsoft_graph_iosVpnConfiguration_beta : microsoft_graph_appleVpnConfiguration_beta { [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "iosVpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_macOSVpnConfiguration_beta : microsoft_graph_appleVpnConfiguration_beta { [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "macOSVpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_windows10CustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$omaSettings; } Class microsoft_graph_windows10EasEmailProfileConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$requireSsl; [object]$accountName; [object]$hostName; [object]$emailAddressSource; [object]$syncContacts; [object]$usernameSource; [object]$emailSyncSchedule; [object]$durationOfEmailToSync; [object]$syncTasks; [object]$syncCalendar; } Class microsoft_graph_windows10EnterpriseModernAppManagementConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$uninstallBuiltInApps; } Class microsoft_graph_sharedPCConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$disableAccountManager; [object]$allowedAccounts; [object]$disablePowerPolicies; [object]$kioskAppDisplayName; [object]$maintenanceStartTime; [object]$disableEduPolicies; [object]$idleTimeBeforeSleepInSeconds; [object]$disableSignInOnResume; [object]$kioskAppUserModelId; [object]$allowLocalStorage; [object]$accountManagerPolicy; } Class microsoft_graph_windows10SecureAssessmentConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$allowScreenCapture; [object]$allowTextSuggestion; [object]$configurationAccount; [object]$launchUri; [object]$allowPrinting; } Class microsoft_graph_windows81WifiImportConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$payloadFileName; [object]$profileName; [object]$payload; } Class microsoft_graph_windowsCertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$subjectAlternativeNameType; [object]$certificateValidityPeriodScale; [object]$keyStorageProvider; [object]$subjectNameFormat; [object]$certificateValidityPeriodValue; [object]$renewalThresholdPercentage; } Class microsoft_graph_windows10CertificateProfileBase_beta : microsoft_graph_windowsCertificateProfileBase_beta { } Class microsoft_graph_windows10PkcsCertificateProfile_beta : microsoft_graph_windows10CertificateProfileBase_beta { [object]$certificateTemplateName; [object]$certificationAuthority; [object]$certificationAuthorityName; } Class microsoft_graph_windows81CertificateProfileBase_beta : microsoft_graph_windowsCertificateProfileBase_beta { [object]$extendedKeyUsages; } Class microsoft_graph_windows81SCEPCertificateProfile_beta : microsoft_graph_windows81CertificateProfileBase_beta { [object]$keySize; [object]$scepServerUrls; [object]$keyUsage; [object]$hashAlgorithm; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "windows81SCEPCertificateProfiles/$($this.Id)/rootCertificate") } [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "windows81SCEPCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_windows81TrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$destinationStore; [object]$trustedRootCertificate; [object]$certFileName; } Class microsoft_graph_windowsPhone81CustomConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$omaSettings; } Class microsoft_graph_windowsPhone81TrustedRootCertificate_beta : microsoft_graph_deviceConfiguration_beta { [object]$certFileName; [object]$trustedRootCertificate; } Class microsoft_graph_windowsPhoneEASEmailProfileConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$requireSsl; [object]$applyOnlyToWindowsPhone81; [object]$accountName; [object]$hostName; [object]$emailAddressSource; [object]$syncContacts; [object]$usernameSource; [object]$emailSyncSchedule; [object]$durationOfEmailToSync; [object]$syncTasks; [object]$syncCalendar; } Class microsoft_graph_windowsUpdateForBusinessConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$installationSchedule; [object]$prereleaseFeatures; [object]$qualityUpdatesPaused; [object]$featureUpdatesPaused; [object]$automaticUpdateMode; [object]$featureUpdatesDeferralPeriodInDays; [object]$qualityUpdatesDeferralPeriodInDays; [object]$businessReadyUpdatesOnly; [object]$restartMode; [object]$microsoftUpdateServiceAllowed; [object]$deliveryOptimizationMode; [object]$qualityUpdatesPauseExpiryDateTime; [object]$driversExcluded; [object]$featureUpdatesPauseExpiryDateTime; } Class microsoft_graph_windowsVpnConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$connectionName; [object]$servers; [object]$customXml; } Class microsoft_graph_windows10VpnConfiguration_beta : microsoft_graph_windowsVpnConfiguration_beta { [object]$dnsRules; [object]$enableConditionalAccess; [object]$windowsInformationProtectionDomain; [object]$trafficRules; [object]$connectionType; [object]$authenticationMethod; [object]$onlyAssociatedAppsCanUseConnection; [object]$enableSingleSignOnWithAlternateCertificate; [object]$routes; [object]$rememberUserCredentials; [object]$singleSignOnIssuerHash; [object]$singleSignOnEku; [object]$proxyServer; [object]$eapXml; [object]$associatedApps; [object]$enableSplitTunneling; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "windows10VpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_windows81VpnConfiguration_beta : microsoft_graph_windowsVpnConfiguration_beta { [object]$enableSplitTunneling; [object]$connectionType; [object]$applyOnlyToWindows81; [object]$loginGroupOrDomain; [object]$proxyServer; } Class microsoft_graph_windowsPhone81VpnConfiguration_beta : microsoft_graph_windows81VpnConfiguration_beta { [object]$authenticationMethod; [object]$bypassVpnOnHomeWifi; [object]$dnsSuffixSearchList; [object]$bypassVpnOnCompanyWifi; [object]$rememberUserCredentials; [object]Get_identityCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "windowsPhone81VpnConfigurations/$($this.Id)/identityCertificate") } } Class microsoft_graph_windowsPhone81CertificateProfileBase_beta : microsoft_graph_deviceConfiguration_beta { [object]$subjectAlternativeNameType; [object]$certificateValidityPeriodScale; [object]$keyStorageProvider; [object]$subjectNameFormat; [object]$certificateValidityPeriodValue; [object]$renewalThresholdPercentage; [object]$extendedKeyUsages; } Class microsoft_graph_windowsPhone81SCEPCertificateProfile_beta : microsoft_graph_windowsPhone81CertificateProfileBase_beta { [object]$keySize; [object]$scepServerUrls; [object]$keyUsage; [object]$hashAlgorithm; [object]Get_rootCertificate() { return (Invoke-GraphMethod -Version 'beta' -Query "windowsPhone81SCEPCertificateProfiles/$($this.Id)/rootCertificate") } [object]Get_managedDeviceCertificateStates() { return (Invoke-GraphMethod -Version 'beta' -Query "windowsPhone81SCEPCertificateProfiles/$($this.Id)/managedDeviceCertificateStates") } } Class microsoft_graph_windows81GeneralConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$browserBlockSendingDoNotTrackHeader; [object]$browserIntranetSecurityLevel; [object]$storageRequireDeviceEncryption; [object]$accountsBlockAddingNonMicrosoftAccountEmail; [object]$browserBlockPlugins; [object]$browserTrustedSitesSecurityLevel; [object]$workFoldersUrl; [object]$browserRequireFraudWarning; [object]$cellularBlockDataRoaming; [object]$browserInternetSecurityLevel; [object]$minimumAutoInstallClassification; [object]$browserBlockAutofill; [object]$browserRequireFirewall; [object]$browserBlockPopups; [object]$diagnosticsBlockDataSubmission; [object]$browserBlockJavaScript; [object]$browserLoggingReportLocation; [object]$passwordExpirationDays; [object]$browserRequireSmartScreen; [object]$browserBlockEnterpriseModeAccess; [object]$browserRequireHighSecurityForRestrictedSites; [object]$passwordMinimumLength; [object]$browserBlockAutomaticDetectionOfIntranetSites; [object]$passwordSignInFailureCountBeforeFactoryReset; [object]$passwordBlockPicturePasswordAndPin; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$applyOnlyToWindows81; [object]$updatesRequireAutomaticUpdates; [object]$userAccountControlSettings; [object]$browserEnterpriseModeSiteListLocation; [object]$passwordPreviousPasswordBlockCount; [object]$passwordRequiredType; [object]$browserBlockSingleWordEntryOnIntranetSites; [object]$passwordMinimumCharacterSetCount; } Class microsoft_graph_windowsPhone81GeneralConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$appsBlockCopyPaste; [object]$cellularBlockWifiTethering; [object]$windowsStoreBlocked; [object]$storageRequireEncryption; [object]$nfcBlocked; [object]$diagnosticDataBlockSubmission; [object]$emailBlockAddingAccounts; [object]$cameraBlocked; [object]$compliantAppsList; [object]$microsoftAccountBlocked; [object]$compliantAppListType; [object]$webBrowserBlocked; [object]$bluetoothBlocked; [object]$passwordBlockSimple; [object]$passwordExpirationDays; [object]$wifiBlockHotspotReporting; [object]$storageBlockRemovableStorage; [object]$wifiBlockAutomaticConnectHotspots; [object]$screenCaptureBlocked; [object]$passwordRequired; [object]$passwordMinimumLength; [object]$passwordSignInFailureCountBeforeFactoryReset; [object]$wifiBlocked; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$locationServicesBlocked; [object]$passwordPreviousPasswordBlockCount; [object]$applyOnlyToWindowsPhone81; [object]$passwordRequiredType; [object]$passwordMinimumCharacterSetCount; } Class microsoft_graph_windows10GeneralConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$defenderScheduledQuickScanTime; [object]$automaticUpdateMode; [object]$cellularBlockVpnWhenRoaming; [object]$defenderScanIncomingMail; [object]$automaticUpdateSchedule; [object]$defenderRequireRealTimeMonitoring; [object]$edgeFirstRunUrl; [object]$edgeSearchEngine; [object]$settingsBlockUpdateSecurityPage; [object]$startBlockUnpinningAppsFromTaskbar; [object]$smartScreenBlockPromptOverride; [object]$settingsBlockAccountsPage; [object]$passwordRequiredType; [object]$settingsBlockChangeLanguage; [object]$certificatesBlockManualRootCertificateInstallation; [object]$edgeHomepageUrls; [object]$edgeBlockInPrivateBrowsing; [object]$gameDvrBlocked; [object]$edgeBlockPopups; [object]$automaticUpdateTime; [object]$wiFiBlocked; [object]$settingsBlockNetworkInternetPage; [object]$microsoftAccountBlocked; [object]$developerUnlockSetting; [object]$accountsBlockAddingNonMicrosoftAccountEmail; [object]$smartScreenBlockPromptOverrideForFiles; [object]$settingsBlockEaseOfAccessPage; [object]$bluetoothBlockAdvertising; [object]$edgeBlockJavaScript; [object]$settingsBlockPrivacyPage; [object]$settingsBlockEditDeviceName; [object]$defenderProcessesToExclude; [object]$edgeCookiePolicy; [object]$defenderMonitorFileActivity; [object]$passwordSignInFailureCountBeforeFactoryReset; [object]$resetProtectionModeBlocked; [object]$settingsBlockChangeRegion; [object]$defenderScheduledScanTime; [object]$copyPasteBlocked; [object]$oneDriveDisableFileSync; [object]$voiceRecordingBlocked; [object]$edgeBlockSearchSuggestions; [object]$edgeBlockAccessToAboutFlags; [object]$defenderScanDownloads; [object]$bluetoothBlocked; [object]$defenderBlockEndUserAccess; [object]$passwordMinimumLength; [object]$windowsStoreEnablePrivateStoreOnly; [object]$edgeEnterpriseModeSiteListLocation; [object]$startMenuLayoutXml; [object]$edgeBlockAutofill; [object]$passwordExpirationDays; [object]$edgeRequireSmartScreen; [object]$screenCaptureBlocked; [object]$startMenuMode; [object]$defenderScanRemovableDrivesDuringFullScan; [object]$storageRequireMobileDeviceEncryption; [object]$nfcBlocked; [object]$settingsBlockPersonalizationPage; [object]$defenderRequireBehaviorMonitoring; [object]$lockScreenBlockActionCenterNotifications; [object]$defenderScanType; [object]$prereleaseFeatures; [object]$microsoftAccountBlockSettingsSync; [object]$passwordMinimumCharacterSetCount; [object]$defenderScanMaxCpu; [object]$wiFiBlockManualConfiguration; [object]$appsBlockWindowsStoreOriginatedApps; [object]$deviceManagementBlockManualUnenroll; [object]$edgeBlockPasswordManager; [object]$defenderScanScriptsLoadedInInternetExplorer; [object]$diagnosticsDataSubmissionMode; [object]$edgeBlockSendingDoNotTrackHeader; [object]$defenderPromptForSampleSubmission; [object]$cellularBlockVpn; [object]$settingsBlockChangeSystemTime; [object]$passwordRequired; [object]$safeSearchFilter; [object]$usbBlocked; [object]$appsAllowTrustedAppsSideloading; [object]$cortanaBlocked; [object]$logonBlockFastUserSwitching; [object]$experienceBlockConsumerSpecificFeatures; [object]$defenderRequireNetworkInspectionSystem; [object]$experienceBlockWindowsTips; [object]$settingsBlockAddProvisioningPackage; [object]$defenderRequireCloudProtection; [object]$settingsBlockTimeLanguagePage; [object]$passwordMinutesOfInactivityBeforeScreenTimeout; [object]$settingsBlockSettingsApp; [object]$edgeBlocked; [object]$edgeBlockExtensions; [object]$defenderScanNetworkFiles; [object]$edgeBlockDeveloperTools; [object]$bluetoothBlockDiscoverableMode; [object]$sharedUserAppDataAllowed; [object]$defenderScanMappedNetworkDrivesDuringFullScan; [object]$cameraBlocked; [object]$antiTheftModeBlocked; [object]$windowsStoreBlocked; [object]$settingsBlockSystemPage; [object]$defenderFileExtensionsToExclude; [object]$locationServicesBlocked; [object]$internetSharingBlocked; [object]$webRtcBlockLocalhostIpAddress; [object]$defenderFilesAndFoldersToExclude; [object]$settingsBlockChangePowerSleep; [object]$defenderDaysBeforeDeletingQuarantinedMalware; [object]$storageRestrictAppInstallToSystemVolume; [object]$storageRestrictAppDataToSystemVolume; [object]$defenderScanArchiveFiles; [object]$wiFiBlockAutomaticConnectHotspots; [object]$deviceManagementBlockFactoryResetOnMobile; [object]$settingsBlockRemoveProvisioningPackage; [object]$passwordRequireWhenResumeFromIdleState; [object]$edgeBlockSendingIntranetTrafficToInternetExplorer; [object]$cellularBlockDataWhenRoaming; [object]$experienceBlockWindowsSpotlight; [object]$storageBlockRemovableStorage; [object]$settingsBlockDevicesPage; [object]$windowsStoreBlockAutoUpdate; [object]$defenderSystemScanSchedule; [object]$defenderSignatureUpdateIntervalInHours; [object]$passwordPreviousPasswordBlockCount; } Class microsoft_graph_windows10TeamGeneralConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$welcomeScreenMeetingInformation; [object]$maintenanceWindowDurationInHours; [object]$miracastChannel; [object]$maintenanceWindowStartTime; [object]$azureOperationalInsightsWorkspaceId; [object]$maintenanceWindowBlocked; [object]$azureOperationalInsightsWorkspaceKey; [object]$miracastRequirePin; [object]$azureOperationalInsightsBlockTelemetry; [object]$miracastBlocked; [object]$welcomeScreenBackgroundImageUrl; [object]$welcomeScreenBlockAutomaticWakeUp; } Class microsoft_graph_editionUpgradeConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$license; [object]$productKey; [object]$targetEdition; [object]$licenseType; } Class microsoft_graph_windowsDefenderAdvancedThreatProtectionConfiguration_beta : microsoft_graph_deviceConfiguration_beta { [object]$advancedThreatProtectionOffboardingBlob; [object]$advancedThreatProtectionOnboardingBlob; [object]$allowSampleSharing; } Class microsoft_graph_localizedNotificationMessage_beta : microsoft_graph_entity_beta { [object]$subject; [object]$lastModifiedDateTime; [object]$isDefault; [object]$messageTemplate; [object]$locale; } Class microsoft_graph_androidCompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$deviceThreatProtectionEnabled; [object]$passwordMinutesOfInactivityBeforeLock; [object]$minAndroidSecurityPatchLevel; [object]$osMaximumVersion; [object]$passwordRequired; [object]$storageRequireEncryption; [object]$securityDisableUsbDebugging; [object]$deviceThreatProtectionRequiredSecurityLevel; [object]$osMinimumVersion; [object]$passwordPreviousPasswordBlockCount; [object]$passwordRequiredType; [object]$securityBlockJailbrokenDevices; [object]$securityPreventInstallAppsFromUnknownSources; [object]$passwordExpirationDays; [object]$passwordMinimumLength; [object]$requireAppVerify; } Class microsoft_graph_iosCompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passcodeBlockSimple; [object]$passcodeMinutesOfInactivityBeforeLock; [object]$passcodeMinimumCharacterSetCount; [object]$deviceThreatProtectionRequiredSecurityLevel; [object]$passcodeExpirationDays; [object]$osMaximumVersion; [object]$osMinimumVersion; [object]$passcodeRequired; [object]$passcodePreviousPasscodeBlockCount; [object]$securityBlockJailbrokenDevices; [object]$passcodeRequiredType; [object]$passcodeMinimumLength; [object]$deviceThreatProtectionEnabled; [object]$managedEmailProfileRequired; } Class microsoft_graph_macOSCompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passwordMinutesOfInactivityBeforeLock; [object]$storageRequireEncryption; [object]$passwordRequired; [object]$passwordMinimumCharacterSetCount; [object]$osMaximumVersion; [object]$osMinimumVersion; [object]$passwordRequiredType; [object]$deviceThreatProtectionRequiredSecurityLevel; [object]$passwordBlockSimple; [object]$passwordPreviousPasswordBlockCount; [object]$passwordExpirationDays; [object]$passwordMinimumLength; [object]$deviceThreatProtectionEnabled; } Class microsoft_graph_windows10CompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passwordMinutesOfInactivityBeforeLock; [object]$passwordMinimumLength; [object]$earlyLaunchAntiMalwareDriverEnabled; [object]$passwordRequired; [object]$passwordMinimumCharacterSetCount; [object]$osMaximumVersion; [object]$osMinimumVersion; [object]$codeIntegrityEnabled; [object]$passwordRequiredType; [object]$passwordRequiredToUnlockFromIdle; [object]$mobileOsMinimumVersion; [object]$bitLockerEnabled; [object]$passwordBlockSimple; [object]$passwordPreviousPasswordBlockCount; [object]$secureBootEnabled; [object]$mobileOsMaximumVersion; [object]$passwordExpirationDays; [object]$requireHealthyDeviceReport; [object]$storageRequireEncryption; } Class microsoft_graph_windows10MobileCompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passwordMinutesOfInactivityBeforeLock; [object]$passwordRequired; [object]$earlyLaunchAntiMalwareDriverEnabled; [object]$passwordRequireToUnlockFromIdle; [object]$passwordMinimumCharacterSetCount; [object]$osMaximumVersion; [object]$osMinimumVersion; [object]$codeIntegrityEnabled; [object]$passwordPreviousPasswordBlockCount; [object]$passwordRequiredType; [object]$bitLockerEnabled; [object]$passwordBlockSimple; [object]$secureBootEnabled; [object]$passwordExpirationDays; [object]$passwordMinimumLength; [object]$storageRequireEncryption; } Class microsoft_graph_windows81CompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passwordRequired; [object]$osMinimumVersion; [object]$passwordMinutesOfInactivityBeforeLock; [object]$passwordPreviousPasswordBlockCount; [object]$passwordMinimumCharacterSetCount; [object]$storageRequireEncryption; [object]$passwordBlockSimple; [object]$passwordExpirationDays; [object]$passwordRequiredType; [object]$osMaximumVersion; [object]$passwordMinimumLength; } Class microsoft_graph_windowsPhone81CompliancePolicy_beta : microsoft_graph_deviceCompliancePolicy_beta { [object]$passwordRequired; [object]$osMinimumVersion; [object]$passwordMinutesOfInactivityBeforeLock; [object]$passwordPreviousPasswordBlockCount; [object]$passwordMinimumCharacterSetCount; [object]$storageRequireEncryption; [object]$passwordBlockSimple; [object]$passwordExpirationDays; [object]$passwordRequiredType; [object]$osMaximumVersion; [object]$passwordMinimumLength; } Class microsoft_graph_onPremisesConditionalAccessSettings_beta : microsoft_graph_entity_beta { [object]$includedGroups; [object]$excludedGroups; [object]$enabled; } Class microsoft_graph_mobileAppIdentifierDeployment_beta : microsoft_graph_entity_beta { [object]$version; [object]$mobileAppIdentifier; } Class microsoft_graph_managedAppPolicyDeploymentSummary_beta : microsoft_graph_entity_beta { [object]$configurationDeploymentSummaryPerApp; [object]$configurationDeployedUserCount; [object]$displayName; [object]$version; [object]$lastRefreshTime; } Class microsoft_graph_managedAppOperation_beta : microsoft_graph_entity_beta { [object]$lastModifiedDateTime; [object]$displayName; [object]$version; [object]$state; } Class microsoft_graph_windowsInformationProtectionAppLockerFile_beta : microsoft_graph_entity_beta { [object]$fileHash; [object]$displayName; [object]$file; [object]$version; } Class microsoft_graph_iosManagedAppRegistration_beta : microsoft_graph_managedAppRegistration_beta { } Class microsoft_graph_androidManagedAppRegistration_beta : microsoft_graph_managedAppRegistration_beta { } Class microsoft_graph_managedAppStatusRaw_beta : microsoft_graph_managedAppStatus_beta { [object]$content; } Class microsoft_graph_reportRoot_beta : microsoft_graph_entity_beta { }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/MetadataExplorer/MetadataExplorer.ps1
MetadataExplorer.ps1
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase Function New-GraphXAMLClass { Param ( $ClassName, $ClassHash ) $Class = @" using System.ComponentModel; using System.Windows; public class $ClassName : INotifyPropertyChanged { "@ Foreach ($Key in $ClassHash.Keys) { $ClassType = $ClassHash[$Key] $Class = $Class + @" private $ClassType private$Key; public $ClassType $key { get { return private$Key; } set { private$Key = value; NotifyPropertyChanged("$Key"); } } "@ } $Class = $Class + @" public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string property) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } "@ try { $null = Add-Type -Language CSharp $Class -ErrorAction SilentlyContinue } catch { } } Function Add-GraphTreeItem { param( $Name, $Parent, $Tag ) $NewItem = New-Object System.Windows.Controls.TreeViewItem $NewItem.Header = $Name $NewItem.Tag = $Tag $Null = $Parent.Items.Add($NewItem) } Function Set-GraphTreeViewVisibility { Param( $FilterText, $TreeItem ) if($TreeItem.Items.Count -eq 0) { if([string]::IsNullOrEmpty($FilterText)) { $TreeItem.Visibility = [System.Windows.Visibility]::Visible } elseif($TreeItem.Header.ToLower().contains($FilterText.ToLower())) { $TreeItem.Visibility = [System.Windows.Visibility]::Visible } else { $TreeItem.Visibility = [System.Windows.Visibility]::Collapsed } } else { foreach($instance in $TreeItem.Items) { Set-GraphTreeViewVisibility -FilterText $FilterText -TreeItem $instance } } } Function Add-GraphMetadataTree { Param( $type, $metadata, $parent, $datahash ) $ParentGuid = (New-Guid).Guid $tempparenttype = New-Object System.Windows.Controls.TreeViewItem $tempparenttype.Header = $type $tempparenttype.Tag = $ParentGuid $datahash[$ParentGuid] = $metadata."$type" $SortArray = New-Object System.Collections.ArrayList if($type -eq 'EntityContainer') { $LoopObjects = $metadata.EntityContainer.EntitySet } else { $LoopObjects = $metadata."$type" } foreach($instance in $LoopObjects) { $tempobject = New-Object SortProperties if($type -eq 'Annotations') { $tempobject.Name = $instance.Target $tempobject.Value = $instance $null = $SortArray.Add($tempobject) } elseif(($type -eq 'Action') -or ($type -eq 'Function')) { $tempobject.Name = $instance.Name $tempobject.Value = $instance foreach($Param in $instance.Parameter){ if(($Param.Name -eq 'bindingParameter') -or ($Param.Name -eq 'bindParameter')) { $tempobject.bindingparameter = $Param.Type } } $null = $SortArray.Add($tempobject) } else { $tempobject.Name = $instance.Name $tempobject.Value = $instance $null = $SortArray.Add($tempobject) } } $SortArray = $SortArray | Sort-Object -Property Name foreach($instance in $SortArray) { $tempguid = (New-Guid).Guid $NodeName = $instance.Name if(($type -eq 'Action') -or ($type -eq 'Function')) { $NodeName = "$($instance.Name) - $($instance.BindingParameter)" } elseif($type -eq 'EntityContainer'){ $ExampleCodeHash[$tempguid] = @" # Sample code automatically generated! # This will hopefully give you workable examples for the MSGraphAPI cmdlets #Should return a type of $($instance.Value.EntityType) - You can view the properties of this in EntityType `$Objects = Invoke-GraphMethod -Query "$($instance.Name)" "@ $NavCode = '' foreach($navprop in $instance.Value.NavigationPropertyBinding) { if([string]::IsNullOrEmpty($NavCode)) { $NavCode = 'foreach($Object in $Objects) {' } $NavCode = $NavCode + "`n Invoke-GraphMethod -Query `"$($instance.Name)/`$(`$Object.Id)/$($navprop.Path)`"" } if(-not [string]::IsNullOrEmpty($NavCode)) { $NavCode = $NavCode + "`n}" $ExampleCodeHash[$tempguid] = $ExampleCodeHash[$tempguid] + $NavCode } } $null = Add-GraphTreeItem -Name $NodeName -Parent $tempparenttype -Tag $tempguid $DataHash[$tempguid] = $instance.Value } $null = $parent.Items.Add($tempparenttype) return $datahash } [xml]$xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Graph PS Explorer" Height="550" Width="725"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="30"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> <ColumnDefinition Width="75"/> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Tenant Name:"/> <TextBox Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Margin="2" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" Text="{Binding Path=TenantName}"/> <Button Name="Btn_Connect" Content="Connect" Grid.Row="0" Grid.Column="3" Margin="3"/> <Label Content="{Binding LabelTenantUser}" Grid.Row="0" Grid.Column="4" Grid.ColumnSpan="3" VerticalAlignment="Center"/> <Label Grid.Row="1" Grid.Column="0" Content="Filter:" HorizontalAlignment="Right" VerticalAlignment="Center"/> <TextBox Name="Txt_Filter" Grid.Row="1" Grid.Column="1" Margin="2" VerticalContentAlignment="Center" Text="{Binding Filter}"/> <TabControl Grid.Row="1" Grid.Column="2" Grid.RowSpan="2" Grid.ColumnSpan="4"> <TabItem Header="Properties" Name="Tab_Properties"> <DataGrid IsReadOnly="True" CanUserAddRows="False" ItemsSource="{Binding PropertiesGrid, Mode=TwoWay}"/> </TabItem> <TabItem Header="Navigation Properties" Name="Tab_NavigationProperties"> <DataGrid IsReadOnly="True" CanUserAddRows="False" ItemsSource="{Binding NavigationPropertiesGrid, Mode=TwoWay}"/> </TabItem> <TabItem Header="Members" Name="Tab_Members"> <DataGrid IsReadOnly="True" CanUserAddRows="False" ItemsSource="{Binding MemberGrid, Mode=TwoWay}"/> </TabItem> <TabItem Header="Parameters" Name="Tab_Parameters"> <DataGrid IsReadOnly="True" CanUserAddRows="False" ItemsSource="{Binding ParameterGrid, Mode=TwoWay}"/> </TabItem> <TabItem Header="Annotations" Name="Tab_Annotations"> <DataGrid IsReadOnly="True" CanUserAddRows="False" ItemsSource="{Binding AnnotationGrid, Mode=TwoWay}"/> </TabItem> <TabItem Header="Raw Data"> <TextBox IsReadOnly="True" Text="{Binding RawData}" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto"/> </TabItem> <TabItem Header="Example Code" Name="Tab_ExampleCode"> <TextBox IsReadOnly="True" Text="{Binding ExampleCode}" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto"/> </TabItem> </TabControl> <TreeView Name="MDTree" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding MetaDataTree}"/> <Expander Grid.Row="3" Header="Log" Grid.Column="0" Grid.ColumnSpan="10"> <TextBox Height="100" IsReadOnly="True" Text="{Binding Log}" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto"/> </Expander> </Grid> </Window> '@ $v1Metadata = Get-GraphMetadata -Version 'v1.0' $BetaMetadata = Get-GraphMetadata -Version 'Beta' $WindowClassHash = @{ 'TenantName' = 'string' 'LabelTenantUser' = 'string' 'Filter' = 'string' 'PropertiesGrid' = 'object' 'NavigationPropertiesGrid' = 'object' 'MemberGrid' = 'object' 'ParameterGrid' = 'object' 'AnnotationGrid' = 'object' 'RawData' = 'string' 'ExampleCode' = 'string' 'MetaDataTree' = 'object' 'Log' = 'string' } New-GraphXAMLClass -ClassName 'WindowClass' -ClassHash $WindowClassHash $AnnotationGridClassHash = @{ 'Term' = 'string' 'Record' = 'string' } New-GraphXAMLClass -ClassName 'AnnotationGridClass' -ClassHash $AnnotationGridClassHash $MemberGridClassHash = @{ 'Name'='string' 'value' = 'string' } New-GraphXAMLClass -ClassName 'MemberGridClass' -ClassHash $MemberGridClassHash $PropertyGridClassHash = @{ 'Name'='string' 'Type' = 'string' 'Unicode' = 'string' 'Nullable' = 'string' } New-GraphXAMLClass -ClassName 'PropertyGridClass' -ClassHash $PropertyGridClassHash $NavigationPropertyGridClassHash = @{ 'Name'='string' 'Type' = 'string' } New-GraphXAMLClass -ClassName 'NavigationPropertyGridClass' -ClassHash $NavigationPropertyGridClassHash $ParameterGridClassHash = @{ 'Name'='string' 'Type' = 'string' 'Nullable' = 'string' } New-GraphXAMLClass -ClassName 'ParameterGridClass' -ClassHash $ParameterGridClassHash Class SortProperties { [string]$Name [string]$BindingParameter [object]$Value } $Window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml)) $xaml.SelectNodes("//*[@Name]") | Foreach-Object { Set-Variable -Name (("Window" + "_" + $_.Name)) -Value $Window.FindName($_.Name) } $WindowDataContext = New-Object -TypeName WindowClass $Window.DataContext = $WindowDataContext $WindowDataContext.TenantName = $Global:GraphAuthenticationHash.Parameters.TenantName $WindowDataContext.LabelTenantUser = "User: $($Global:GraphAuthenticationHash.Parameters.Credential.UserName)" $Window_Btn_Connect.Visibility = [System.Windows.Visibility]::Hidden $Window_MDTree.Add_SelectedItemChanged({ $SelItem = $Window_MDTree.SelectedItem if(-not [string]::IsNullOrEmpty($SelItem.Tag)) { $metadata = $DataHash[$SelItem.Tag] $WindowDataContext.RawData = '' foreach($instance in $metadata){ [xml]$OuterXML = $instance.outerxml $StringWriter = New-Object System.IO.StringWriter $XMLWriter = New-Object System.Xml.XmlTextWriter $StringWriter $XMLWriter.Formatting = 'indented' $XMLWriter.Indentation = 2 $OuterXML.WriteContentTo($XMLWriter) $XMLWriter.Flush() $StringWriter.Flush() $WindowDataContext.RawData = "$($WindowDataContext.RawData)" + "$($StringWriter.ToString())`n" } if($metadata.Annotation -and (($metadata.GetType()).Name -ne 'Object[]')) { $Window_Tab_Annotations.Visibility = [System.Windows.Visibility]::Visible $AnnotationsGrid = New-Object System.Collections.ArrayList foreach($Annotation in $metadata.Annotation) { $tempobject = New-Object -TypeName 'AnnotationGridClass' $tempobject.Term = $Annotation.Term.ToString() $tempobject.Record = "$($Annotation.Record.PropertyValue.Property)=$($Annotation.Record.PropertyValue.Bool)" $null = $AnnotationsGrid.Add($tempobject) } $WindowDataContext.AnnotationGrid = $AnnotationsGrid } else { $Window_Tab_Annotations.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.AnnotationGrid = $null } if($metadata.Member -and (($metadata.GetType()).Name -ne 'Object[]')) { $Window_Tab_Members.Visibility = [System.Windows.Visibility]::Visible $MembersGrid = New-Object System.Collections.ArrayList foreach($Member in $metadata.Member) { $tempobject = New-Object -TypeName 'MemberGridClass' $tempobject.Name = $Member.Name $tempobject.Value = $Member.Value $null = $MembersGrid.Add($tempobject) } $WindowDataContext.MemberGrid = $MembersGrid } else { $Window_Tab_Members.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.MemberGrid = $null } if($metadata.Property -and (($metadata.GetType()).Name -ne 'Object[]')) { $Window_Tab_Properties.Visibility = [System.Windows.Visibility]::Visible $PropertiesGrid = New-Object System.Collections.ArrayList foreach($Property in $metadata.Property) { $tempobject = New-Object -TypeName 'PropertyGridClass' $tempobject.Name = $Property.Name $tempobject.Type = $Property.Type $tempobject.Unicode = $Property.Unicode $tempobject.Nullable = $Property.Nullable $null = $PropertiesGrid.Add($tempobject) } $WindowDataContext.PropertiesGrid = $PropertiesGrid } else { $Window_Tab_Properties.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.PropertiesGrid = $null } if($metadata.NavigationProperty -and (($metadata.GetType()).Name -ne 'Object[]')) { $Window_Tab_NavigationProperties.Visibility = [System.Windows.Visibility]::Visible $NavigationPropertiesGrid = New-Object System.Collections.ArrayList foreach($Property in $metadata.NavigationProperty) { $tempobject = New-Object -TypeName 'NavigationPropertyGridClass' $tempobject.Name = $Property.Name $tempobject.Type = $Property.Type $null = $NavigationPropertiesGrid.Add($tempobject) } $WindowDataContext.NavigationPropertiesGrid = $NavigationPropertiesGrid } else { $Window_Tab_NavigationProperties.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.NavigationPropertiesGrid = $null } if($metadata.Parameter -and (($metadata.GetType()).Name -ne 'Object[]')) { $Window_Tab_Parameters.Visibility = [System.Windows.Visibility]::Visible $ParametersGrid = New-Object System.Collections.ArrayList foreach($Parameter in $metadata.Parameter) { $tempobject = New-Object -TypeName 'ParameterGridClass' $tempobject.Name = $Parameter.Name $tempobject.Type = $Parameter.Type $tempobject.Nullable = $Parameter.Nullable $null = $ParametersGrid.Add($tempobject) } $WindowDataContext.ParameterGrid = $ParametersGrid } else { $Window_Tab_Parameters.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.ParameterGrid = $null } if($ExampleCodeHash[$SelItem.Tag]) { $WindowDataContext.ExampleCode = $ExampleCodeHash[$SelItem.Tag] } else { $Window_Tab_ExampleCode.Visibility = [System.Windows.Visibility]::Collapsed $WindowDataContext.ExampleCode = '' } } }) $Window_Txt_Filter.Add_TextChanged({ Set-GraphTreeViewVisibility -FilterText $Window_Txt_Filter.Text -TreeItem $Window_MDTree }) $DataHash = @{} $ExampleCodeHash = @{} $v1TreeRoot = New-Object System.Windows.Controls.TreeViewItem $v1TreeRoot.Header = 'v1' $v1Guid = (New-Guid).Guid $v1TreeRoot.Tag = $v1Guid $DataHash[$v1Guid] = $v1Metadata $betaTreeRoot = New-Object System.Windows.Controls.TreeViewItem $betaTreeRoot.Header = 'beta' $betaGuid = (New-Guid).Guid $betaTreeRoot.Tag = $betaGuid $DataHash[$betaGuid] = $BetaMetadata $DataHash = Add-GraphMetadataTree -type 'EnumType' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'EntityType' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'ComplexType' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Action' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Function' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'EntityContainer' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Annotations' -metadata $v1Metadata -parent $v1TreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'EnumType' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'EntityType' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'ComplexType' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Action' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Function' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'EntityContainer' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $DataHash = Add-GraphMetadataTree -type 'Annotations' -metadata $BetaMetadata -parent $betaTreeRoot -datahash $DataHash $null = $Window_MDTree.Items.Add($v1TreeRoot) $null = $Window_MDTree.Items.Add($betaTreeRoot) $Window.ShowDialog() | Out-Null
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/AzureAD/AzureAD-Device.ps1
AzureAD-Device.ps1
Function Get-GraphDevices { <# .SYNOPSIS Will get all the devices by querying Microsoft Graph .DESCRIPTION Queries for devices .EXAMPLE Get-GraphDevices This will list all devices the authenticated user can see in Azure .PARAMETER Filter This parameter will allow you to search for a device by name .PARAMETER DeviceId Specify the Id of the Device to get only one Id .PARAMETER GraphVersion By default this only searches for devices in v1.0. If you want to access the beta features, use Beta .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/device_list .Notes Author: Ryan Ephgrave #> Param( [string]$Filter, [string]$DeviceId, [string]$GraphVersion = 'v1.0' ) try { if(-not [string]::IsNullOrEmpty($DeviceId)) { Invoke-GraphMethod -query "devices/$($DeviceId)" -filter $Filter -Version $GraphVersion } else { $Params = @{ 'query'='Devices' 'version'=$GraphVersion } if(-not [string]::IsNullOrEmpty($Filter)) {$Params['filter'] = $Filter} Invoke-GraphMethod @Params } } catch { throw $_ } }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/AzureAD/AzureAD-Group.ps1
AzureAD-Group.ps1
Function Get-GraphGroup { <# .SYNOPSIS Querys the Groups endpoint to get a list of Azure AD groups .DESCRIPTION Queries groups in Azure AD .EXAMPLE Get-GraphGroups -Filter "startswith(displayName,'Sec')" .PARAMETER Filter Use OData filter query. Additional documentation found here: https://developer.microsoft.com/en-us/graph/docs/overview/query_parameters .PARAMETER GroupId Query a specific group by Id .PARAMETER GraphVersion Graph version to query. Acceptible values are v1.0 or beta .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_list .Notes Author: Ryan Ephgrave #> Param( [string]$Filter, [string]$GroupId, [string]$GraphVersion = 'v1.0' ) try { if(-not [string]::IsNullOrEmpty($GroupId)) { Invoke-GraphMethod -query "groups/$($GroupId)" -filter $Filter -Version $GraphVersion } else { $Params = @{ 'query'='groups' 'version'=$GraphVersion } if(-not [string]::IsNullOrEmpty($Filter)) {$Params['filter'] = $Filter} Invoke-GraphMethod @Params } } catch { Write-Error -Message $_.Exception.Message } } Function New-GraphGroup { <# .SYNOPSIS Will create a new instance of Group .DESCRIPTION Will create a new instance of Group .EXAMPLE New-GraphGroup -PropertyHash ParamHash .PARAMETER PropertyHash Hashtable of properties to set .PARAMETER GraphVersion Version of graph .PARAMETER displayName The name to display in the address book for the group. .PARAMETER mailEnabled Set to true for mail-enabled groups. Set this to true if creating an Office 365 group. Set this to false if creating dynamic or security group. .PARAMETER mailNickname The mail alias for the group. .PARAMETER securityEnabled Set to true for security-enabled groups. Set this to true if creating a dynamic or security group. Set this to false if creating an Office 365 group. .Notes Author: Ryan Ephgrave #> Param( [Parameter(Mandatory=$false)] [hashtable]$PropertyHash, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$GraphVersion = 'v1.0', [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$displayName, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Nullable[bool]]$mailEnabled, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$mailNickname, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Nullable[bool]]$securityEnabled, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string[]]$groupTypes, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$description ) $BodyHash = @{} if($PropertyHash) { $BodyHash = $PropertyHash } if(-not [string]::IsNullOrEmpty($displayName)) { $BodyHash['displayName'] = $displayName } if(-not [string]::IsNullOrEmpty($mailEnabled)) { $BodyHash['mailEnabled'] = $mailEnabled } if(-not [string]::IsNullOrEmpty($mailNickname)) { $BodyHash['mailNickname'] = $mailNickname } if(-not [string]::IsNullOrEmpty($securityEnabled)) { $BodyHash['securityEnabled'] = $securityEnabled } if(-not [string]::IsNullOrEmpty($groupTypes)) { $BodyHash['groupTypes'] = $groupTypes } if(-not [string]::IsNullOrEmpty($description)) { $BodyHash['description'] = $description } $BodyJson = ConvertTo-Json -InputObject $BodyHash Invoke-GraphMethod -method 'Post' -query 'Groups' -body $BodyJson -ContentType 'application/json' } Function Set-GraphGroup { <# .SYNOPSIS Will update a Group .DESCRIPTION Will update a Group .EXAMPLE Set-GraphGroup -PropertyHash ParamHash .PARAMETER PropertyHash Hashtable of properties to set .PARAMETER GraphVersion Version of graph .Notes Author: Ryan Ephgrave #> Param( [Parameter(Mandatory=$false)] [hashtable]$PropertyHash, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$GraphVersion = 'v1.0' ) $BodyHash = @{} if($PropertyHash) { $BodyHash = $PropertyHash } $BodyJSON = $BodyHash | ConvertTo-Json -Depth 10 Invoke-GraphMethod -method 'Patch' -query 'Groups' -body $BodyHash -ContentType 'application/json' }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/AzureAD/AzureAD-User.ps1
AzureAD-User.ps1
Function Get-GraphUsers { <# .SYNOPSIS Used to get a list of users in Azure AD .DESCRIPTION Queries Graph /users to get information on users in Azure AD .EXAMPLE Get-GraphUsers -Filter "startswith(displayName,'Sec')" .PARAMETER Filter Use OData filter query. Additional documentation found here: https://developer.microsoft.com/en-us/graph/docs/overview/query_parameters .PARAMETER UserId Query a specific user by Id .PARAMETER GraphVersion Graph version to query. Acceptible values are v1.0 or beta .PARAMETER SelectProperties List of properties to retrieve. Not all properties come by default, like assignedLicenses .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user .Notes Author: Ryan Ephgrave #> Param( [string]$Filter, [string]$UserId, [string]$GraphVersion = 'v1.0', [string[]]$SelectProperties ) try { $ParamHash = @{ 'Version'=$GraphVersion } if(-not [string]::IsNullOrEmpty($UserId)) { $UserId = $UserId.Replace('@','%40') $ParamHash['query'] = "users/$($UserId)" } else { $ParamHash['query'] = 'users' } if(-not [string]::IsNullOrEmpty($Filter)){ $ParamHash['filter'] = $Filter } if(-not [string]::IsNullOrEmpty($SelectProperties)){ $SelectString = '' foreach($instance in $SelectProperties) { $SelectString = $SelectString + ",$($instance)" } $SelectString = $SelectString.TrimStart(',') $ParamHash['Select'] = $SelectString } Invoke-GraphMethod @ParamHash } catch { throw $_ } } Function New-GraphUser { <# .SYNOPSIS Will create a new user through Graph in Azure AD .DESCRIPTION Can create a user with properties .EXAMPLE New-GraphUser -userPrincipalName 'Ryan@Tenant.onmicrosoft.com' -displayName 'Ryan Ephgrave' -Pass 'MyTestPass' -MailNickName 'Ryan.Mailbox' .PARAMETER accountEnabled Create the account as enabled. .PARAMETER userPrincipalName The user principal name (someuser@contoso.com). .PARAMETER displayName The name to display in the address book for the user. .PARAMETER Pass The password for the user. This property is required when a user is created. It can be updated, but the user will be required to change the password on the next login. The password must satisfy minimum requirements as specified by the user’s passwordPolicies property. By default, a strong password is required. .PARAMETER forceChangePasswordNextLogin true if the user must change her password on the next login; otherwise false. .PARAMETER MailNickName The mail alias for the user. .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_post_users .Notes Author: Ryan Ephgrave #> Param ( [Parameter(Mandatory=$false)] [bool]$accountEnabled = $true, [Parameter(Mandatory=$true)] [string]$userPrincipalName, [Parameter(Mandatory=$true)] [string]$displayName, [Parameter(Mandatory=$true)] [string]$Pass, [Parameter(Mandatory=$false)] [bool]$forceChangePasswordNextLogin = $true, [Parameter(Mandatory=$true)] $MailNickName ) [hashtable]$UserHashTable = @{ 'accountEnabled'=$accountEnabled 'displayName'=$displayName 'mailNickname'=$MailNickName 'userPrincipalName'=$userPrincipalName 'passwordProfile'=@{ 'password'=$Pass 'forceChangePasswordNextSignIn'=$forceChangePasswordNextLogin } } $UserJSON = $UserHashTable | ConvertTo-Json -Depth 10 Invoke-GraphMethod -Method 'Post' -query 'users' -body $UserJSON -ContentType 'application/json' }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/Directory/Directory-SubscribedSku.ps1
Directory-SubscribedSku.ps1
Function Get-GraphSubscribedSkus { <# .SYNOPSIS Will list subscribedSkus from Graph .DESCRIPTION Contains information about a service SKU that a company is subscribed to. Only the read operation is supported on subscribed SKUs; create, update, and delete are not supported. Query filter expressions are not supported. .EXAMPLE Get-GraphSubscribedSkus .PARAMETER Filter Filters results .PARAMETER Id Searches for specific SubscribedSku .PARAMETER GraphVersion Specifies the Graph version .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/subscribedsku .Notes Author: Ryan Ephgrave #> Param ( [string]$Filter, [string]$Id, [string]$GraphVersion = 'v1.0' ) try { if(-not [string]::IsNullOrEmpty($Id)) { Invoke-GraphMethod -query "subscribedskus/$($Id)" -filter $Filter -Version $GraphVersion } else { $Params = @{ 'query'='subscribedskus' 'version'=$GraphVersion } if(-not [string]::IsNullOrEmpty($Filter)) {$Params['filter'] = $Filter} Invoke-GraphMethod @Params } } catch { Write-Error -Message $_.Exception.Message } }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/Intune/Intune-DeviceCateogry.ps1
Intune-DeviceCateogry.ps1
Function New-GraphIntuneDeviceCateogry { <# .SYNOPSIS Will create a new Device Category .DESCRIPTION Calls post method to deviceManagement/deviceCategories .EXAMPLE New-GraphIntuneDeviceCateogry -DisplayName 'Category' -Description 'My description' .PARAMETER DisplayName Display name of the device category .PARAMETER Description Description of the device category .LINK https://github.com/Ryan2065/MSGraphCmdlets .Notes Author: Ryan Ephgrave #> Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$DisplayName, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Description ) $CategoryHash = @{ '@odata.type' = '#microsoft.graph.deviceCategory' 'displayName' = $DisplayName 'description' = $Description } $CategoryJSON = $CategoryHash | ConvertTo-Json -Depth 10 $GraphHash = @{ 'Method' = 'Post' 'Version' = Get-GraphIntuneVersion 'Query' = 'deviceManagement/deviceCategories' 'body' = $CategoryJSON 'ContentType' = 'application/json' } Invoke-GraphMethod @GraphHash } Function Get-GraphIntuneDeviceCateogry { <# .SYNOPSIS Retrieves Intune device categories .DESCRIPTION Calls get from deviceManagement/deviceCategories .EXAMPLE Get-GraphIntuneDeviceCateogry -DisplayName 'MyCategory' Will search for the category with display name of MyCategory .PARAMETER DisplayName Filters the results based on displayName .PARAMETER Id Retrieves a specific device category .LINK https://github.com/Ryan2065/MSGraphCmdlets .Notes Author: Ryan Ephgrave #> Param( [Parameter(ParameterSetName='DisplayName')] [ValidateNotNullOrEmpty()] [string]$DisplayName, [Parameter(ParameterSetName='Id')] [ValidateNotNullOrEmpty()] [string]$Id ) $InvokeHash = @{ query = "deviceManagement/deviceCategories" Version = Get-GraphIntuneVersion Method = 'Get' } if($DisplayName) { $InvokeHash['Search'] = "displayName:$($DisplayName)" } elseif($Id){ $InvokeHash['query'] = "deviceManagement/deviceCategories/$($Id)" } Invoke-GraphMethod @InvokeHash } Function Set-GraphIntuneDeviceCategory{ <# .SYNOPSIS Will update the device category .DESCRIPTION Calls Patch to deviceManagement/deviceCategories/ID .EXAMPLE Set-GraphIntuneDeviceCategory -Id 'GUID' -DisplayName 'My New Name' .PARAMETER Id Id of device category .PARAMETER DisplayName New display name .PARAMETER Description New description .LINK https://github.com/Ryan2065/MSGraphCmdlets .Notes Author: Ryan Ephgrave #> Param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [ValidateNotNullOrEmpty()] [string]$Id, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$DisplayName, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$Description ) Process { foreach($CategoryId in $Id){ $UpdateHash = @{} $SendPatch = $false if($DisplayName) { $UpdateHash['displayName'] = $DisplayName $SendPatch = $true } if ($Description) { $UpdateHash['description'] = $Description $SendPatch = $true } if($SendPatch){ $UpdateJSON = $UpdateHash | ConvertTo-Json -Depth 10 $InvokeHash = @{ 'query' = "deviceManagement/deviceCategories/$($CategoryId)" 'Version' = Get-GraphIntuneVersion 'Method' = 'Patch' 'body' = $UpdateJSON 'ContentType' = 'application/json' } Invoke-GraphMethod @InvokeHash } } } } Function Remove-GraphIntuneDeviceCategory { <# .SYNOPSIS Will remove the device category .DESCRIPTION Calls delete to deviceManagement/deviceCategories/Id .EXAMPLE Remove-GraphIntuneDeviceCategory -Id 'My Id' .PARAMETER Id Id of device category .Parameter Force Delete without prompting .LINK https://github.com/Ryan2065/MSGraphCmdlets .Notes Author: Ryan Ephgrave #> Param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [ValidateNotNullOrEmpty()] [string]$Id, [switch]$force ) Process { foreach($CategoryId in $Id) { $Response = 'y' if(-not $force){ $Category = Get-GraphIntuneDeviceCateogry -Id $($CategoryId) $Response = Read-Host "Do you want to remove category $($Category.displayName)? (y/n)" } if($Response -eq 'y') { $InvokeHash = @{ 'query' = "deviceManagement/deviceCategories/$($CategoryId)" 'Version' = Get-GraphIntuneVersion 'Method' = 'Delete' } Invoke-GraphMethod @InvokeHash } } } }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/Intune/Intune-VersionInfo.ps1
Intune-VersionInfo.ps1
Function Get-GraphIntuneVersion { <# .SYNOPSIS Helper function for Graph version .DESCRIPTION Help function so the version info only needs to be changed in one spot when Intune switches from beta to v1.0 .EXAMPLE Get-GraphIntuneVersion .LINK https://github.com/Ryan2065/MSGraphCmdlets .Notes Author: Ryan Ephgrave #> return 'beta' }
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/Intune/Intune-Apps.ps1
Intune-Apps.ps1
Function New-GraphIntuneApp { <# .SYNOPSIS Creates a Intune App through Graph .DESCRIPTION Creates an Intune app. Currently in Beta through Graph .EXAMPLE New-GraphIntuneApp -ApplicationType 'Android Store App' -DisplayName 'Candy Crush' -Description 'A game that shouldn't be installed many places' -publisher 'Candy Crush Publisher' -minimumSupportedAndroidOS 'v4_1' -appStoreUrl 'https://play.google.com/store/apps/details?id=com.king.candycrushsaga' .PARAMETER ApplicationType What type of application to create. .PARAMETER DisplayName The admin provided or imported title of the app. .PARAMETER Description The description of the app. .PARAMETER publisher The publisher of the app .PARAMETER appStoreUrl The app store URL for the type of app being created .PARAMETER minimumSupportedAndroidOS Minimum supported OS for the Android app .PARAMETER minimumSupportediOS Minimum supported OS for iOS app .PARAMETER iosDeviceType iOS type required for app. .PARAMETER iconType file type of icon being uploaded. .PARAMETER iconBase64 Icon content in base64 .PARAMETER isFeatured Is the icon featured. .PARAMETER WebAppURL App url for web app. .PARAMETER UseManagedBrowser Is managed browser required for web app .PARAMETER InformationURL Information URL .PARAMETER PrivacyURL Privacy URL .PARAMETER Developer Developer of application .PARAMETER Owner Owner of the application .PARAMETER Notes App notes .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/intune_apps_app_conceptual .Notes Author: Ryan Ephgrave #> [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [ValidateSet( 'Android LOB App', 'Android Store App', 'iOS LOB App', 'iOS Store App', 'Web App', 'Windows Phone 8.1 Store App', 'Windows Store App' )] [string]$ApplicationType, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$DisplayName, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Description, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$publisher, [Parameter(ParameterSetName='AndroidStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='iOSStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='WindowsPhoneStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='WindowsStoreApp', Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$appStoreUrl, [Parameter(ParameterSetName='AndroidStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='AndroidLOBApp', Mandatory=$true)] [ValidateSet( 'v4_0', 'v4_0_3', 'v4_1', 'v4_2', 'v4_3', 'v4_4', 'v5_0', 'v5_1' )] [string]$minimumSupportedAndroidOS, [Parameter(ParameterSetName='iOSStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='iOSLOBApp', Mandatory=$true)] [ValidateSet( 'v8_0', 'v9_0', 'v10_0' )] [string]$minimumSupportediOS, [Parameter(ParameterSetName='iOSStoreApp', Mandatory=$true)] [Parameter(ParameterSetName='iOSLOBApp', Mandatory=$true)] [ValidateSet( 'iPad', 'iPhone', 'Both' )] [string]$iosDeviceType, [string]$iconType, [string]$iconBase64, [bool]$isFeatured = $false, [Parameter(ParameterSetName='WebApp', Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$WebAppURL, [Parameter(ParameterSetName='WebApp', Mandatory=$false)] [bool]$UseManagedBrowser, [ValidateNotNullOrEmpty()] [string]$InformationURL, [ValidateNotNullOrEmpty()] [string]$PrivacyURL, [ValidateNotNullOrEmpty()] [string]$Developer, [ValidateNotNullOrEmpty()] [string]$Owner, [ValidateNotNullOrEmpty()] [string]$Notes ) [hashtable]$AppHashTable = @{} $AppHashTable['displayName'] = $DisplayName $AppHashTable['description'] = $Description $AppHashTable['publisher'] = $publisher $AppHashTable['isFeatured'] = $isFeatured switch($ApplicationType) { 'Android LOB App' { $AppHashTable['@odata.type'] = '#microsoft.graph.androidLobApp' Write-Host 'This is not supported yet...' } 'iOS LOB App'{ } 'Android Store App' { $AppHashTable['@odata.type'] = '#microsoft.graph.androidStoreApp' $AppHashTable['appStoreUrl'] = $appStoreUrl $AppHashTable['minimumSupportedOperatingSystem'] = @{ '@odata.type' = '#microsoft.graph.androidMinimumOperatingSystem' "$minimumSupportedAndroidOS" = $true } } 'iOS Store App' { $AppHashTable['@odata.type'] = '#microsoft.graph.iosStoreApp' $AppHashTable['appStoreUrl'] = $appStoreUrl $AppHashTable['minimumSupportedOperatingSystem'] = @{ '@odata.type' = '#microsoft.graph.iosMinimumOperatingSystem' "$minimumSupportediOS" = $true } Switch($iosDeviceType) { 'iPad' { $AppHashTable['applicableDeviceType'] = @{ '@odata.type' = '#microsoft.graph.iosDeviceType' "iPad" = $true } } 'iPhone' { $AppHashTable['applicableDeviceType'] = @{ '@odata.type' = '#microsoft.graph.iosDeviceType' "iPhoneAndIPod" = $true } } 'Both' { $AppHashTable['applicableDeviceType'] = @{ '@odata.type' = '#microsoft.graph.iosDeviceType' "iPhoneAndIPod" = $true "iPad" = $true } } } } 'Web App' { $AppHashTable['@odata.type'] = '#microsoft.graph.webApp' $AppHashTable['useManagedBrowser'] = $UseManagedBrowser $AppHashTable['appUrl'] = $WebAppURL } 'Windows Phone 8.1 Store App' { $AppHashTable['@odata.type'] = '#microsoft.graph.windowsPhone81StoreApp' $AppHashTable['appStoreUrl'] = $appStoreUrl } 'Windows Store App' { $AppHashTable['@odata.type'] = '#microsoft.graph.windowsStoreApp' $AppHashTable['appStoreUrl'] = $appStoreUrl } } if(-not [string]::IsNullOrEmpty($iconType)){ $AppHashTable['largeIcon'] = @{ '@odata.type' = '#microsoft.graph.mimeContent' 'type' = $iconType 'value' = $iconBase64 } } if($InformationURL) { $AppHashTable['informationUrl'] = $InformationURL } if($PrivacyURL) { $AppHashTable['privacyInformationUrl'] = $PrivacyURL } if($Developer) { $AppHashTable['developer'] = $Developer } if($Owner) { $AppHashTable['owner'] = $Owner } if($Notes) { $AppHashTable['notes'] = $Notes } $AppJSON = $AppHashTable | ConvertTo-Json -Depth 10 Invoke-GraphMethod -Method 'Post' -Version (Get-GraphIntuneVersion) -query 'deviceAppManagement/mobileApps' -body $AppJSON -ContentType 'application/json' } Function Remove-GraphIntuneApp { <# .SYNOPSIS Removes specified application .DESCRIPTION Will delete an Intune application .EXAMPLE Get-GraphIntuneApp | Remove-GraphIntuneApp -WhatIf .PARAMETER id Id of the app you want to remove. Supports pipeline. .PARAMETER force Remove app without prompting. .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/intune_apps_app_conceptual .Notes Author: Ryan Ephgrave #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [ValidateNotNullOrEmpty()] [string]$id, [Parameter(Mandatory=$false)] [switch]$force ) process { foreach($AppId in $id){ if($force) { if($PSCmdlet.ShouldProcess("$($AppId)","Invoke-GraphMethod -Method Delete")){ Invoke-GraphMethod -Version (Get-GraphIntuneVersion) -method 'Delete' -query "deviceAppManagement/mobileApps/$($AppId)" } } else { $AppInfo = Get-GraphIntuneApps -AppId $AppId if(-not [string]::IsNullOrEmpty($AppInfo)) { $Result = Read-Host "Do you want to delete the app $($AppInfo.DisplayName)? (Y/N)" if($Result -eq 'y') { if($PSCmdlet.ShouldProcess("$($AppId)","Invoke-GraphMethod -Method Delete")){ Invoke-GraphMethod -Version (Get-GraphIntuneVersion) -method 'Delete' -query "deviceAppManagement/mobileApps/$($AppId)" } } } } } } } Function Get-GraphIntuneApps { <# .SYNOPSIS List Intune apps .DESCRIPTION Will query deviceAppManagement/mobileApps to get a list of Intune apps. Filters out managed apps .EXAMPLE Get-GraphIntuneApps .PARAMETER Id Get specific app by Id. .LINK https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/intune_apps_app_conceptual .Notes Author: Ryan Ephgrave #> Param( [string]$Id ) $results = '' if(-not [string]::IsNullOrEmpty($Id)) { $results = Invoke-GraphMethod -Version (Get-GraphIntuneVersion) -query "deviceAppManagement/mobileApps/$($Id)" -method 'Get' } else { $results = Invoke-GraphMethod -Version (Get-GraphIntuneVersion) -query "deviceAppManagement/mobileApps" -method 'Get' } foreach($result in $results) { $Type = $result."@odata.type" if(-not $type.contains('managed')){ $result } } } <# Function Set-GraphIntuneApp { [CmdletBinding()] Param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [ValidateNotNullOrEmpty()] [string]$Id, [ValidateNotNullOrEmpty()] [string]$DisplayName, [ValidateNotNullOrEmpty()] [string]$Description, [ValidateNotNullOrEmpty()] [string]$publisher, [ValidateNotNullOrEmpty()] [string]$appUrl, [ValidateSet( 'v4_0', 'v4_0_3', 'v4_1', 'v4_2', 'v4_3', 'v4_4', 'v5_0', 'v5_1' )] [string]$minimumSupportedAndroidOS, [ValidateSet( 'v8_0', 'v9_0', 'v10_0' )] [string]$minimumSupportediOS, [ValidateSet( 'iPad', 'iPhone', 'Both' )] [string]$iosDeviceType, [string]$iconType, [string]$iconBase64, [Nullable[bool]]$isFeatured, [bool]$UseManagedBrowser, [ValidateNotNullOrEmpty()] [string]$InformationURL, [ValidateNotNullOrEmpty()] [string]$PrivacyURL, [ValidateNotNullOrEmpty()] [string]$Developer, [ValidateNotNullOrEmpty()] [string]$Owner, [ValidateNotNullOrEmpty()] [string]$Notes ) Process{ } } #>
PowerShellCorpus/PowerShellGallery/MSGraphAPI/0.3.8/Intune/Intune-DeviceProfiles.ps1
Intune-DeviceProfiles.ps1
<#Function New-GraphIntuneDeviceProfile { Param( [Parameter(Mandatory=$true)] [ValidateSet( 'Android LOB App', 'Android Store App', 'iOS LOB App', 'iOS Store App', 'Web App', 'Windows Phone 8.1 Store App', 'Windows Store App' )] [string]$ApplicationType ) }#>
PowerShellCorpus/PowerShellGallery/GoogleCloud/1.0.0.5/AppendPsModulePath.ps1
AppendPsModulePath.ps1
# Copyright 2015-2016 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Appends the Cloud Tools for PowerShell module location to the registry's PSModulePath environment # variable param($installPath) # Let a user manually select a Cloud SDK install path $installPath = $installPath -or $args[0] # Find the Google Cloud SDK install path from the registry. if (-not $installPath) { $hklmPath = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" $hkcuPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" if (Test-Path $hklmPath) { $installPath = Get-ItemPropertyValue $hklmPath InstallLocation } elseif (Test-Path $hkcuPath) { $installPath = Get-ItemPropertyValue $hkcuPath InstallLocation } else { Write-Error "Can not find Cloud SDK from the registry." return } } $installPath = $installPath -replace '"' # Registry values had quotes for some reason # The folder above where the PowerShell cmdlets are installed. PowerShell will crawl subfolders # looking for .psd1 files. (So it should find .\GoogleCloud\GoogleCloud.psd1.) $googlePowerShellPath = Join-Path $installPath "google-cloud-sdk\platform\PowerShell" if (-not (Test-Path $googlePowerShellPath)) { Write-Error "Can not find Google PowerShell. $googlePowerShellPath does not exist." return } # Get the value of the two registry keys that initialize the environment variable. $hklmLocation = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" $hklmValue = (Get-ItemProperty $hklmLocation).PSModulePath $hkcuLocation = "HKCU:\Environment" $hkcuValue = (Get-ItemProperty $hkcuLocation).PSModulePath $regValue = (($hklmValue, $hkcuValue | ?{$_}) -join ";") if(($regValue -split ";" -contains $googlePowerShellPath)) { Write-Warning "Path already exists." return } $wid = [Security.Principal.WindowsIdentity]::GetCurrent() $wip = New-Object Security.Principal.WindowsPrincipal $wid $isElevated = $wip.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) if ($isElevated -and (Test-Path $hklmPath)) { # If we are running as administrator, and the Cloud SDK is installed for all users, # append to the PSModluePath in the local machine registry location. Write-Verbose "Adding to registry key for all users." Push-Location $hklmLocation # Don't add a semicolon if $hklmValue is $null Set-ItemProperty . PSModulePath (($hklmValue, $googlePowerShellPath | ?{$_}) -join ";") } else { # If we are running as a local user, or Cloud SDK is installed for just the current user, # append to the PSModluePath in the current user registry location. Write-Verbose "Adding to registry key for user $env:UserName." Push-Location $hkcuLocation # Don't add a semicolon if $hkcuValue is $null Set-ItemProperty . PSModulePath (($hkcuValue, $googlePowerShellPath | ?{$_}) -join ";") } Write-Output (Get-ItemProperty . PSModulePath) Pop-Location
PowerShellCorpus/PowerShellGallery/GoogleCloud/1.0.0.5/BootstrapCloudToolsForPowerShell.ps1
BootstrapCloudToolsForPowerShell.ps1
# Copyright 2015 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Bootstraps the Google Cloud cmdlets into the current PowerShell session. function Get-ScriptDirectory { $invocation = (Get-Variable MyInvocation -Scope 1).Value return Split-Path $invocation.MyCommand.Path } $modulePath = Join-Path (Get-ScriptDirectory) "GoogleCloud.psd1" Import-Module $modulePath $Env:UserProfile clear Write-Output "Google Cloud Tools for PowerShell"
PowerShellCorpus/PowerShellGallery/GoogleCloud/1.0.0.5/PatchFromGcs.ps1
PatchFromGcs.ps1
# Copyright 2015-2016 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Updates Cloud Tools for PowerShell module to the latest found in # Google Cloud Storage bucket g-cloudsharp-unsignedbinaries. # Let a user manually select a Cloud SDK install path param($installPath) $installPath = $installPath -or $args[0] # Find the Google Cloud SDK install path from the registry. if (-not $installPath) { $hklmPath = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" $hkcuPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" if (Test-Path $hklmPath) { $installPath = Get-ItemPropertyValue $hklmPath InstallLocation } elseif (Test-Path $hkcuPath) { $installPath = Get-ItemPropertyValue $hkcuPath InstallLocation } else { Write-Error "Can not find Cloud SDK from the registry." return } } $installPath = $installPath -replace '"' # Registry values had quotes. This removes them. Push-Location (Join-Path $installPath "google-cloud-sdk\platform\PowerShell") $googlePowerShellPath = Resolve-Path "GoogleCloud" if (-not (Test-Path $googlePowerShellPath)) { Write-Error "Can not find Cloud Tools for PowerShell. '$googlePowerShellPath' does not exist." return } $pathToOldCmdlets = "GoogleCloudPowerShell-unpatched-backup" if (Test-Path $pathToOldCmdlets) { Remove-Item $pathToOldCmdlets -Recurse } Move-Item $googlePowerShellPath $pathToOldCmdlets Import-Module "$pathToOldCmdlets/GoogleCloud.psd1" $bucket = Get-GcsBucket g-cloudsharp-unsignedbinaries # Find objects in the powershell directory, and select one most recently created. $zipObject = Find-GcsObject $bucket -Prefix powershell | Sort TimeCreated -Descending | Select -First 1 $zipFileName = Split-Path $zipObject.Name -Leaf Write-Verbose "Saving new file to $zipFileName" Read-GcsObject $bucket $zipObject.Name -OutFile $zipFileName -Force $zipPath = Resolve-Path $zipFileName Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, "$googlePowerShellPath\..") Pop-Location
PowerShellCorpus/PowerShellGallery/MrAD/1.0/Compare-MrADGroup.ps1
Compare-MrADGroup.ps1
#Requires -Version 3.0 -Modules ActiveDirectory function Compare-MrADGroup { <# .SYNOPSIS Compares the groups of a the specified Active Directory users. .DESCRIPTION Compare-MrADGroup is a function that retrieves a list of all the Active Directory groups that the specified Active Directory users are a member of. It determines what groups are common between the users based on membership of 50% or more of the specified users. It then compares the specified users group membership to the list of common groups and returns a list of users whose group membership differentiates from that list. A minus (-) in the status column means the user is not a member of a common group and a plus (+) means the user is a member of an additional group. .PARAMETER UserName The Active Directory user(s) account object to compare. Can be specified in the form or SamAccountName, Distinguished Name, or GUID. This parameter is mandatory. .PARAMETER IncludeEqual Switch parameter to include common groups that the specified user is a member of. An equals (=) sign means the user is a member of a common group. .EXAMPLE Compare-MrADGroup -UserName 'jleverling', 'lcallahan', 'mpeacock' .EXAMPLE 'jleverling', 'lcallahan', 'mpeacock' | Compare-MrADGroup -IncludeEqual .EXAMPLE Get-ADUser -Filter {Department -eq 'Sales' -and Enabled -eq 'True'} | Compare-MrADGroup .INPUTS String .OUTPUTS PSCustomObject .NOTES Author: Mike F Robbins Website: http://mikefrobbins.com Twitter: @mikefrobbins #> [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline)] [string[]]$UserName, [switch]$IncludeEqual ) BEGIN { $Params = @{} If ($PSBoundParameters['IncludeEqual']) { $Params.IncludeEqual = $true } } PROCESS { foreach ($name in $UserName) { try { Write-Verbose -Message "Attempting to query Active Directory of user: '$name'." [array]$users += Get-ADUser -Identity $name -Properties MemberOf -ErrorAction Stop } catch { Write-Warning -Message "An error occured. Error Details: $_.Exception.Message" } } } END { Write-Verbose -Message "The `$users variable currently contains $($users.Count) items." $commongroups = ($groups = $users | Select-Object -ExpandProperty MemberOf | Group-Object) | Where-Object Count -ge ($users.Count / 2) | Select-Object -ExpandProperty Name Write-Verbose -Message "There are $($commongroups.Count) groups with 50% or more of the specified users in them." foreach ($user in $users) { Write-Verbose -Message "Checking user: '$($user.SamAccountName)' for group differences." $differences = Compare-Object -ReferenceObject $commongroups -DifferenceObject $user.MemberOf @Params foreach ($difference in $differences) { [PSCustomObject]@{ UserName = $user.SamAccountName GroupName = $difference.InputObject -replace '^CN=|,.*$' Status = switch ($difference.SideIndicator){'<='{'-';break}'=>'{'+';break}'=='{'=';break}} 'RatioOfUsersInGroup(%)' = ($groups | Where-Object name -eq $difference.InputObject).Count / $users.Count * 100 -as [int] } } } } }
PowerShellCorpus/PowerShellGallery/MrAD/1.0/Get-MrADLockOutInfo.ps1
Get-MrADLockOutInfo.ps1
#Requires -Version 3.0 function Get-MrADLockOutInfo { <# .SYNOPSIS Get-MrADLockOutInfo returns a list of users who were locked out in Active Directory. .DESCRIPTION Get-MrADLockOutInfo is an advanced function that returns a list of users who were locked out in Active Directory by querying the event logs on the PDC emulator in the domain. .PARAMETER UserName The userid of the specific user you are looking for lockouts for. The default is all locked out users. .PARAMETER StartTime The datetime to start searching the event logs from. The default is the past three days. .PARAMETER Credential Specifies a user account that has permission to read the security event log on the PDC emulator. The default is the current user. .EXAMPLE Get-MrADLockOutInfo .EXAMPLE Get-MrADLockOutInfo -Credential (Get-Credential) .EXAMPLE Get-MrADLockOutInfo -UserName 'mikefrobbins' .EXAMPLE Get-MrADLockOutInfo -StartTime (Get-Date).AddDays(-1) .EXAMPLE Get-MrADLockOutInfo -UserName 'mikefrobbins' -StartTime (Get-Date).AddDays(-1) -Credential (Get-Credential) #> [CmdletBinding()] param ( [ValidateNotNullOrEmpty()] [string]$DomainName = $env:USERDOMAIN, [ValidateNotNullOrEmpty()] [string]$UserName = '*', [ValidateNotNullOrEmpty()] [datetime]$StartTime = (Get-Date).AddDays(-3), [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty ) try { $ErrorActionPreference = 'Stop' $PdcEmulator = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain(( New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $DomainName)) ).PdcRoleOwner.name Write-Verbose -Message "The PDC emulator in your forest root domain is: $PdcEmulator" $ErrorActionPreference = 'Continue' } catch { Write-Error -Message 'Unable to query the domain. Verify the user running this script has read access to Active Directory and try again.' } $Params = @{} If ($PSBoundParameters['Credential']) { $Params.Credential = $Credential } Invoke-Command -ComputerName $PdcEmulator { Get-WinEvent -FilterHashtable @{LogName='Security';Id=4740;StartTime=$Using:StartTime} | Where-Object {$_.Properties[0].Value -like "$Using:UserName"} | Select-Object -Property TimeCreated, @{Label='UserName';Expression={$_.Properties[0].Value}}, @{Label='ClientName';Expression={$_.Properties[1].Value}} } @Params | Select-Object -Property TimeCreated, UserName, ClientName }
PowerShellCorpus/PowerShellGallery/MrAD/1.0/Get-MrADUser.ps1
Get-MrADUser.ps1
#Requires -Version 3.0 function Get-MrADUser { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [String[]]$UserName ) PROCESS { foreach ($user in $UserName){ $Search = [adsisearcher]"(&(objectCategory=person)(objectClass=user)(samaccountname=$user))" foreach ($user in $($Search.FindAll())){ $stringSID = (New-Object -TypeName System.Security.Principal.SecurityIdentifier($($user.Properties.objectsid),0)).Value $objectGUID = [System.Guid]$($user.Properties.objectguid) [pscustomobject]@{ DistinguishedName = $($user.Properties.distinguishedname) Enabled = (-not($($user.GetDirectoryEntry().InvokeGet('AccountDisabled')))) GivenName = $($user.Properties.givenname) Name = $($user.Properties.name) ObjectClass = $($user.Properties.objectclass)[-1] ObjectGUID = $objectGUID SamAccountName = $($user.Properties.samaccountname) SID = $stringSID Surname = $($user.Properties.sn) UserPrincipalName = $($user.Properties.userprincipalname) } } } } }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Private/Compress-PSGelfString.ps1
Compress-PSGelfString.ps1
function Compress-PSGelfString ([String]$ToZip) { #This creates a Byte array of GZiPd data. $ms = New-Object System.IO.MemoryStream $cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress) $sw = New-Object System.IO.StreamWriter($cs) $sw.Write($ToZip) $sw.Close(); Return $ms.ToArray() }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Private/New-PSGelfObject.ps1
New-PSGelfObject.ps1
function New-PSGelfObject { [cmdletbinding()] Param ( [Parameter(Mandatory)][String]$GelfServer, [Parameter(Mandatory)][Int]$Port, [Parameter()][String]$HostName, [Parameter(Mandatory)][String]$ShortMessage, [Parameter()][String]$FullMessage, [Parameter()][System.DateTime]$DateTime, [Parameter()][Int]$Level, [Parameter()][String]$Facility, [Parameter()][Int]$Line, [Parameter()][String]$File, [Parameter()][Hashtable]$AdditionalField ) Begin { } Process { $Message = New-Object –TypeName PSObject $Message | Add-Member –MemberType NoteProperty –Name version –Value "1.1" $Message | Add-Member –MemberType NoteProperty –Name ShortMessage –Value $ShortMessage if (!$HostName) { $HostName = & {hostname} } $Message | Add-Member –MemberType NoteProperty –Name host –Value $HostName if ($FullMessage) { $Message | Add-Member –MemberType NoteProperty –Name full_message –Value $FullMessage } if ($DateTime) { $TimeStampConversion = Get-Date($DateTime).ToUniversalTime() -uformat "%s" $Message | Add-Member –MemberType NoteProperty –Name timestamp –Value $TimeStampConversion } if ($Level ) { $Message | Add-Member –MemberType NoteProperty –Name level –Value $Level } if ($Facility) { $Message | Add-Member –MemberType NoteProperty –Name facility –Value $Facility } if ($Line) { $Message | Add-Member –MemberType NoteProperty –Name line –Value $Line } if ($File) { $Message | Add-Member –MemberType NoteProperty –Name file –Value $File } if ($AdditionalField) { ($AdditionalField).GetEnumerator() | ForEach-Object { $FieldName = "_" + $_.Name $FieldValue = $_.Value if(!($FieldName -eq "_id")) { $Message | Add-Member –MemberType NoteProperty –Name $FieldName –Value $FieldValue } else { throw 'An additionional field can not be named ID.' } } } Write-Output $Message } End { } }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Private/Repair-PSGelfObject.ps1
Repair-PSGelfObject.ps1
function Repair-PSGelfObject { [cmdletbinding()] Param ( [Parameter(Mandatory )][PSCustomObject]$GelfMessage ) #Most of these changes are so you can easily pipe Get-WinEvent to this function. if($GelfMessage.MachineName) { Write-Verbose 'The property MachineName is being added as host.' $GelfMessage = $GelfMessage | Select @{Name="host";Expression={$_."MachineName"}},* } if(!($GelfMessage.host)) { Write-Verbose 'There wasnt a host set in the object. The host is set to the local machine.' $GelfMessage = $GelfMessage | Select @{Name="host";Expression={& {hostname}}},* } if($GelfMessage.TimeCreated) { Write-Verbose 'There was a property named TimeCreated. We are going to infer that is what the timestamp needs to be.' $GelfMessage = $GelfMessage | Select @{Name="timestamp";Expression={Get-Date($_."TimeCreated").ToUniversalTime() -uformat "%s"}},* -ExcludeProperty TimeCreated } if($GelfMessage.ID) { Write-Verbose 'There should not be a property named ID in the object. The property ID is being reanmed to EventID.' $GelfMessage = $GelfMessage | Select @{Name="_EventID";Expression={$_."ID"}},* -ExcludeProperty ID } if($GelfMessage.ShortMessage) { $GelfMessage = $GelfMessage | Select @{Name="short_message";Expression={$_."ShortMessage"}},* -ExcludeProperty ShortMessage } else { if($GelfMessage.Message) { $GelfMessage = $GelfMessage | Select @{Name="short_message";Expression={$_."Message"}},* -ExcludeProperty Message Write-Verbose 'ShortMessage is a required property. The property Message has been renamed ShortMessage to meet the requirments.' } else { Write-Error 'There must be a ShortMessage or Message property. You can use Select-Object to rename an existing property. The message has not been sent.' Return } } #We have to rename all of the non default fields to start with an underscore. $DefaultFields = @("version","host","short_message","full_message","timestamp","level","facility","line","file") $GelfMessage | Get-Member -MemberType NoteProperty | Where-Object {$DefaultFields -notcontains $_.Name -and $_.Name -notlike "_*"} | ForEach-Object { $FieldToBeRenamed = $_.Name $GelfMessage = $GelfMessage | Select @{Name="_$FieldToBeRenamed";Expression={$_."$FieldToBeRenamed"}},* -ExcludeProperty $FieldToBeRenamed } Write-Output $GelfMessage }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Public/Send-PSGelfUDPFromObject.ps1
Send-PSGelfUDPFromObject.ps1
<# .Synopsis Sends an PSObject to Graylog via UDP. .DESCRIPTION This function sends an PSObject to Graylog via UDP to a server supporting GELF. This function should be used if you do want to pipe input. .EXAMPLE Get-WinEvent Setup | Send-PSGelfUDPFromObject -GelfServer graylog -Port 12202 #> function Send-PSGelfUDPFromObject { [cmdletbinding()] Param ( [Parameter(Mandatory)][String]$GelfServer, [Parameter(Mandatory)][Int]$Port, [Parameter(Mandatory,ValueFromPipeline )][PSCustomObject]$GelfMessage ) Begin { } Process { if($GelfServer -notmatch "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$") { $GelfServer = [String]$([System.Net.Dns]::GetHostAddressesAsync($GelfServer)).Result[0] } # Create a UDP client to be used to send data $Address = [system.net.IPAddress]::Parse($GelfServer) $EndPoint = New-Object System.Net.IPEndPoint($Address, $Port) $UdpClient = new-Object System.Net.Sockets.UdpClient $RepairedGelfMessage = Repair-PSGelfObject -GelfMessage $GelfMessage #$CompressedJSON = Compress-PSGelfString($RepairedGelfMessage | ConvertTo-Json -Compress) $CompressedJSON = [System.Text.Encoding]::ASCII.GetBytes($($RepairedGelfMessage | ConvertTo-Json -Compress)) #We only need to chunk if the packet is greater than 8192 bytes. #...I left some wiggle room. if($CompressedJSON.Length -ge 8100) { $ChunkSize = 6000 $NumOfChunks = [math]::ceiling($CompressedJSON.Length / $ChunkSize) - 1 $TotalChunks = [Byte]$($NumOfChunks + 1) if($TotalChunks -ge 128) { Write-Error 'There are too many chunks to send. The maxium number of chunks is 128.' Return } #GELF Magic Bytes $HeaderBytes = [byte]0x1e,[byte]0x0f #Random Message ID for the Message. 8 Bytes [Object]$Random = New-Object System.Random $GelfMessageID = New-Object Byte[] 8 $Random.NextBytes($GelfMessageID) 0 .. $NumOfChunks | ForEach-Object { #Sequence number of this chunk. Must start at 0 $SequenceNum = [byte]$_ #Indexes of where the chunk will start and stop $StartPacketIndex = $_ * $ChunkSize $EndPacketIndex = $StartPacketIndex + $ChunkSize - 1 $ChunkData = $CompressedJSON[$StartPacketIndex .. $EndPacketIndex] $ChunkPacket = $HeaderBytes + $GelfMessageID + $SequenceNum + $TotalChunks + $ChunkData #UDP.Send returns the length of the data sent. We don't need this. $UDPClient.SendAsync($ChunkPacket, $ChunkPacket.Length,$EndPoint) | Out-Null } } else { $UDPclient.SendAsync($CompressedJSON, $CompressedJSON.Length,$EndPoint) | Out-Null } } End { } }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Public/Send-PSGelfTCPFromObject.ps1
Send-PSGelfTCPFromObject.ps1
<# .Synopsis Sends an PSObject to Graylog via TCP. .DESCRIPTION This function sends an PSObject to Graylog via TCP to a server supporting GELF. This function should be used if you do want to pipe input. .EXAMPLE Get-WinEvent Setup | Send-PSGelfTCPFromObject -GelfServer graylog -Port 12201 #> function Send-PSGelfTCPFromObject { [cmdletbinding()] Param ( [Parameter(Mandatory)][String]$GelfServer, [Parameter(Mandatory)][Int]$Port, [Parameter(Mandatory,ValueFromPipeline )][PSCustomObject]$GelfMessage ) Begin { } Process { try { $TcpClient = New-Object System.Net.Sockets.TcpClient #I am using ConnectAsync because connect isnt supported in .net core $Connect = $TcpClient.ConnectAsync($GelfServer,$Port) if(!($Connect.Wait(500))) { Write-Error "The connection timed out." return } $TcpStream = $TcpClient.GetStream() $RepairedGelfMessage = Repair-PSGelfObject -GelfMessage $GelfMessage $ConvertedJSON = [System.Text.Encoding]::ASCII.GetBytes($($RepairedGelfMessage | ConvertTo-Json -Compress)) #Graylog needs a NULL byte on the end of the data packet $ConvertedJSON = $ConvertedJSON + [Byte]0x00 $TcpStream.Write($ConvertedJSON, 0, $ConvertedJSON.Length) $TcpStream.Close() } Catch { $_ } } End { } }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Public/Send-PSGelfTCP.ps1
Send-PSGelfTCP.ps1
<# .Synopsis Sends a GELF message via TCP. .DESCRIPTION This function sends a GELF message via TCP to a server supporting GELF. This function should be used if you don't want to pipe input. .EXAMPLE Send-PSGelfTCP -GelfServer graylog -Port 12202 -ShortMessage "This is a short message" .EXAMPLE Send-PSGelfTCP -GelfServer graylog -Port 12202 -HostName "dc01" -AdditionalField @{TestField1 = "wow!";TestField2 = "wow2"} -ShortMessage "Test Additional Fields" #> function Send-PSGelfTCP { [cmdletbinding()] Param ( [Parameter(Mandatory)][String]$GelfServer, [Parameter(Mandatory)][Int]$Port, [Parameter()][String]$HostName, [Parameter(Mandatory)][String]$ShortMessage, [Parameter()][String]$FullMessage, [Parameter()][System.DateTime]$DateTime, [Parameter()][Int]$Level, [Parameter()][String]$Facility, [Parameter()][Int]$Line, [Parameter()][String]$File, [Parameter()][Hashtable]$AdditionalField ) Begin { } Process { $GelfMessage = New-PSGelfObject @PsBoundParameters Send-PSGelfTCPFromObject -GelfServer $GelfServer -Port $Port -GelfMessage $GelfMessage } End { } }
PowerShellCorpus/PowerShellGallery/PSGELF/1.0/Public/Send-PSGelfUDP.ps1
Send-PSGelfUDP.ps1
<# .Synopsis Sends a GELF message via UDP. .DESCRIPTION This function sends a GELF message via UDP to a server supporting GELF. This function should be used if you don't want to pipe input. .EXAMPLE Send-PSGelfUDP -GelfServer graylog -Port 12201 -ShortMessage "This is a short message" .EXAMPLE Send-PSGelfUDP -GelfServer graylog -Port 12201 -HostName "dc01" -AdditionalField @{TestField1 = "wow!";TestField2 = "wow2"} -ShortMessage "Test Additional Fields" #> function Send-PSGelfUDP { Param ( [Parameter(Mandatory)][String]$GelfServer, [Parameter(Mandatory)][Int]$Port, [Parameter()][String]$HostName, [Parameter(Mandatory)][String]$ShortMessage, [Parameter()][String]$FullMessage, [Parameter()][System.DateTime]$DateTime, [Parameter()][Int]$Level, [Parameter()][String]$Facility, [Parameter()][Int]$Line, [Parameter()][String]$File, [Parameter()][Hashtable]$AdditionalField ) Begin { } Process { $GelfMessage = New-PSGelfObject @PsBoundParameters Send-PSGelfUDPFromObject -GelfServer $GelfServer -Port $Port -GelfMessage $GelfMessage } End { } }
PowerShellCorpus/PowerShellGallery/AzureGraphCmdlets/1.0.727.1/Install-AzureGraphCmdletsModule.ps1
Install-AzureGraphCmdletsModule.ps1
<# .SYNOPSIS Installs the AzureGraphCmdlets module to the user's modules folder. .DESCRIPTION Installs the AzureGraphCmdlets module to the user's modules folder. Replaces any existing versions of the PowerShell module. .EXAMPLE Install-AzureGraphCmdletsModule.ps1 Installs the AzureGraphCmdlets module to the user's PowerShell modules folder. .NOTES No notes at this time. #> $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition $scriptFileName = split-path -Leaf $MyInvocation.MyCommand.Definition Set-Location $scriptPath $moduleName = "AzureGraphCmdlets" $userModulesFolder = "$([System.Environment]::GetFolderPath("mydocuments"))\WindowsPowerShell\Modules\$moduleName" if (Test-Path $userModulesFolder) { Remove-Item -Recurse -Force $userModulesFolder } New-Item -ItemType directory -Path $userModulesFolder -ErrorAction Stop | Out-Null if ($?) { Write-Host -ForegroundColor Black -BackgroundColor Green "Created user modules folder at '$userModulesFolder'" } Get-ChildItem $scriptPath | ? { $_.Name -ne $scriptFileName } | % { Copy-Item -Path $_.FullName -Destination $userModulesFolder -Recurse -Force -Container } Write-Host -ForegroundColor Black -BackgroundColor Green "Installed $moduleName to modules folder at '$userModulesFolder'"
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Private/Format-WinSCPPathString.ps1
Format-WinSCPPathString.ps1
<# .SYNOPSIS Properly formats a path string for WinSCP. .DESCRIPTION This help function is used to properly format a path string for WinSCP to avoid syntax errors. .INPUTS System.String. .OUTPUTS System.String. .PARAMETER Path The path string to be formated. .EXAMPLE Format-WinSCPPathString -Path '\' / .EXAMPLE Format-WinSCPPathString -Path 'Top Folder\Middle Folder' Top Folder/Middle Folder .EXAMPLE Format-WinSCPPathString -Path '.\path\subpath\file.txt' ./path/subpath/file.txt .LINK http://dotps1.github.io/WinSCP #> Function Format-WinSCPPathString { [OutputType( [String] )] Param ( [Parameter( Mandatory = $true )] [String[]] $Path ) Process { foreach ($item in $Path) { if ($item.Contains('\')) { $item = $item.Replace('\', '/') } $item } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Get-WinSCPItem.ps1
Get-WinSCPItem.ps1
Function Get-WinSCPItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Get-WinSCPItem' )] [OutputType( [WinSCP.RemoteFileInfo] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( ValueFromPipelineByPropertyName = $true )] [String[]] $Path = '/', [Parameter()] [String] $Filter = '*' ) Begin { $sessionValueFromPipeline = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $item)) { Write-Error -Message "Cannot find path: $item because it does not exist." continue } if ($PSBoundParameters.ContainsKey('Filter')) { Get-WinSCPChildItem -WinSCPSession $WinSCPSession -Path $item -Filter $Filter } else { try { $WinSCPSession.GetFileInfo($item) } catch { Write-Error -Message $_.ToString() } } } } End { if (-not ($sessionValueFromPipeline)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Test-WinSCPPath.ps1
Test-WinSCPPath.ps1
Function Test-WinSCPPath { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Test-WinSCPPath' )] [OutputType( [Bool] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Path ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach($item in (Format-WinSCPPathString -Path $($Path))) { try { $WinSCPSession.FileExists($item) } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Get-WinSCPChildItem.ps1
Get-WinSCPChildItem.ps1
Function Get-WinSCPChildItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Get-WinSCPChildItem' )] [OutputType( [Array] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( ValueFromPipelineByPropertyName = $true )] [String[]] $Path = '/', [Parameter()] [String] $Filter = $null, [Parameter()] [Switch] $Recurse, [Parameter()] [Int] $Depth = $null, [Parameter()] [Switch] $Name, [Parameter()] [Switch] $Directory, [Parameter()] [Switch] $File ) Begin { $sessionValueFromPipeline = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $Path)) { Write-Error -Message "Cannot find path: $item because it does not exist." continue } if ($PSBoundParameters.ContainsKey('Depth') -and -not $Recurse.IsPresent) { $Recurse = $true } try { if ($Recurse.IsPresent) { $enumerationOptions = ([WinSCP.EnumerationOptions]::AllDirectories -bor [WinSCP.EnumerationOptions]::MatchDirectories) } else { $enumerationOptions = ([WinSCP.EnumerationOptions]::None -bor [WinSCP.EnumerationOptions]::MatchDirectories) } $items = $WinSCPSession.EnumerateRemoteFiles( $item, $Filter, $enumerationOptions ) | Sort-Object -Property IsDirectory -Descending:$false | Sort-Object -Property @{ Expression = { Split-Path $_.FullName } }, Name if ($PSBoundParameters.ContainsKey('Depth')) { $items = $items | Where-Object { ($_.FullName.SubString(0, $_.FullName.LastIndexOf([System.IO.Path]::AltDirectorySeparatorChar)).Split([System.IO.Path]::AltDirectorySeparatorChar).Count - 1) -le $Depth } } if ($Directory.IsPresent -and -not $File.IsPresent) { $items = $items | Where-Object { $_.IsDirectory -eq $true } } elseif ($File.IsPresent -and -not $Directory.IsPresent) { $items = $items | Where-Object { $_.IsDirectory -eq $false } } if ($Name.IsPresent) { $items = $items | Select-Object -ExpandProperty Name } Write-Output -InputObject $items } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeline)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/New-WinSCPSession.ps1
New-WinSCPSession.ps1
Function New-WinSCPSession { [CmdletBinding( SupportsShouldProcess = $true, HelpUri = 'https://github.com/dotps1/WinSCP/wiki/New-WinSCPSession' )] [OutputType( [WinSCP.Session] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateNotNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter()] [WinSCP.FtpMode] $FtpMode = (New-Object -TypeName WinSCP.FtpMode), [Parameter()] [WinSCP.FtpSecure] $FtpSecure = (New-Object -TypeName WinSCP.FtpSecure), [Parameter()] [Switch] $GiveUpSecurityAndAcceptAnySshHostKey, [Parameter()] [Switch] $GiveUpSecurityAndAcceptAnyTlsHostCertificate, [Parameter( Mandatory = $true )] [String] $HostName = $null, [Parameter()] [Int] $PortNumber = 0, [Parameter()] [WinSCP.Protocol] $Protocol = (New-Object -TypeName WinSCP.Protocol), [Parameter( ValueFromPipelineByPropertyName = $true )] [String[]] $SshHostKeyFingerprint = $null, [Parameter()] [ValidateScript({ if (Test-Path -Path $_) { return $true } else { throw "$_ not found." } })] [String] $SshPrivateKeyPath = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [SecureString] $SshPrivateKeySecurePassphrase = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [String] $TlsHostCertificateFingerprint = $null, [Parameter()] [TimeSpan] $Timeout = (New-TimeSpan -Seconds 15), [Parameter()] [Switch] $WebdavSecure, [Parameter()] [String] $WebdavRoot = $null, [Parameter()] [HashTable] $RawSetting = $null, [Parameter()] [ValidateScript({ if (Test-Path -Path (Split-Path -Path $_)) { return $true } else { throw "Path not found $(Split-Path -Path $_)." } })] [String] $DebugLogPath = $null, [Parameter()] [ValidateScript({ if (Test-Path -Path (Split-Path -Path $_)) { return $true } else { throw "Path not found $(Split-Path -Path $_)." } })] [String] $SessionLogPath = $null, [Parameter()] [TimeSpan] $ReconnectTime = (New-TimeSpan -Seconds 120), [Parameter()] [ScriptBlock] $FileTransferProgress = $null ) # Create WinSCP.Session and WinSCP.SessionOptions Objects, parameter values will be assigned to matching object properties. $sessionOptions = New-Object -TypeName WinSCP.SessionOptions $session = New-Object -TypeName WinSCP.Session -Property @{ ExecutablePath = "$PSScriptRoot\..\bin\winscp.exe" } # Convert PSCredential Object to match names of the WinSCP.SessionOptions Object. $PSBoundParameters.Add('UserName', $Credential.UserName) $PSBoundParameters.Add('SecurePassword', $Credential.Password) # Resolve Full Path, WinSCP.exe does not like dot sourced path for the Certificate. if (-not [String]::IsNullOrEmpty($SshPrivateKeyPath)) { $PSBoundParameters.SshPrivateKeyPath = (Resolve-Path -Path $SshPrivateKeyPath).Path } # Convert SshPrivateKeySecurePasspahrase to plain text and set it to the corresponding SessionOptions property. if ($SshPrivateKeySecurePassphrase -ne $null) { try { $sessionOptions.SshPrivateKeyPassphrase = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SshPrivateKeySecurePassphrase)) } catch { Write-Error -Message $_.ToString() return $null } } try { # Enumerate each parameter. foreach ($key in $PSBoundParameters.Keys) { # If the property is a member of the WinSCP.SessionOptions object, set the matching value. if (($sessionOptions | Get-Member -MemberType Properties).Name -contains $key) { $sessionOptions.$key = $PSBoundParameters.$key } # If the property is a member of the WinSCP.Session object, set the matching value. elseif (($session | Get-Member -MemberType Properties).Name -contains $key) { $session.$key = $PSBoundParameters.$key } } # Enumerate raw settings and add the options to the WinSCP.SessionOptions object. foreach ($key in $RawSetting.Keys) { $sessionOptions.AddRawSettings($key, $RawSetting[$key]) } # Add FileTransferProgress ScriptBlock if present. if ($FileTransferProgress -ne $null) { $session.Add_FileTransferProgress($FileTransferProgress) } } catch { Write-Error -Message $_.ToString() return $null } if ($PSCmdlet.ShouldProcess($session)) { try { # Open the WinSCP.Session object using the WinSCP.SessionOptions object. $session.Open($sessionOptions) # Set the default -WinSCPSession Parameter Value for other cmdlets. Get-Command -Module WinSCP -ParameterName WinSCPSession | ForEach-Object { $Global:PSDefaultParameterValues.Remove("$($_.Name):WinSCPSession") $Global:PSDefaultParameterValues.Add("$($_.Name):WinSCPSession", $session) } # Return the WinSCP.Session object. return $session } catch { $PSCmdlet.WriteError($_) $session.Dispose() return $null } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/New-WinSCPTransferOption.ps1
New-WinSCPTransferOption.ps1
Function New-WinSCPTransferOption { [CmdletBinding( SupportsShouldProcess = $true, HelpUri = 'https://github.com/dotps1/WinSCP/wiki/New-WinSCPTransferOption' )] [OutputType( [WinSCP.TransferOptions] )] Param ( [Parameter()] [String] $FileMask = $null, [Parameter()] [WinSCP.FilePermissions] $FilePermissions = $null, [Parameter()] [WinSCP.OverwriteMode] $OverwriteMode = (New-Object -TypeName WinSCP.OverwriteMode), [Parameter()] [Bool] $PreserveTimestamp = $true, [Parameter()] [WinSCP.TransferResumeSupportState] $State = (New-Object -TypeName WinSCP.TransferResumeSupportState), [Parameter()] [Int] $Threshold = 100, [Parameter()] [Int] $SpeedLimit = 0, [Parameter()] [WinSCP.TransferMode] $TransferMode = (New-Object -TypeName WinSCP.TransferMode) ) Begin { $transferOptions = New-Object -TypeName WinSCP.TransferOptions if ($PSCmdlet.ShouldProcess($transferOptions)) { foreach ($key in $PSBoundParameters.Keys) { try { if ($key -eq 'State' -or $key -eq 'Threshold') { $transferOptions.ResumeSupport.$($key) = $PSBoundParameters.$($key) } else { $transferOptions.$($key) = $PSBoundParameters.$($key) } } catch { Write-Error -Message $_.ToString() } } } } End { return $transferOptions } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Rename-WinSCPItem.ps1
Rename-WinSCPItem.ps1
Function Rename-WinSCPItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Rename-WinSCPItem' )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true )] [String] $Path, [Parameter( Mandatory = $true )] [String] $NewName, [Parameter()] [Switch] $PassThru ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { try { $item = Get-WinSCPItem -WinSCPSession $WinSCPSession -Path (Format-WinSCPPathString -Path $($Path)) -ErrorAction Stop if ($NewName.Contains('/') -or $NewName.Contains('\')) { $NewName = $NewName.Substring($NewName.LastIndexOfAny('/\')) } $newPath = "$($item.FullName.Substring(0, $item.FullName.LastIndexOf('/') + 1))$NewName" $WinSCPSession.MoveFile($item.FullName, $newPath) if ($PassThru.IsPresent) { Get-WinSCPItem -WinSCPSession $WinSCPSession -Path $newPath } } catch { Write-Error -Message $_.ToString() } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Get-WinSCPItemChecksum.ps1
Get-WinSCPItemChecksum.ps1
Function Get-WinSCPItemChecksum { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Get-WinSCPItemChecksum' )] [OutputType( [Array] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true )] [String] $Algorithm, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Path ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $item)) { Write-Error -Message "Cannot find path: $item because it does not exist." continue } try { return ($WinSCPSession.CalculateFileChecksum($Algorithm, $item)) } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Invoke-WinSCPCommand.ps1
Invoke-WinSCPCommand.ps1
Function Invoke-WinSCPCommand { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Invoke-WinSCPCommand' )] [OutputType( [WinSCP.CommandExecutionResult] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Command ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($commandment in $Command) { try { $WinSCPSession.ExecuteCommand($commandment) } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Send-WinSCPItem.ps1
Send-WinSCPItem.ps1
Function Send-WinSCPItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Send-WinSCPItem' )] [OutputType( [WinSCP.TransferOperationResult] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Path, [Parameter()] [String] $Destination = '/', [Parameter()] [Switch] $Remove, [Parameter()] [WinSCP.TransferOptions] $TransferOptions = ( New-Object -TypeName WinSCP.TransferOptions ) ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in $Path) { if (-not (Test-Path -Path $item)) { Write-Error -Message "Cannot find path: $item because it does not exist." continue } if (-not ($Destination.EndsWith('/'))) { if ((Get-WinSCPItem -WinSCPSession $WinSCPSession -Path $Destination -ErrorAction SilentlyContinue).IsDirectory) { $Destination += '/' } } try { $result = $WinSCPSession.PutFiles( $item, (Format-WinSCPPathString -Path $($Destination)), $Remove.IsPresent, $TransferOptions ) if ($result.IsSuccess) { Write-Output -InputObject $result } else { $result.Failures[0] | Write-Error } } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Start-WinSCPConsole.ps1
Start-WinSCPConsole.ps1
Function Start-WinSCPConsole { [CmdletBinding( ConfirmImpact = "None", HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Start-WinSCPConsole', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param() $process = "$PSScriptRoot\..\bin\WinSCP.exe" $args = '/Console' if ($PSCmdlet.ShouldProcess($process)) { Start-Process -FilePath $process -ArgumentList $args -Wait } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/ConvertTo-WinSCPEscapedString.ps1
ConvertTo-WinSCPEscapedString.ps1
Function ConvertTo-WinSCPEscapedString { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/ConvertTo-WinSCPEscapedString' )] [OutputType( [String] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $FileMask ) Begin { $sessionObject = New-Object -TypeName WinSCP.Session } Process { foreach ($item in $FileMask) { try { $sessionObject.EscapeFileMask($item) } catch { Write-Error -Message $_.ToString() } } } End { $sessionObject.Dispose() } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Remove-WinSCPSession.ps1
Remove-WinSCPSession.ps1
Function Remove-WinSCPSession { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Remove-WinSCPSession' )] [OutputType([ Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [WinSCP.Session] $WinSCPSession ) try { $WinSCPSession.Dispose() Get-Command -Module WinSCP -ParameterName WinSCPSession | ForEach-Object { $Global:PSDefaultParameterValues.Remove("$($_.Name):WinSCPSession") } } catch { Write-Error $_.ToString() } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Receive-WinSCPItem.ps1
Receive-WinSCPItem.ps1
Function Receive-WinSCPItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Receive-WinSCPItem' )] [OutputType( [WinSCP.TransferOperationResult] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Path, [Parameter()] [String] $Destination = $pwd, [Parameter()] [Switch] $Remove, [Parameter()] [WinSCP.TransferOptions] $TransferOptions = ( New-Object -TypeName WinSCP.TransferOptions ) ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') if ((Get-Item -Path $Destination -ErrorAction SilentlyContinue).PSIsContainer -and -not $Destination.EndsWith('\')) { $Destination = "$Destination\" } } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { try { $result = $WinSCPSession.GetFiles( $item, $Destination, $Remove.IsPresent, $TransferOptions ) if ($result.IsSuccess) { Write-Output -InputObject $result } else { $result.Failures[0] | Write-Error } } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Remove-WinSCPItem.ps1
Remove-WinSCPItem.ps1
Function Remove-WinSCPItem { [CmdletBinding( SupportsShouldProcess = $true, ConfirmImpact = 'High', HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Remove-WinSCPItem' )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [String[]] $Path ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $item)) { Write-Error -Message "Cannot find path: $item because it does not exist." continue } if ($PSCmdlet.ShouldProcess($item)) { try { $WinSCPSession.RemoveFiles($item) | Out-Null } catch { Write-Error -Message $_.ToString() } } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/New-WinSCPItemPermission.ps1
New-WinSCPItemPermission.ps1
Function New-WinSCPItemPermission { [CmdletBinding( SupportsShouldProcess = $true, HelpUri = 'https://github.com/dotps1/WinSCP/wiki/New-WinSCPItemPermission' )] [OutputType( [WinSCP.FilePermissions] )] Param ( [Parameter()] [Switch] $GroupExecute, [Parameter()] [Switch] $GroupRead, [Parameter()] [Switch] $GroupWrite, [Parameter()] [Int] $Numeric = $null, [Parameter()] [String] $Octal = $null, [Parameter()] [Switch] $OtherExecute, [Parameter()] [Switch] $OtherRead, [Parameter()] [Switch] $OtherWrite, [Parameter()] [Switch] $SetGid, [Parameter()] [Switch] $SetUid, [Parameter()] [Switch] $Sticky, [Parameter()] [String] $Text = $null, [Parameter()] [Switch] $UserExecute, [Parameter()] [Switch] $UserRead, [Parameter()] [Switch] $UserWrite ) Begin { $filePermmisions = New-Object -TypeName WinSCP.FilePermissions if ($PSCmdlet.ShouldProcess($filePermmisions)) { foreach ($key in $PSBoundParameters.Keys) { try { $filePermmisions.$($key) = $PSBoundParameters.$($key) } catch { Write-Error -Message $_.ToString() } } } } End { return $filePermmisions } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Move-WinSCPItem.ps1
Move-WinSCPItem.ps1
Function Move-WinSCPItem { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Move-WinSCPItem' )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Path, [Parameter()] [String] $Destination = '/', [Parameter()] [Switch] $Force, [Parameter()] [Switch] $PassThru ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path ($Destination = Format-WinSCPPathString -Path $($Destination)))) { if ($Force.IsPresent) { New-WinSCPItem -WinSCPSession $WinSCPSession -Path $Destination -ItemType Directory } else { Write-Error -Message 'Could not find a part of the path.' return } } foreach ($item in (Format-WinSCPPathString -Path $($Path))) { try { if (-not ($Destination.EndsWith($item))) { if (-not ($Destination.EndsWith('/'))) { $Destination += '/' } } $WinSCPSession.MoveFile($item.TrimEnd('/'), $Destination) if ($PassThru.IsPresent) { Get-WinSCPItem -WinSCPSession $WinSCPSession -Path (Join-Path -Path $Destination -ChildPath (Split-Path -Path $item -Leaf)) } } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/Sync-WinSCPPath.ps1
Sync-WinSCPPath.ps1
Function Sync-WinSCPPath { [CmdletBinding( HelpUri = 'https://github.com/dotps1/WinSCP/wiki/Sync-WinSCPPath' )] [OutputType( [WinSCP.SynchronizationResult] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( Mandatory = $true )] [WinSCP.SynchronizationMode] $Mode, [Parameter()] [String] $LocalPath = $pwd, [Parameter()] [String] $RemotePath = '/', [Parameter()] [Switch] $Remove, [Parameter()] [Switch] $Mirror, [Parameter()] [WinSCP.SynchronizationCriteria] $Criteria = (New-Object -TypeName WinSCP.SynchronizationCriteria), [Parameter()] [WinSCP.TransferOptions] $TransferOptions = (New-Object -TypeName WinSCP.TransferOptions) ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { $RemotePath = Format-WinSCPPathString -Path $($RemotePath) if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $RemotePath)) { Write-Error -Message "Cannot find path: $RemotePath because it does not exist." continue } try { $localPathInfo = Get-Item -Path $LocalPath -ErrorAction Stop if (-not ($localPathInfo.PSIsContainer)){ Write-Error -Message "$($localPathInfo.FullName) must be a directory." continue } } catch { Write-Error -Message "Cannot find path: $LocalPath because it does not exist." continue } try { $WinSCPSession.SynchronizeDirectories($Mode, $localPathInfo.FullName, $RemotePath, $Remove.IsPresent, $Mirror.IsPresent, $Criteria, $TransferOptions) } catch { Write-Error -Message $_.ToString() } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/WinSCP/5.9.5.6/Public/New-WinSCPItem.ps1
New-WinSCPItem.ps1
Function New-WinSCPItem { [CmdletBinding( SupportsShouldProcess = $true, HelpUri = 'https://github.com/dotps1/WinSCP/wiki/New-WinSCPItem' )] [OutputType( [WinSCP.RemoteFileInfo] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateScript({ if ($_.Opened) { return $true } else { throw 'The WinSCP Session is not in an Open state.' } })] [WinSCP.Session] $WinSCPSession, [Parameter( ValueFromPipelineByPropertyName = $true )] [String[]] $Path = '/', [Parameter( ValueFromPipelineByPropertyName = $true )] [String] $Name = $null, [Parameter()] [String] $ItemType = 'File', [Parameter()] [String] $Value = $null, [Parameter()] [Switch] $Force, [Parameter()] [WinSCP.TransferOptions] $TransferOptions = (New-Object -TypeName WinSCP.TransferOptions) ) Begin { $sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession') } Process { foreach ($item in (Format-WinSCPPathString -Path $($Path))) { if ($PSBoundParameters.ContainsKey('Name')) { $item = Format-WinSCPPathString -Path $(Join-Path -Path $item -ChildPath $Name) } if (-not (Test-WinSCPPath -WinSCPSession $WinSCPSession -Path (Split-Path -Path $item -Parent))) { Write-Error -Message "Could not find a part of the path '$item'" continue } if ((Test-WinSCPPath -WinSCPSession $WinSCPSession -Path $item) -and -not $Force.IsPresent) { Write-Error -Message "An item with the spcified name '$item' already exists." continue } try { $newItemParams = @{ Path = $env:TEMP Name = (Split-Path -Path $item -Leaf) ItemType = $ItemType Value = $Value Force = $true } if ($PSCmdlet.ShouldProcess($item)) { $result = $WinSCPSession.PutFiles((New-Item @newItemParams).FullName, $item, $true, $TransferOptions) if ($result.IsSuccess) { Get-WinSCPItem -WinSCPSession $WinSCPSession -Path $item } else { Write-Error $result.Check() continue } } } catch { Write-Error -Message $_.ToString() } } } End { if (-not ($sessionValueFromPipeLine)) { Remove-WinSCPSession -WinSCPSession $WinSCPSession } } }
PowerShellCorpus/PowerShellGallery/FastLookup/1.2/Test-FastLookup.ps1
Test-FastLookup.ps1
function Test-FastLookup { <# .SYNOPSIS Designed to optimize the speed of searching an array. .DESCRIPTION Improve the speed of looking up a value in an array by creating a hashtable index. Good for looping through very large arrays or CSV files .NOTES Version: 1.2 Author: Miles Gratz Creation Date: April 20, 2017 Purpose/Change: Improve examples .OUTPUTS 1. Creates a sample array 2. Measures speed of searching array with Where-Object, Foreach/If, and Get-FastLookup .EXAMPLE PS> Test-FastLookup -ArraySize 100000 -SearchSize 10000 Creating 'speedtest' array (total array size: 100000; search size: 10000) Example object: DeviceName : DeviceName9475 Type : Security Camera IP : 10.10.128.62 VLAN : VLAN86 Location : Los Angeles Patch Window : Saturday Warranty Service Level : 24x7 Warranty Days Left : 124 Primary Technical Contact : Chris Application Manager : Doug Severity Level : Harry Technical Emergency Contact Number : P1 Manager Emergency Contact Number : 515-249-1602 --------------------------------------------------------------- Measuring speed of Where-Object lookup: $Results = $Array | Where-Object { $_.DeviceName -in $Search } Days : 0 Hours : 0 Minutes : 4 Seconds : 18 Milliseconds : 366 --------------------------------------------------------------- Measuring speed of Foreach/If lookup: [System.Collections.ArrayList]$Results = @() foreach ($Item in $Array) { If ($Item.DeviceName -in $Search) { [void]$Results.Add($Item) } } Days : 0 Hours : 0 Minutes : 4 Seconds : 14 Milliseconds : 148 --------------------------------------------------------------- Measuring speed of Get-FastLookup lookup: $Hashtable = New-FastLookup -Array $Array -Header "DeviceName" [System.Collections.ArrayList]$Results = @() foreach ($Item in $Search) { [void]$Results.Add((Get-FastLookup -Value $Item -Array $Array -Table $Hashtable)) } Days : 0 Hours : 0 Minutes : 0 Seconds : 52 Milliseconds : 773 -------------------------------------------------------------- [NOTE] Performance test on Windows 10 x64 (i5-6200U/8GB/SSD) #> param( # Default sample size of 100K, searching for 10K objects [int]$ArraySize = 100000, [int]$SearchSize = 10000 ) # Define empty ArrayList for sample array [System.Collections.ArrayList]$csvLines = @() # Create array based on quantity $Index = 0 Write-Output "Creating 'speedtest' array (total array size: $ArraySize; search size: $SearchSize)" while ($Index -lt $ArraySize) { # Calculate percentage $PercentageIndex = $Percentage $Percentage = [math]::Round((($Index / $ArraySize)*100)) # Announce percentage If ($Percentage -gt $PercentageIndex) { Write-Output "Creating 'speedtest' array ($Percentage%)" } # Example template $DeviceNumber = Get-Random -Maximum $($ArraySize*5) $Type = Get-Random 'Laptop','Workstation','Network Switch','Wireless Access Point','Security Camera','Server' $IP = "10.10.128." + (Get-Random (1..254)) $VLAN = "VLAN" + (Get-Random (1..100)) $Location = Get-Random 'Chicago','New York','Los Angeles' $PatchWindow = Get-Random 'Sunday','Saturday' $WarrantyServiceLevel = Get-Random '24x7','Next Business Day','Parts Only' $WarrantyDaysLeft = Get-Random -Minimum -100 -Maximum 1095 $PrimaryTech = Get-Random 'Angela','Bob','Chris' $SecondaryTech = Get-Random 'Doug','Eileen','Francis' $AppManager = Get-Random 'Grace','Harry','Isabel' $SeverityLevel = Get-Random 'P1','P2','P3','P4' $TechEmergencyNum = "515-249-" + (0..9 | Get-Random) + (0..9 | Get-Random) + (0..9 | Get-Random) + (0..9 | Get-Random) $MgrEmergencyNum = "515-249-" + (0..9 | Get-Random) + (0..9 | Get-Random) + (0..9 | Get-Random) + (0..9 | Get-Random) # Create custom object to add to array $csvLine = (('"DeviceName' + $DeviceNumber), $Type, $IP, $VLAN, $Location, $PatchWindow, $WarrantyServiceLevel, $WarrantyDaysLeft, $PrimaryTech, $SecondaryTech, $AppManager, $SeverityLevel, $TechEmergencyNum, ($MgrEmergencyNum + '"')) -join '","' # Add object to array [void]$csvLines.Add($csvLine) # Increment loop $Index++ } # Convert lines to CSV [string[]]$stringArray += '"DeviceName","Type","IP","VLAN","Location","Patch Window","Warranty Service Level","Warranty Days Left","Primary Technical Contact","Application Manager","Severity Level","Technical Emergency Contact Number","Manager Emergency Contact Number"' $stringArray += $csvLines [array]$Array = $stringArray | ConvertFrom-Csv # Create list of random server names $Index = 0 [System.Collections.ArrayList]$Search = @() while ($Index -lt $SearchSize) { $RandomIndex = Get-Random -Minimum 0 -Maximum ($Array.Count-1) $Random = $Array[$RandomIndex] [void]$Search.Add($Random.DeviceName) $Index++ } # Example object Write-Output "" Write-Output "Example object:" Write-Output $Array[0] # Measuring speed of Where-Object lookup Write-Output "" Write-Output ('-'*80) Write-Output 'Measuring speed of Where-Object lookup:' Write-Output "" Write-Output ('$Results = $Array | Where-Object { $_.DeviceName -in $Search }') $MeasureWhereObject = Measure-Command { $Results = $Array | Where-Object { $_.DeviceName -in $Search } } | Select-Object Days,Hours,Minutes,Seconds,Milliseconds Write-Output $MeasureWhereObject Write-Output "" Write-Output "Number of results: $($Results.Count)" Write-Output "First result:" Write-Output "" Write-Output $Results[0] # Measuring speed of ForEach lookup Write-Output "" Write-Output ('-'*80) Write-Output 'Measuring speed of Foreach/If lookup:' Write-Output "" Write-Output '[System.Collections.ArrayList]$Results = @()' Write-Output 'foreach ($Item in $Array)' Write-Output '{' Write-Output ' If ($Item.DeviceName -in $Search)' Write-Output ' {' Write-Output ' [void]$Results.Add($Item)' Write-Output ' }' Write-Output '}' $MeasureForeachIf = Measure-Command { [System.Collections.ArrayList]$Results = @() foreach ($Item in $Array) { If ($Item.DeviceName -in $Search) { [void]$Results.Add($Item) } } } | Select-Object Days,Hours,Minutes,Seconds,Milliseconds Write-Output $MeasureForeachIf Write-Output "" Write-Output "Number of results: $($Results.Count)" Write-Output "First result:" Write-Output "" Write-Output $Results[0] # Measuring speed of Get-FastLookup Write-Output "" Write-Output ('-'*80) Write-Output 'Measuring speed of Get-FastLookup lookup:' Write-Output "" Write-Output '$Hashtable = New-FastLookup -Array $Array -Header "DeviceName"' Write-Output '[System.Collections.ArrayList]$Results = @()' Write-Output 'foreach ($Item in $Search)' Write-Output '{' Write-Output ' [void]$Results.Add((Get-FastLookup -Value $Item -Array $Array -Table $Hashtable))' Write-Output '}' $MeasureFastLookup = Measure-Command { $Hashtable = New-FastLookup -Array $Array -Header "DeviceName" [System.Collections.ArrayList]$Results = @() foreach ($Item in $Search) { [void]$Results.Add((Get-FastLookup -Value $Item -Array $Array -Table $Hashtable)) } } | Select-Object Days,Hours,Minutes,Seconds,Milliseconds Write-Output "" Write-Output $MeasureFastLookup Write-Output "" Write-Output "Number of results: $($Results.Count)" Write-Output "First result:" Write-Output "" Write-Output $Results[0] }
PowerShellCorpus/PowerShellGallery/FastLookup/1.2/New-FastLookup.ps1
New-FastLookup.ps1
function New-FastLookup { <# .SYNOPSIS Designed to optimize the speed of searching an array. .DESCRIPTION Improve the speed of looking up a value in an array by creating a hashtable index. Good for looping through very large arrays or CSV files .NOTES Version: 1.2 Author: Miles Gratz Creation Date: April 20, 2017 Purpose/Change: Improve examples .PARAMETER Array A mandatory parameter specifying input array used to create 'FastLookup' .PARAMETER Header An optional parameter specifying the header in the input array used to create 'FastLookup' .OUTPUTS A hashtable, listing the values in the array and their corresponding index .EXAMPLE PS> $array = 1..1000000 $hashtable = New-FastLookup -Array $array Get-FastLookup -Value 2017 -Array $array -Table $hashtable .EXAMPLE PS> # Search for thousand random numbers in an array of one million $array = 1..1000000 $search = 1..1000 | ForEach-Object { Get-Random -Maximum $array.Count } --------------------------------------------------------------- Where-Object Performance Test Measure-Command { $array | Where-Object { $_ -in $search } } Minutes : 2 Seconds : 39 Milliseconds : 658 --------------------------------------------------------------- ForEach Performance Test Measure-Command { foreach ($item in $array){ if ($item -in $search){ $item } } } Minutes : 1 Seconds : 27 Milliseconds : 460 --------------------------------------------------------------- FastLookup Performance Test Measure-Command { $hashtable = New-FastLookup -Array $array foreach ($item in $search){ Get-FastLookup -Value $item -Array $array -Table $hashtable } } Minutes : 0 Seconds : 49 Milliseconds : 933 --------------------------------------------------------------- [NOTE] Performance test on Windows 10 x64 (i5-6200U/8GB/SSD) #> param( [Parameter(Mandatory=$true)] [array]$Array, $Header ) # Identify headers in input array $Headers = $Array | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' # Define empty hashtable and index $HashTable = @{} $Index = 0 #1: Header specified #2: Header exists in array If (($Header -ne $null) -and ($Header -in $Headers)) { # Redefine array with only data from specified Header $Array = $Array.$Header } #1: Header is specified #2: Header does NOT exist in array ElseIf (($Header -ne $null) -and ($Header -notin $Headers)) { # Exit function with error Write-Error "Specified header ($Header) does not exist in input array." Break } #1: Header is NOT specified #2: Array contains multiple Headers ElseIf (($Header -eq $null) -and ($Headers.Count -gt 1)) { # Exit function with error Write-Error "Input array requires the -Header parameter (multiple columns detected)." Break } # Loop through array foreach ($Item in $Array) { # Add index of Item to hashtable # Name Value # ---- ----- # Server1 953 # Server2 1157 Try { $HashTable.Add($Item,$Index) } # Duplicate key detected, add to existing value # Name Value # ---- ----- # Server1 953 # Server2 1157,3325 Catch { $HashTable[$Item] = ($HashTable[$Item],$Index -join ",") } # Increment loop $Index++ } # Output results $HashTable }
PowerShellCorpus/PowerShellGallery/FastLookup/1.2/Get-FastLookup.ps1
Get-FastLookup.ps1
function Get-FastLookup { <# .SYNOPSIS Designed to optimize the speed of searching an array. .DESCRIPTION Improve the speed of looking up a value in an array by creating a hashtable index. Good for looping through very large arrays or CSV files .NOTES Version: 1.2 Author: Miles Gratz Creation Date: April 20, 2017 Purpose/Change: Improve examples .PARAMETER Array A mandatory parameter specifying the array used to create a 'FastLookup' (hashtable index) .PARAMETER Table A mandatory parameter specifying the 'FastLookup' created by New-FastLookup .PARAMETER Value A mandatory parameter specifying the search criteria (e.g. "Server458") .OUTPUTS The object(s) in the array that match the search .EXAMPLE PS> $array = 1..1000000 $hashtable = New-FastLookup -Array $array Get-FastLookup -Value 2017 -Array $array -Table $hashtable .EXAMPLE PS> # Search for thousand random numbers in an array of one million $array = 1..1000000 $search = 1..1000 | ForEach-Object { Get-Random -Maximum $array.Count } --------------------------------------------------------------- Where-Object Performance Test Measure-Command { $array | Where-Object { $_ -in $search } } Minutes : 2 Seconds : 39 Milliseconds : 658 --------------------------------------------------------------- ForEach Performance Test Measure-Command { foreach ($item in $array){ if ($item -in $search){ $item } } } Minutes : 1 Seconds : 27 Milliseconds : 460 --------------------------------------------------------------- FastLookup Performance Test Measure-Command { $hashtable = New-FastLookup -Array $array foreach ($item in $search){ Get-FastLookup -Value $item -Array $array -Table $hashtable } } Minutes : 0 Seconds : 49 Milliseconds : 933 --------------------------------------------------------------- [NOTE] Performance test on Windows 10 x64 (i5-6200U/8GB/SSD) #> param( [Parameter(Mandatory=$true)] $Value, [Parameter(Mandatory=$true)] [Array]$Array, [Parameter(Mandatory=$true)] [Hashtable]$Table ) Try { # Lookup Value in hashtable $Index = $Table[$Value] # Find quantity of Index values $IndexQty = ($Index -split ",").Count # Find objects in Array based on Index # (if multiple, split into array) If ($IndexQty -eq 1){ $Array[$Index] } If ($IndexQty -ge 2){ $Array[$Index -split ","] } } Catch { $null } }
PowerShellCorpus/PowerShellGallery/ciSCSI/1.2.1.95/Examples/Sample_ciSCSIInitiator.ps1
Sample_ciSCSIInitiator.ps1
configuration Sample_ciSCSIInitiator { Param ( [String] $NodeName = 'LocalHost' ) Import-DscResource -Module ciSCSI Node $NodeName { Service iSCSIService { Name = 'MSiSCSI' StartupType = 'Automatic' State = 'Running' } ciSCSIInitiator iSCSIInitiator { Ensure = 'Present' NodeAddress = 'iqn.1991-05.com.microsoft:fileserver01-cluster-target' TargetPortalAddress = '192.168.128.10' InitiatorPortalAddress = '192.168.128.20' IsPersistent = $true iSNSServer = 'isns.contoso.com' DependsOn = "[Service]iSCSIService" } # End of ciSCSIInitiator Resource } # End of Node } # End of Configuration