full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassificationProperty.config.ps1
|
BMD_cFSRMClassificationProperty.config.ps1
|
$classificationproperty = @{
Name = 'IntegrationTest'
DisplayName = 'Integration Test'
Type = 'SingleChoice'
Ensure = 'Present'
Description = 'Integration Test Property'
PossibleValue = @( 'Value1', 'Value2', 'Value3' )
Parameters = @( 'Parameter1=Value1', 'Parameter2=Value2')
}
Configuration BMD_cFSRMClassificationProperty_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMClassificationProperty Integration_Test {
Name = $classificationproperty.Name
DisplayName = $classificationproperty.DisplayName
Type = $classificationproperty.Type
Ensure = $classificationproperty.Ensure
Description = $classificationproperty.Description
PossibleValue = $classificationproperty.PossibleValue
Parameters = $classificationproperty.Parameters
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaTemplate.Integration.Tests.ps1
|
BMD_cFSRMQuotaTemplate.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMQuotaTemplate'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$quotaTemplateNew = Get-FSRMQuotaTemplate -Name $quotaTemplate.Name
$quotaTemplate.Name | Should Be $quotaTemplateNew.Name
$quotaTemplate.Description | Should Be $quotaTemplateNew.Description
$quotaTemplate.Size | Should Be $quotaTemplateNew.Size
$quotaTemplate.SoftLimit | Should Be $quotaTemplateNew.SoftLimit
(Compare-Object `
-ReferenceObject $quotaTemplate.ThresholdPercentages `
-DifferenceObject $quotaTemplateNew.Threshold.Percentage).Count | Should Be 0
}
# Clean up
Remove-FSRMQuotaTemplate `
-Name $quotaTemplate.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMAutoQuota.Integration.Tests.ps1
|
BMD_cFSRMAutoQuota.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMAutoQuota'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the AutoQuota details
$autoquotaNew = Get-FSRMAutoQuota -Path $autoquota.Path
$autoquota.Path | Should Be $autoquotaNew.Path
$autoquota.Disabled | Should Be $autoquotaNew.Disabled
$autoquota.Template | Should Be $autoquotaNew.Template
}
# Clean up
Remove-FSRMAutoQuota -Path $autoquota.path -Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassification.config.ps1
|
BMD_cFSRMClassification.config.ps1
|
$classification = @{
Id = 'Default'
Continuous = $False
ContinuousLog = $False
ContinuousLogSize = 2048
ExcludeNamespace = @('[AllVolumes]\$Extend /','[AllVolumes]\System Volume Information /s')
ScheduleMonthly = @( 12,13 )
ScheduleRunDuration = 10
ScheduleTime = '13:00'
}
Configuration BMD_cFSRMClassification_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMClassification Integration_Test {
Id = $classification.Id
Continuous = $classification.Continuous
ContinuousLog = $classification.ContinuousLog
ContinuousLogSize = $classification.ContinuousLogSize
ExcludeNamespace = $classification.ExcludeNamespace
ScheduleMonthly = $classification.ScheduleMonthly
ScheduleRunDuration = $classification.ScheduleRunDuration
ScheduleTime = $classification.ScheduleTime
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileGroup.Integration.Tests.ps1
|
BMD_cFSRMFileGroup.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMFileGroup'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$filegroupNew = Get-FSRMFileGroup -Name $filegroup.Name
$filegroup.Name | Should Be $filegroupNew.Name
$filegroup.Description | Should Be $filegroupNew.Description
$filegroup.IncludePattern | Should Be $filegroupNew.IncludePattern
$filegroup.ExcludePattern | Should Be $filegroupNew.ExcludePattern
}
# Clean up
Remove-FSRMFileGroup `
-Name $filegroup.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMAutoQuota.config.ps1
|
BMD_cFSRMAutoQuota.config.ps1
|
$autoquota = @{
Path = $ENV:Temp
Ensure = 'Present'
Disabled = $false
Template = (Get-FSRMQuotaTemplate | Select-Object -First 1).Name
}
Configuration BMD_cFSRMAutoQuota_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMAutoQuota Integration_Test {
Path = $autoquota.Path
Ensure = $autoquota.Ensure
Disabled = $autoquota.Disabled
Template = $autoquota.Template
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenTemplateAction.Integration.Tests.ps1
|
BMD_cFSRMFileScreenTemplateAction.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMFileScreenTemplateAction'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the File Screen that will be worked with
New-FSRMFileScreenTemplate `
-Name $fileScreenTemplate.Name `
-Description $fileScreenTemplate.Description `
-IncludeGroup $fileScreenTemplate.IncludeGroup
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$fileScreenTemplateNew = Get-FSRMFileScreenTemplate -Name $fileScreenTemplate.Name
$fileScreenTemplateNew.Notification[0].Type | Should Be $fileScreenTemplateAction.Type
$fileScreenTemplateNew.Notification[0].Subject | Should Be $fileScreenTemplateAction.Subject
$fileScreenTemplateNew.Notification[0].Body | Should Be $fileScreenTemplateAction.Body
$fileScreenTemplateNew.Notification[0].MailBCC | Should Be $fileScreenTemplateAction.MailBCC
$fileScreenTemplateNew.Notification[0].MailCC | Should Be $fileScreenTemplateAction.MailCC
$fileScreenTemplateNew.Notification[0].MailTo | Should Be $fileScreenTemplateAction.MailTo
}
# Clean up
Remove-FSRMFileScreenTemplate `
-Name $fileScreenTemplate.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaTemplateAction.Integration.Tests.ps1
|
BMD_cFSRMQuotaTemplateAction.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMQuotaTemplateAction'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the File Screen that will be worked with
New-FSRMQuotaTemplate `
-Name $quotaTemplate.Name `
-Description $quotaTemplate.Description `
-Size $quotaTemplate.Size `
-Threshold (New-FSRMQuotaThreshold -Percentage $quotaTemplate.ThresholdPercentages[0])
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$quotaTemplateNew = Get-FSRMQuotaTemplate -Name $quotaTemplate.Name
$quotaTemplateNew.Threshold[0].Action[0].Type | Should Be $quotaAction.Type
$quotaTemplateNew.Threshold[0].Action[0].Subject | Should Be $quotaAction.Subject
$quotaTemplateNew.Threshold[0].Action[0].Body | Should Be $quotaAction.Body
$quotaTemplateNew.Threshold[0].Action[0].MailBCC | Should Be $quotaAction.MailBCC
$quotaTemplateNew.Threshold[0].Action[0].MailCC | Should Be $quotaAction.MailCC
$quotaTemplateNew.Threshold[0].Action[0].MailTo | Should Be $quotaAction.MailTo
}
# Clean up
Remove-FSRMQuotaTemplate `
-Name $quotaTemplate.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenAction.config.ps1
|
BMD_cFSRMFileScreenAction.config.ps1
|
$fileScreen = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
Active = $false
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
Template = (Get-FSRMFileScreenTemplate | Select-Object -First 1).Name
MatchesTemplate = $false
}
$fileScreenAction = @{
Type = 'Email'
Subject = '[FileScreen Threshold]% FileScreen threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [FileScreen Threshold]% FileScreen threshold for FileScreen on [FileScreen Path] on server [Server]. The FileScreen limit is [FileScreen Limit MB] MB and the current usage is [FileScreen Used MB] MB ([FileScreen Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
}
Configuration BMD_cFSRMFileScreenAction_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileScreenAction Integration_Test {
Path = $fileScreen.Path
Type = $fileScreenAction.Type
Subject = $fileScreenAction.Subject
Body = $fileScreenAction.Body
MailBCC = $fileScreenAction.MailBCC
MailCC = $fileScreenAction.MailCC
MailTo = $fileScreenAction.MailTo
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMSettings.Integration.Tests.ps1
|
BMD_cFSRMSettings.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMSettings'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Backup existing Settings
$settingsOld = Get-FSRMSetting
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$settingsNew = Get-FSRMSetting
$settings.SmtpServer | Should Be $settingsNew.SmtpServer
$settings.AdminEmailAddress | Should Be $settingsNew.AdminEmailAddress
$settings.FromEmailAddress | Should Be $settingsNew.FromEmailAddress
$settings.CommandNotificationLimit | Should Be $settingsNew.CommandNotificationLimit
$settings.EmailNotificationLimit | Should Be $settingsNew.EmailNotificationLimit
$settings.EventNotificationLimit | Should Be $settingsNew.EventNotificationLimit
}
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassificationProperty.Integration.Tests.ps1
|
BMD_cFSRMClassificationProperty.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMClassificationProperty'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Classification Property details
$classificationPropertyNew = Get-FSRMClassificationPropertyDefinition -Name $classificationProperty.Name
$classificationProperty.Name | Should Be $classificationPropertyNew.Name
$classificationProperty.DisplayName | Should Be $classificationPropertyNew.DisplayName
$classificationProperty.Type | Should Be $classificationPropertyNew.Type
$classificationProperty.Description | Should Be $classificationPropertyNew.Description
(Compare-Object `
-ReferenceObject $classificationProperty.PossibleValue `
-DifferenceObject $classificationPropertyNew.PossibleValue.Name).Count | Should Be 0
(Compare-Object `
-ReferenceObject $classificationProperty.Parameters `
-DifferenceObject $classificationPropertyNew.Parameters).Count | Should Be 0
}
# Clean up
Remove-FSRMClassificationPropertyDefinition `
-Name $classificationProperty.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenException.Integration.Tests.ps1
|
BMD_cFSRMFileScreenException.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMFileScreenException'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the File Screen that will be worked with
New-FSRMFileScreen `
-Path $fileScreen.Path `
-Description $fileScreen.Description `
-IncludeGroup $fileScreen.IncludeGroup `
-Template $fileScreen.Template
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$fileScreenExceptionNew = Get-FSRMFileScreenException -Path $fileScreenException.Path
$fileScreenException.Path | Should Be $fileScreenExceptionNew.Path
$fileScreenException.Description | Should Be $fileScreenExceptionNew.Description
$fileScreenException.IncludeGroup | Should Be $fileScreenExceptionNew.IncludeGroup
}
# Clean up
Remove-FSRMFileScreenException `
-Path $fileScreenException.Path `
-Confirm:$false
Remove-FSRMFileScreen `
-Path $fileScreen.Path `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuota.config.ps1
|
BMD_cFSRMQuota.config.ps1
|
$quota = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
Size = 5GB
SoftLimit = $false
ThresholdPercentages = [System.Collections.ArrayList]@( 100 )
Disabled = $false
}
Configuration BMD_cFSRMQuota_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMQuota Integration_Test {
Path = $quota.Path
Description = $quota.Description
Ensure = $quota.Ensure
Size = $quota.Size
SoftLimit = $quota.SoftLimit
ThresholdPercentages = $quota.ThresholdPercentages
Disabled = $quota.Disabled
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassificationRule.Tests.ps1
|
BMD_cFSRMClassificationRule.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMclassificationRule'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the Classification Property that will be worked with
New-FSRMClassificationPropertyDefinition `
-Name $classificationProperty.Name `
-Type $classificationProperty.Type `
-PossibleValue @(New-FSRMClassificationPropertyValue -Name $classificationProperty.PossibleValue[0])
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$classificationRuleNew = Get-FSRMclassificationRule -Name $classificationRule.Name
$classificationRule.Name | Should Be $classificationRuleNew.Name
$classificationRule.Description | Should Be $classificationRuleNew.Description
$classificationRule.ClassificationMechanism | Should Be $classificationRuleNew.ClassificationMechanism
$classificationRule.ContentRegularExpression | Should Be $classificationRuleNew.ContentRegularExpression
$classificationRule.ContentString | Should Be $classificationRuleNew.ContentString
$classificationRule.ContentStringCaseSensitive | Should Be $classificationRuleNew.ContentStringCaseSensitive
$classificationRule.Disabled | Should Be $classificationRuleNew.Disabled
$classificationRule.Flags | Should Be $classificationRuleNew.Flags
$classificationRule.Namespace | Should Be $classificationRuleNew.Namespace
$classificationRule.Parameters | Should Be $classificationRuleNew.Parameters
$classificationRule.Property | Should Be $classificationRuleNew.Property
$classificationRule.PropertyValue | Should Be $classificationRuleNew.PropertyValue
$classificationRule.ReevaluateProperty | Should Be $classificationRuleNew.ReevaluateProperty
}
# Clean up
Remove-FSRMClassificationRule `
-Name $classificationRule.Name `
-Confirm:$false
Remove-FSRMClassificationPropertyDefinition `
-Name $classificationProperty.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassificationPropertyValue.config.ps1
|
BMD_cFSRMClassificationPropertyValue.config.ps1
|
$classificationproperty = @{
Name = 'IntegrationTest'
Type = 'SingleChoice'
PossibleValue = @( 'Value1' )
}
$classificationPropertyValue = @{
PropertyName = $classificationproperty.Name
Name = $classificationproperty.PossibleValue[0]
Description = 'Top Secret Description'
}
Configuration BMD_cFSRMClassificationPropertyValue_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMClassificationPropertyValue Integration_Test {
Name = $classificationPropertyValue.Name
PropertyName = $classificationPropertyValue.PropertyName
Description = $classificationpropertyValue.Description
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassification.Integration.Tests.ps1
|
BMD_cFSRMClassification.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMClassification'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Backup existing Classification
$classificationOld = Get-FSRMClassification
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Classification details
$classificationNew = Get-FSRMClassification
$classification.Continuous | Should Be $classificationNew.Continuous
$classification.ContinuousLog | Should Be $classificationNew.ContinuousLog
$classification.ContinuousLogSize | Should Be $classificationNew.ContinuousLogSize
(Compare-Object `
-ReferenceObject $classification.ExcludeNamespace `
-DifferenceObject $classificationNew.ExcludeNamespace).Count | Should Be 0
(Compare-Object `
-ReferenceObject $classification.ScheduleMonthly `
-DifferenceObject $classificationNew.Schedule.Monthly).Count | Should Be 0
$classification.ScheduleRunDuration | Should Be $classificationNew.Schedule.RunDuration
$classification.ScheduleTime | Should Be $classificationNew.Schedule.Time
}
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenTemplate.config.ps1
|
BMD_cFSRMFileScreenTemplate.config.ps1
|
$fileScreenTemplate = @{
Name = 'IntegrationTest'
Description = 'Integration Test'
Ensure = 'Present'
Active = $false
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
}
Configuration BMD_cFSRMFileScreenTemplate_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileScreenTemplate Integration_Test {
Name = $fileScreenTemplate.Name
Description = $fileScreenTemplate.Description
Ensure = $fileScreenTemplate.Ensure
Active = $fileScreenTemplate.Active
IncludeGroup = $fileScreenTemplate.IncludeGroup
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaTemplate.config.ps1
|
BMD_cFSRMQuotaTemplate.config.ps1
|
$quotaTemplate = @{
Name = 'IntegrationTest'
Description = 'Integration Test'
Ensure = 'Present'
Size = 5GB
SoftLimit = $false
ThresholdPercentages = [System.Collections.ArrayList]@( 85, 100 )
}
Configuration BMD_cFSRMQuotaTemplate_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMQuotaTemplate Integration_Test {
Name = $quotaTemplate.Name
Description = $quotaTemplate.Description
Ensure = $quotaTemplate.Ensure
Size = $quotaTemplate.Size
SoftLimit = $quotaTemplate.SoftLimit
ThresholdPercentages = $quotaTemplate.ThresholdPercentages
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuota.Integration.Tests.ps1
|
BMD_cFSRMQuota.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMQuota'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$quotaNew = Get-FSRMQuota -Path $quota.Path
$quota.Path | Should Be $quotaNew.Path
$quota.Description | Should Be $quotaNew.Description
$quota.Size | Should Be $quotaNew.Size
$quota.SoftLimit | Should Be $quotaNew.SoftLimit
(Compare-Object `
-ReferenceObject $quota.ThresholdPercentages `
-DifferenceObject $quotaNew.Threshold.Percentage).Count | Should Be 0
$quota.Disabled | Should Be $quotaNew.Disabled
}
# Clean up
Remove-FSRMQuota `
-Path $quota.Path `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenTemplateAction.config.ps1
|
BMD_cFSRMFileScreenTemplateAction.config.ps1
|
$fileScreenTemplate = @{
Name = 'IntegrationTest'
Description = 'Integration Test'
Ensure = 'Present'
Active = $false
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
}
$fileScreenTemplateAction = @{
Type = 'Email'
Subject = '[FileScreen Threshold]% FileScreen threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [FileScreen Threshold]% FileScreen threshold for FileScreen on [FileScreen Path] on server [Server]. The FileScreen limit is [FileScreen Limit MB] MB and the current usage is [FileScreen Used MB] MB ([FileScreen Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
}
Configuration BMD_cFSRMFileScreenTemplateAction_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileScreenTemplateAction Integration_Test {
Name = $fileScreenTemplate.Name
Type = $fileScreenTemplateAction.Type
Subject = $fileScreenTemplateAction.Subject
Body = $fileScreenTemplateAction.Body
MailBCC = $fileScreenTemplateAction.MailBCC
MailCC = $fileScreenTemplateAction.MailCC
MailTo = $fileScreenTemplateAction.MailTo
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaTemplateAction.config.ps1
|
BMD_cFSRMQuotaTemplateAction.config.ps1
|
$quotaTemplate = @{
Name = 'IntegrationTest'
Description = 'Integration Test'
Ensure = 'Present'
Size = 5GB
SoftLimit = $false
ThresholdPercentages = [System.Collections.ArrayList]@( 100 )
}
$quotaAction = @{
Type = 'Email'
Subject = '[FileScreen Threshold]% FileScreen threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [FileScreen Threshold]% FileScreen threshold for FileScreen on [FileScreen Path] on server [Server]. The FileScreen limit is [FileScreen Limit MB] MB and the current usage is [FileScreen Used MB] MB ([FileScreen Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
}
Configuration BMD_cFSRMQuotaTemplateAction_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMQuotaTemplateAction Integration_Test {
Name = $quotaTemplate.Name
Percentage = $quotaTemplate.ThresholdPercentages[0]
Type = $quotaAction.Type
Subject = $quotaAction.Subject
Body = $quotaAction.Body
MailBCC = $quotaAction.MailBCC
MailCC = $quotaAction.MailCC
MailTo = $quotaAction.MailTo
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenException.config.ps1
|
BMD_cFSRMFileScreenException.config.ps1
|
$fileScreen = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
Active = $false
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
Template = (Get-FSRMFileScreenTemplate | Select-Object -First 1).Name
MatchesTemplate = $false
}
$fileScreenException = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
}
Configuration BMD_cFSRMFileScreenException_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileScreenException Integration_Test {
Path = $fileScreenException.Path
Description = $fileScreenException.Description
Ensure = $fileScreenException.Ensure
IncludeGroup = $fileScreenException.IncludeGroup
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenAction.Integration.Tests.ps1
|
BMD_cFSRMFileScreenAction.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMFileScreenAction'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the File Screen that will be worked with
New-FSRMFileScreen `
-Path $fileScreen.Path `
-Description $fileScreen.Description `
-IncludeGroup $fileScreen.IncludeGroup `
-Template $fileScreen.Template
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$fileScreenNew = Get-FSRMFileScreen -Path $fileScreen.Path
$fileScreenNew.Notification[1].Type | Should Be $fileScreenAction.Type
$fileScreenNew.Notification[1].Subject | Should Be $fileScreenAction.Subject
$fileScreenNew.Notification[1].Body | Should Be $fileScreenAction.Body
$fileScreenNew.Notification[1].MailBCC | Should Be $fileScreenAction.MailBCC
$fileScreenNew.Notification[1].MailCC | Should Be $fileScreenAction.MailCC
$fileScreenNew.Notification[1].MailTo | Should Be $fileScreenAction.MailTo
}
# Clean up
Remove-FSRMFileScreen `
-Path $fileScreen.Path `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaAction.config.ps1
|
BMD_cFSRMQuotaAction.config.ps1
|
$quota = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
Size = 5GB
SoftLimit = $false
ThresholdPercentages = [System.Collections.ArrayList]@( 100 )
Disabled = $false
}
$quotaAction = @{
Type = 'Email'
Subject = '[FileScreen Threshold]% FileScreen threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [FileScreen Threshold]% FileScreen threshold for FileScreen on [FileScreen Path] on server [Server]. The FileScreen limit is [FileScreen Limit MB] MB and the current usage is [FileScreen Used MB] MB ([FileScreen Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
}
Configuration BMD_cFSRMQuotaAction_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMQuotaAction Integration_Test {
Path = $quota.Path
Percentage = $quota.ThresholdPercentages[0]
Type = $quotaAction.Type
Subject = $quotaAction.Subject
Body = $quotaAction.Body
MailBCC = $quotaAction.MailBCC
MailCC = $quotaAction.MailCC
MailTo = $quotaAction.MailTo
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMClassificationRule.config.ps1
|
BMD_cFSRMClassificationRule.config.ps1
|
$classificationProperty = @{
Name = 'IntegrationTest'
Type = 'SingleChoice'
PossibleValue = @( 'Value1' )
}
$classificationRule = @{
Name = 'IntegrationTest'
Description = 'Test Rule Description'
ClassificationMechanism = 'Content Classifier'
ContentRegularExpression = @( 'Regex1','Regex2' )
ContentString = @( 'String1','String2' )
ContentStringCaseSensitive = @( 'String1','String2' )
Disabled = $false
Flags = @( 1024 )
Namespace = @( '[FolderUsage_MS=User Files]',$ENV:Temp )
Parameters = @( 'FileName=*.doc','FSRMClearruleInternal=0' )
Property = $classificationProperty.Name
PropertyValue = $classificationProperty.PossibleValue[0]
ReevaluateProperty = 'Never'
}
Configuration BMD_cFSRMClassificationRule_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMClassificationRule Integration_Test {
Name = $classificationRule.Name
Description = $classificationRule.Description
ClassificationMechanism = $classificationRule.ClassificationMechanism
ContentRegularExpression = $classificationRule.ContentRegularExpression
ContentString = $classificationRule.ContentString
ContentStringCaseSensitive = $classificationRule.ContentStringCaseSensitive
Disabled = $classificationRule.Disabled
Flags = $classificationRule.Flags
Namespace = $classificationRule.Namespace
Parameters = $classificationRule.Parameters
Property = $classificationRule.Property
PropertyValue = $classificationRule.PropertyValue
ReevaluateProperty = $classificationRule.ReevaluateProperty
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreen.config.ps1
|
BMD_cFSRMFileScreen.config.ps1
|
$fileScreen = @{
Path = $ENV:Temp
Description = 'Integration Test'
Ensure = 'Present'
Active = $false
IncludeGroup = [System.Collections.ArrayList]@( 'Audio and Video Files','Executable Files','Backup Files' )
Template = (Get-FSRMFileScreenTemplate | Select-Object -First 1).Name
MatchesTemplate = $false
}
Configuration BMD_cFSRMFileScreen_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileScreen Integration_Test {
Path = $fileScreen.Path
Description = $fileScreen.Description
Ensure = $fileScreen.Ensure
Active = $fileScreen.Active
IncludeGroup = $fileScreen.IncludeGroup
Template = $fileScreen.Template
MatchesTemplate = $fileScreen.MatchesTemplate
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileScreenTemplate.Integration.Tests.ps1
|
BMD_cFSRMFileScreenTemplate.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMFileScreenTemplate'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$fileScreenTemplateNew = Get-FSRMFileScreenTemplate -Name $fileScreenTemplate.Name
$fileScreenTemplate.Name | Should Be $fileScreenTemplateNew.Name
$fileScreenTemplate.Description | Should Be $fileScreenTemplateNew.Description
$fileScreenTemplate.Active | Should Be $fileScreenTemplateNew.Active
$fileScreenTemplate.IncludeGroup | Should Be $fileScreenTemplateNew.IncludeGroup
}
# Clean up
Remove-FSRMFileScreenTemplate `
-Name $fileScreenTemplate.Name `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMFileGroup.config.ps1
|
BMD_cFSRMFileGroup.config.ps1
|
$filegroup = @{
Name = 'Test Group'
Ensure = 'Present'
Description = 'Test Description'
IncludePattern = @('*.eps','*.pdf','*.xps')
ExcludePattern = @('*.epsx')
}
Configuration BMD_cFSRMFileGroup_Config {
Import-DscResource -ModuleName cFSRM
node localhost {
cFSRMFileGroup Integration_Test {
Name = $filegroup.Name
Ensure = $filegroup.Ensure
Description = $filegroup.Description
IncludePattern = $filegroup.IncludePattern
ExcludePattern = $filegroup.ExcludePattern
}
}
}
|
PowerShellCorpus/PowerShellGallery/cFSRM/2.0.1.48/Tests/Integration/BMD_cFSRMQuotaAction.Integration.Tests.ps1
|
BMD_cFSRMQuotaAction.Integration.Tests.ps1
|
$DSCModuleName = 'cFSRM'
$DSCResourceName = 'BMD_cFSRMQuotaAction'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PlagueHO/DscResource.Tests.git')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $DSCModuleName `
-DSCResourceName $DSCResourceName `
-TestType Integration
#endregion
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$DSCResourceName.config.ps1"
. $ConfigFile
Describe "$($DSCResourceName)_Integration" {
# Create the File Screen that will be worked with
New-FSRMQuota `
-Path $quota.Path `
-Description $quota.Description `
-Size $quota.Size `
-Threshold (New-FSRMQuotaThreshold -Percentage $quota.ThresholdPercentages[0])
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
Invoke-Expression -Command "$($DSCResourceName)_Config -OutputPath `$TestEnvironment.WorkingFolder"
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion
It 'Should have set the resource and all the parameters should match' {
# Get the Rule details
$quotaNew = Get-FSRMQuota -Path $quota.Path
$quotaNew.Threshold[0].Action[0].Type | Should Be $quotaAction.Type
$quotaNew.Threshold[0].Action[0].Subject | Should Be $quotaAction.Subject
$quotaNew.Threshold[0].Action[0].Body | Should Be $quotaAction.Body
$quotaNew.Threshold[0].Action[0].MailBCC | Should Be $quotaAction.MailBCC
$quotaNew.Threshold[0].Action[0].MailCC | Should Be $quotaAction.MailCC
$quotaNew.Threshold[0].Action[0].MailTo | Should Be $quotaAction.MailTo
}
# Clean up
Remove-FSRMQuota `
-Path $quota.Path `
-Confirm:$false
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/PesterMatchArray/0.2.2/RunPester.ps1
|
RunPester.ps1
|
function GetLineNumber($stackTrace){
if($stackTrace -match "at line: (\d*)"){
$matches[1];
} else {
$null
}
}
function GetFileName($stackTrace){
if($stackTrace -match "at line: (?:\d*) in (.*)\n"){
$matches[1];
} else {
$null
}
}
function FormatResult ($result){
process {
$lineNumber = GetLineNumber $_.StackTrace
$file = GetFileName $_.StackTrace | Resolve-Path -Relative
$collapsedMessage = $_.FailureMessage -replace "`n"," "
$testDescription = "$($_.Describe):$($_.Name)"
"$file;$lineNumber;${testDescription}:$collapsedMessage"
}
}
Write-Output "Running tests..."
$results = Invoke-Pester -PassThru # can use -Quiet to suppress the default Pester output
$results.TestResult | ?{ -not $_.Passed} | FormatResult
Write-Output "Done"
|
PowerShellCorpus/PowerShellGallery/PesterMatchArray/0.2.2/Publish.ps1
|
Publish.ps1
|
Param(
[Parameter(Mandatory=$true)]
[string]$powershellGalleryKey
)
Publish-Module -NuGetApiKey $powershellGalleryKey -Path ./
|
PowerShellCorpus/PowerShellGallery/PesterMatchArray/0.2.2/Examples.ps1
|
Examples.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$here\PesterMatchArray.psm1" -Force
Describe "MatchArrayOrdered examples" {
It "single item arrays match" {
,@("a") | Should MatchArrayOrdered @("a")
}
It "arrays with the same contents match" {
,@("a", 1) | Should MatchArrayOrdered @("a",1)
}
It "arrays with the same contents in different orders do not match" {
,@("a", 1) | Should Not MatchArrayOrdered @(1,"a")
}
}
Describe "MatchArrayUnordered examples" {
It "single item arrays match" {
,@("a") | Should MatchArrayUnordered @("a")
}
It "arrays with the same contents match" {
,@("a", 1) | Should MatchArrayUnordered @("a",1)
}
It "arrays with the same contents in different orders match" {
,@("a", 1) | Should MatchArrayUnordered @(1,"a")
}
}
|
PowerShellCorpus/PowerShellGallery/PesterMatchArray/0.2.2/PesterMatchArray.ps1
|
PesterMatchArray.ps1
|
function PesterMatchArrayUnordered($value, $expectedMatch) {
$value = @($value)
if($value.Length -ne $expectedMatch.Length){
return $false;
}
for($i=0; $i -lt $expectedMatch.Length; $i++){
if(-not($value -contains $expectedMatch[$i])){
return $false;
}
}
return $true;
}
function PesterMatchArrayUnorderedFailureMessage($value, $expectedMatch) {
$value = @($value)
for($i=0; $i -lt $expectedMatch.Length; $i++){
if(-not($value -contains $expectedMatch[$i])){
return "Expected: {$expectedMatch}. Actual: {$value}. Actual is missing item: $($expectedMatch[$i])"
}
}
for($i=0; $i -lt $value.Length; $i++){
if(-not($expectedMatch -contains $value[$i])){
return "Expected: {$expectedMatch}. Actual: {$value}. Actual contains extra item: $($value[$i])"
}
}
}
function NotPesterMatchArrayUnorderedFailureMessage($value, $expectedMatch) {
return "Expected: ${value} to not match the expression ${expectedMatch}"
}
###################################################################################################
function PesterMatchArrayOrdered($value, $expectedMatch) {
$value = @($value)
if($value.Length -ne $expectedMatch.Length){
return $false;
}
for($i=0; $i -lt $expectedMatch.Length; $i++){
if(-not($value[$i] -eq $expectedMatch[$i])){
return $false;
}
}
return $true;
}
function PesterMatchArrayOrderedFailureMessage($value, $expectedMatch) {
$value = @($value)
for($i=0; $i -lt $expectedMatch.Length -and $i -lt $value.Length; $i++){
if(-not($value[$i] -eq $expectedMatch[$i])){
return "Differs at index $i. Expected: {$expectedMatch}. Actual: {$value}."
}
}
if($value.Length -ne $expectedMatch.Length){
return "Lengths differ - Expected length $($expectedMatch.Length), actual length $($value.Length)";
}
}
function NotPesterMatchArrayOrderedFailureMessage($value, $expectedMatch) {
return "Expected: ${value} to not match the expression ${expectedMatch}"
}
|
PowerShellCorpus/PowerShellGallery/PesterMatchArray/0.2.2/PesterMatchArray.Tests.ps1
|
PesterMatchArray.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
## Test Assertion functions takenb from: https://github.com/pester/Pester/blob/ebfb0997365fea29f25b2aa3065378a3765eff4c/Functions/Assertions/Test-Assertion.ps1
function Test-PositiveAssertion($result) {
if (-not $result) {
throw "Expecting expression to pass, but it failed"
}
}
function Test-NegativeAssertion($result) {
if ($result) {
throw "Expecting expression to pass, but it failed"
}
}
Describe "PesterMatchArrayUnordered" {
It "returns true for matching single item arrays" {
Test-PositiveAssertion (PesterMatchArrayUnordered @("a") @("a"))
}
It "returns true for matching single item and single item array" {
Test-PositiveAssertion (PesterMatchArrayUnordered "a" @("a"))
}
It "returns true for matching single item array and single item" {
Test-PositiveAssertion (PesterMatchArrayUnordered @("a") "a")
}
It "returns true for arrays with the same contents" {
Test-PositiveAssertion (PesterMatchArrayUnordered @("a", 1) @("a",1))
}
It "returns true for arrays with the same contents in different orders" {
Test-PositiveAssertion (PesterMatchArrayUnordered @("a", 1) @(1,"a"))
}
It "returns false if arrays differ in content" {
Test-NegativeAssertion (PesterMatchArrayUnordered @(1) @(2))
}
It "returns false if arrays differ in length" {
Test-NegativeAssertion (PesterMatchArrayUnordered @(1) @(1, 1))
}
}
Describe "PesterMatchArrayOrdered" {
It "returns true for matching single item arrays" {
Test-PositiveAssertion (PesterMatchArrayOrdered @("a") @("a"))
}
It "returns true for matching single item and single item array" {
Test-PositiveAssertion (PesterMatchArrayOrdered "a" @("a"))
}
It "returns true for matching single item array and single item" {
Test-PositiveAssertion (PesterMatchArrayOrdered @("a") "a")
}
It "returns true for arrays with the same contents in the same order" {
Test-PositiveAssertion (PesterMatchArrayOrdered @("a", 1) @("a",1))
}
It "returns false for arrays with the same contents in different orders" {
Test-NegativeAssertion (PesterMatchArrayOrdered @("a", 1) @(1,"a"))
}
It "returns false if arrays differ in content" {
Test-NegativeAssertion (PesterMatchArrayOrdered @(1) @(2))
}
It "returns false if arrays differ in length" {
Test-NegativeAssertion (PesterMatchArrayOrdered @(1) @(1, 1))
}
}
|
PowerShellCorpus/PowerShellGallery/PsConfigHive/0.1.2/main/Get-CurrentHiveName.ps1
|
Get-CurrentHiveName.ps1
|
<#
.SYNOPSIS
Gets the Hive Name for the current scope
.DESCRIPTION
Gets the Hive Name for the current scope, this means that caller stack gets inspected in order to get the
appropriate scope. This cmdlet uses Get-PSCallStack to understand the call hierarchy and determine the caller
scope to use.
- When the caller is on the console or console defined (i.e. console defined functions/script blocks) the script
returns 'ConsoleScope' by default
- When the caller is a defined script file .ps1 the file name will be returned (i.e. myScript.ps1)
- When the caller is a module the name of the module will be returned
.EXAMPLE
PS> Get-CurrentHiveName
Returns the current hive name: 'ConsoleScope' when called from the command line
Returns the current hive name: 'ScriptName.ps1' when called from within a script file
Returns the current hive name: 'ModuleName' when called from within a module
.EXAMPLE
PS> function func { param(); Get-CurrentHiveName }
PS> func
Returns the current hive name: 'ConsoleScope' when called from the command line
Returns the current hive name: 'ScriptName.ps1' when called from within a script file
Returns the current hive name: 'ModuleName' when called from within a module
.EXAMPLE
PS> $block = { Get-CurrentHiveName }
PS> . $block
Returns the current hive name: 'ConsoleScope' when called from the command line
Returns the current hive name: 'ScriptName.ps1' when called from within a script file
Returns the current hive name: 'ModuleName' when called from within a module
.LINK
https://github.com/hobelinm/PsConfigHive
#>
function Get-CurrentHiveName {
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
$scripBlockCmd = '<ScriptBlock>'
$noFileLabel = '<No file>'
$callStacks = Get-PSCallStack
$loadedModules = Get-Module
$foundCommand = $false
Get-PSCallStack | Out-String | Write-Verbose
1..$callStacks.Count | Where-Object { -not $foundCommand } | ForEach-Object {
$callStack = $callStacks[$_]
$commandName = [string] $callStack.Command
if ($commandName -eq $scripBlockCmd -and $callStack.Location -eq $noFileLabel) {
$foundCommand = $true
Write-Output 'ConsoleScope'
}
elseif ($commandName -eq $scripBlockCmd) {
# Find any module that contains the path of the script that contains the execution
$scriptBlockFile = $callStack.InvocationInfo.ScriptName
$sourceModule = $null
$sourceModule = $loadedModules | Where-Object { $_.FileList -contains $scriptBlockFile }
if ($sourceModule -eq $null) {
# Some modules do not disclose the FileList so we need to do something more creative using
# the module's path
$sourceModule = $loadedModules | Where-Object {
$modulePath = ([System.IO.FileInfo] $_.Path).Directory.FullName
if ($callStack.ScriptName.StartsWith($modulePath)) {
return $true
}
else {
return $false
}
}
}
if ($sourceModule -ne $null) {
$foundCommand = $true
Write-Output $sourceModule.Name
}
else {
# Get the script name
$foundCommand = $true
$scriptName = [System.IO.FileInfo] $callStack.ScriptName
Write-Output $scriptName.Name
}
}
elseif ($commandName.EndsWith('.ps1') -or $commandName.EndsWith('.psm1')) {
$foundCommand = $true
Write-Output $commandName
}
else {
# Here we've got two cases:
# a function name exposed by a module/script
# a function name not exposed by it
$loadedModules | Where-Object { -not $foundCommand} | ForEach-Object {
$moduleDefinition = $_
if ($moduleDefinition.ExportedAliases.Keys.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
elseif ($moduleDefinition.ExportedCmdlets.Keys.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
elseif ($moduleDefinition.ExportedCommands.Keys.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
elseif ($moduleDefinition.ExportedDscResources.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
elseif ($moduleDefinition.ExportedFunctions.Keys.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
elseif ($moduleDefinition.ExportedWorkflows.Keys.Contains($commandName)) {
$foundCommand = $true
Write-Output $moduleDefinition.Name
}
}
# Function name was not exposed
if (-not $foundCommand) {
$functionFile = $callStack.InvocationInfo.ScriptName
$sourceModule = $loadedModules | Where-Object { $_.FileList -contains $functionFile }
if ($sourceModule -ne $null) {
Write-Output $sourceModule.Name
$foundCommand = $true
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Get-Font.ps1
|
Get-Font.ps1
|
function Get-Font
{
<#
.Synopsis
Gets the fonts available
.Description
Gets the fonts available on the current installation
.Example
Get-Font
.Example
Get-Font -IncludeDetail
#>
[OutputType([Windows.Media.FontFamily], [string])]
param(
# If set, finds finds with this name
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[string]$Name,
# If set, includes all details about the font.
# If set, will include all details of the font
[switch]$IncludeDetail,
# If set, will sort the results
[Switch]$Sort
)
begin {
$fontList = [Windows.Media.Fonts]::SystemFontFamilies
}
process {
#region Filter Font List
if ($Name.Trim()){
$currentFontList = foreach ($f in $fontList) {
if ($f.Source -like "$name*") {
$f
}
}
} else {
$currentFontList = $fontList
}
#endregion Filter Font List
if ($IncludeDetail) {
if ($sort) {
$currentFontList |
Sort-Object Source |
Add-Member ScriptProperty Name { $this.Source } -PassThru -Force
} else {
$currentFontList |
Add-Member ScriptProperty Name { $this.Source } -PassThru -Force
}
} else {
if ($sort) {
$currentFontList |
Sort-Object Source |
Select-Object -ExpandProperty Source
} else {
$currentFontList |
Select-Object -ExpandProperty Source
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Send-Printer.ps1
|
Send-Printer.ps1
|
function Send-Printer
{
<#
.Synopsis
Sends a image to the printer
.Description
#>
[CmdletBinding(DefaultParameterSetName='FilePath')]
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName='FilePath')]
[Alias('Fullname')]
[string]
$FilePath,
[Switch]
$Landscape,
# The number of copies to make
[Uint32]
$CopyCount = 1,
# If set, then the image will not be printed in color
[Switch]
$BlackAndWhite
)
begin {
}
process {
$printDoc = New-Object Drawing.Printing.PrintDocument
$printDoc.DefaultPageSettings.Landscape = $Landscape
if ($psCmdlet.ParameterSetName -eq 'FilePath') {
$resolvedFile = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($FilePath)
if (-not $resolvedFile) { return }
$bmp = try {
[Drawing.Bitmap]::FromFile("$resolvedFile")
} catch {
}
if (-not $bmp) {
$bmp = try {
Get-Thumbnail -FilePath $resolvedFile
} catch {
}
}
if (-not $bmp) {
return
}
$script:Bmp = $bmp
$printDoc.PrinterSettings.Copies = $CopyCount
$printDoc.DefaultPageSettings.Color = -not $BlackAndWhite
$printDoc.add_PrintPage({
$e = $_
$newWidth = $bmp.Width * 100 / $bmp.HorizontalResolution
$newHeight = $bmp.height * 100 / $bmp.VerticalResolution
if ($Landscape) {
$widthFactor = $newWidth / $e.PageSettings.PrintableArea.height
$HeightFactor = $newHeight / $e.PageSettings.PrintableArea.Width
} else {
$widthFactor = $newWidth / $e.PageSettings.PrintableArea.Width
$HeightFactor = $newHeight / $e.PageSettings.PrintableArea.Height
}
$widthMargin = 0
$heightMargin = 0
if ($widthFactor -ge 1 -or $HeightFactor -ge 1) {
if ($widthFactor -gt $HeightFactor) {
$newWidth = $newWidth / $widthFactor
$newHeight = $newHeight / $widthFactor
} else {
$newWidth = $newWidth / $HeightFactor
$newHeight = $newHeight / $HeightFactor
}
}
if ($Landscape) {
$heightMargin = (($e.PageSettings.PrintableArea.Height - $newHeight) / 2) / 2
} else {
$widthMargin = (($e.PageSettings.PrintableArea.Width - $newWidth) / 2) / 2
}
$h = $e.PageSettings.PrintableArea.Height
$m = ($e.PageSettings.PrintableArea.Height - $h) / 2
$e.Graphics.DrawImage($bmp,
($e.PageSetting.HardMarginX + $widthMargin),
($e.PageSetting.HardMarginY + $heightMargin),
$newWidth,
$newHeight);
})
$bmp.Dispose()
$printDoc.Print()
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Show-Shape.ps1
|
Show-Shape.ps1
|
function Show-Shape {
<#
.Synopsis
Shows shapes
.Description
Shows shapes
.Example
Show-Shape "Red" "Circle"
#>
[OutputType([IO.FileInfo], [byte[]])]
param(
# The type of shape
[Parameter(Mandatory=$true,Position=1)]
[ValidateSet("Circle", "Square", "Rectangle", "Ellipse")]
[string]
$Shape,
# The width of the shape. By default, 175 pixels
[Parameter(Position=2)]
[Double]$Width = 175,
# The width of the shape. By default, 175 pixels
[Parameter(Position=3)]
[Double]$Height = 175,
# The colors used in the shape. More than one color will make a gradient.
[Parameter(Mandatory=$true,Position=0)]
[string[]]
$Color = "#012456",
# The anchor points used in the shape.
[string[]]
$Points = @(30,30,60,60),
# The rotation of the image
[Parameter(ValueFromPipelineByPropertyName=$true,Position=8)]
[Double]$Rotation,
# The Horizontal Skew Angle
[Parameter(ValueFromPipelineByPropertyName=$true,Position=16)]
[Double]$SkewAngleHorizontal,
# The Skew Angle
[Parameter(ValueFromPipelineByPropertyName=$true,Position=17)]
[Double]$SkewAngleVertical,
# The type of image to create
[ValidateSet('Jpeg','Png','Tiff', 'Gif')]
[string]
$AsType = "Png",
# The starting point of the gradient
[string]$GradientStartPoint,
# The ending point of the gradient
[string]$GradientEndPoint,
# A list of gradient stop percents. If this list is not provided, the gradient stops will be evenly distributed.
[ValidateRange(0,100)]
[Uint32[]]$GradientStopPercent,
# The gradient radius's X value
[string]$GradientRadiusX,
# The gradient radius's y value
[string]$GradientRadiusY,
# The gradient radius's center value
[string]$GradientCenter,
# The top of the shape inside of an image
[Double]$Top,
# The left location of the shape inside of an image
[Double]$Left,
# The row within a grid that the shape will occupy.
[int]$Row,
# The column within a grid that the shape will occupy.
[int]$Column,
# The number of rows within a grid that a shape will occupy.
[int]$RowSpan,
# The number of columns within a grid that a shape will occupy.
[int]$ColumnSpan,
# If set, the shape will be shown
[switch]$Show,
# If set, the shape will be displayed in a background job
[switch]$AsJob,
# If set, the shape will be displayed in memory
[switch]$InMemory,
# If provided, the shape will have a name.
[string]$Name,
# If set, outputs the UI Element instead of a screenshot.
[switch]$OutputUI
)
process {
$fill =
if ($color.Count) {
$stops =
if ($GradientStopPercent) {
for ($i = 0 ; $i -lt $color.Count; $i++) {
$n = $GradientStopPercent[$i]
New-GradientStop -Color $color[$i] -Offset $n
}
} else {
$stopAmount = 1 / $Color.Count
$n = 0
for ($i = 0 ; $i -lt $color.Count; $i++) {
New-GradientStop -Color $color[$i] -Offset $n
$n += $stopAmount
}
}
if ($GradientCenter -or $GradientRadiusX -or $GradientRadiusY) {
$radialParameters = @{GradientStops= $stops}
if ($GradientRadiusX) {
$radialParameters.RadiusX = $GradientRadiusX
}
if ($GradientRadiusY) {
$radialParameters.RadiusY = $GradientRadiusY
}
if ($GradientCenter) {
$radialParameters.Center = $GradientCenter
}
New-RadialGradientBrush @radialParameters
} else {
$linearParameters = @{GradientStops= $stops}
if ($GradientStartPoint) {
$linearParameters += @{StartPoint=$GradientStartPoint}
}
if ($GradientEndPoint) {
$linearParameters += @{EndPoint=$GradientEndPoint}
}
New-LinearGradientBrush @linearParameters
}
} else {
"$Color"
}
$shapeParameters= @{
Fill = $fill
}
if ($shape -eq 'ellipse' -or
$shape -eq 'circle') {
$shapeCmd = $executionContext.SessionState.InvokeCommand.GetCommand("New-Ellipse", "All")
$shapeParameters.Width = $width
$shapeParameters.Height = $height
} elseif ($shape -eq 'square' -or
$shape -eq 'Rectangle'
) {
$shapeCmd = $executionContext.SessionState.InvokeCommand.GetCommand("New-Rectangle", "All")
$shapeParameters.Width = $width
$shapeParameters.Height = $Height
} elseif ($shape -eq 'polygon') {
$shapeCmd = $executionContext.SessionState.InvokeCommand.GetCommand("New-Polygon", "All")
$shapeParameters.Width = $width
$shapeParameters.Height = $Height
} elseif ($shape -eq 'polyline') {
}
if ($Rotation) {
$shapeParameters.LayoutTransform = New-RotateTransform -Angle $rotation -CenterX $HorizontalCenter -CenterY $VerticalCenter
} elseif ($SkewAngleVertical) {
$shapeParameters.LayoutTransform = New-SkewTransform -AngleX $SkewAngleHorizontal -AngleY $SkewAngleVertical -CenterX $HorizontalCenter -CenterY $VerticalCenter
}
if (-not $shapeCmd) { return }
$text = "$shape $color ($width*$height)"
if ($outputUI) {
& $shapeCmd @shapeParameters
} else {
$screenShotParameters = @{}
$screenShotParameters."As${asType}" = $true
$safeText = $text -ireplace "[\/\?<>\\\:\*\|`"]", "_"
$guidText = if ($noGuid) {"" } else {
".$([GUID]::NewGuid().ToString().Replace('-',''))"
}
$screenShotParameters.OutputPath = "${safeText}${guidText}.${asType}"
$screenShotParameters.DotsPerInch = $dotsPerInch
$screenShotParameters.InMemory = $InMemory
& $shapeCmd @shapeParameters |
Save-Screenshot @screenShotParameters
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Save-FontPreview.ps1
|
Save-FontPreview.ps1
|
function Save-FontPreview
{
<#
.Synopsis
Saves font preview files
.Description
Saves font preview files to a directory, and makes a web page to display them
.Example
Get-Font |
Sort-Object |
Save-FontPreview
.Link
Get-Font
#>
param(
#|Default Kartika
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
if (-not $script:FontCache) {
$script:FontCache = Get-Font
}
if ($script:FontCache -contains $_) {
return $true
} else {
throw "$_ is not an installed font. Installed fonts: $script:FontCache "
}
})]
[string]$FontFamily,
# The font size
#|Default 36
[ValidateRange(8,72)]
[int]$FontSize = 36,
#|Default The Quick Brown Fox Jumped Over The Lazy Dog
[string]$SampleText = "The Quick Brown Fox Jumped Over The Lazy Dog",
# The directory that should store the font preview
[string]$OutputDirectory
)
begin {
$fontPreviewMarkdown = ""
}
process {
if (-not $psBOundParameters.OutputDirectory) {
$OutputDirectory = $pwd
}
if (-not (Test-Path $OutputDirectory)) {
New-Item -ItemType Directory -Path $OutputDirectory |
Out-Null
}
$fontFamilyFile = Join-Path $OutputDirectory "${FontFamily}.png"
Write-Progress "Generating Font Samples" "$fontFamily"
$bytes = Show-Logo -Text $SampleText -Font $FontFamily -Size $FontSize -AsType png -InMemory
$fontPreviewMarkdown += "
### $FontFamily
! [$FontFamily](${fontFamily}.png)
"
[IO.File]::WriteAllBytes($fontFamilyFile, $bytes)
}
end {
ConvertFrom-Markdown -Markdown $fontPreviewMarkdown |
Set-Content $OutputDirectory\index.html
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Format-Image.ps1
|
Format-Image.ps1
|
function Format-Image
{
<#
.Synopsis
Formats an image at various resolutions
.Description
Resizes an image into various resolutions and image formats.
#>
param(
# The path to the image
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('Fullname')]
[string]
$ImagePath,
# The resolutions requested.
[Parameter(Mandatory=$true)]
[ValidateScript({
$x, $y = $_ -split "x"
if (0, 1 -notcontains $y.Count) {
throw "Not a resolution"
}
if (0, 1 -notcontains $x.Count) {
throw "Not a resolution"
}
if (-not ($x -as [Uint32]) -and ($y -as [Uint32])) {
throw "Not a resolution"
}
return $true
})]
[string[]]
$Resolution,
# The JPEG Quality
[Parameter(ParameterSetName='Jpeg')]
[int]$JpegQuality = 100,
# The dots per inch
[Alias('DPI')]
[int]$DotsPerInch = 96,
[ValidateSet('Jpeg','jpg','Png','Tiff', 'Gif')]
[string]
$AsType = "Png",
# The output path. If this is not set, it will be saved to a randomly named file in the
# current directory.
[string]$OutputPath,
[Switch]$DoNotPreserveAspectRatio
)
process {
$resolvedImagePath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($ImagePath)
$imageFile = Get-Item "$resolvedImagePath"
$nameMinusExtension = $imageFile.Name.Substring(0, $ImageFile.Name.Length - $imageFile.Extension.Length)
foreach ($res in $Resolution) {
if (-not $res) { continue }
# Loop thru each potential image size
$w, $h = $res -split "x"
if (-not $psBoundParameters.OutputPath) {
if (-not $psBoundParameters.AsType) {
$ASType = $imageFile.Extension.TrimStart(".")
}
$outputPath = Join-Path $imageFile.Directory "${nameMinusExtension}_${res}.${asType}"
}
#region Actual Resize
$image = New-Object -ComObject Wia.ImageFile
$image.LoadFile($imageFile.FullName)
$filter = New-Object -ComObject Wia.ImageProcess
$index = $filter.Filters.Count + 1
$scale = $filter.FilterInfos.Item("Scale").FilterId
$filter.Filters.Add($scale)
$filter.Filters.Item($index).Properties.Item("PreserveAspectRatio") = "$(-not $DoNotPreserveAspectRatio)"
$filter.Filters.Item($index).Properties.Item("MaximumWidth") = $w
$filter.Filters.Item($index).Properties.Item("MaximumHeight") = $h
$image = $filter.Apply($image.PSObject.BaseObject)
$image.SaveFile($OutputPath)
#endregion Actual Resize
Get-Item -ErrorAction SilentlyContinue -LiteralPath $OutputPath
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Save-Screenshot.ps1
|
Save-Screenshot.ps1
|
function Save-Screenshot
{
<#
.Synopsis
Saves a screenshot of a UI element
.Description
Saves a screenshot of a WPF UI element to many different file formats
.Example
New-Button -FontFamily "Webdings" -Content ([char]0xcf) -FontSize 36 |
Save-Screenshot -AsPng -outputPath .\LockButton.jpg
#>
[CmdletBinding(DefaultParameterSetName='Jpeg')]
[OutputType([Byte[]], [IO.FileInfo])]
param(
# The inputObject
[Parameter(ValueFromPipeline=$true)]
[Windows.Media.Visual]
$InputObject,
# the pixel format used to save the image
[Windows.Media.PixelFormat]
$pixelFormat = [Windows.Media.PixelFormats]::Default,
# The JPEG Quality
[Parameter(ParameterSetName='Jpeg')]
[int]$JpegQuality = 100,
# The dots per inch
[Alias('DPI')]
[int]$DotsPerInch = 96,
# If set, will save as a jpeg
[Parameter(ParameterSetName='Jpeg')]
[Alias('AsJpg', 'Jpg', 'Jpeg')]
[switch]
$AsJpeg,
# If set, will save as a png
[Parameter(ParameterSetName='Png')]
[Alias('Png')]
[switch]
$AsPng,
# If set, interlaces the output PNG
[Parameter(ParameterSetName='Png')]
[switch]
$Interlace,
# If set, outputs a BMP
[Parameter(ParameterSetName='Bmp')]
[Alias('Bmp')]
[switch]
$AsBmp,
# If set, outputs a GIF
[Parameter(ParameterSetName='Gif')]
[Alias('Gif')]
[switch]
$AsGif,
# If set, outputs a TIFF
[Parameter(ParameterSetName='Tiff')]
[Alias('Tiff', 'Tif')]
[switch]
$AsTiff,
# Changes the Tiff Compression
[Parameter(ParameterSetName='Tiff')]
[Windows.Media.Imaging.TiffCompressOption]
$TiffCompression ='Zip',
# If set, outputs HDPhoto
[Parameter(ParameterSetName='Wmp')]
[Alias('Wmp', 'HDPhoto')]
[switch]
$AsWmp,
# If set, returns the item as a frame
[Parameter(ParameterSetName='Frame')]
[switch]
$AsFrame,
# The output path. If this is not set, it will be saved to a randomly named file in the
# current directory.
[string]$OutputPath,
# If set, will output bytes instead of a file
[switch]$InMemory,
# The amount of time to wait before closing the window
[Timespan]
$ScreenShotTimer = 10
)
process {
#region Process Parameters Before Launching UI
if ($psCmdlet.ParameterSetName -eq 'Jpeg') {
$psBoundParameters.AsJpeg = $true
$asJpeg = $true
}
$psBoundParameters."As$($psCmdlet.ParameterSetName)" = $true
if (-not $psBoundParameters.PixelFormat) {
$psBoundParameters.PixelFormat = $pixelFormat
}
if (-not $psBoundParameters.DotsPerInch) {
$psBoundParameters.DotsPerInch = $DotsPerInch
}
if (-not $psBoundParameters.JpegQuality) {
$psBoundParameters.JpegQuality = $jpegQuality
}
if (-not $psBoundParameters.TiffCompression) {
$psBoundParameters.TiffCompression = $tiffCompression
}
if (-not $psBoundParameters.OutputPath) {
if ($asJpeg) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).jpeg"
} elseif ($asPng) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).png"
} elseif ($asbmp) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).bmp"
} elseif ($astiff) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).tiff"
} elseif ($aswmp) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).wmp"
} elseif ($asgif) {
$psBoundParameters.OutputPath = Join-Path $pwd "Screenshot.$(Get-Random).gif"
} elseif ($asFrame) {
$psBoundParameters.OutputPath = $null
} elseif ($InMemory) {
$psBoundParameters.OutputPath = $null
}
} else {
$psBoundParameters.OutputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($psBoundParameters.OutputPath)
}
#endregion
foreach ($kv in $psBoundParameters.GetEnumerator()) {
$inputObject.Resources[$kv.Key] = $kv.Value
}
if ($Window) {
# Already in ShowUI
} else {
$inputObject.Resources['ScreenshotTimer'] = $screenShotTimer
$inputObject |
Add-EventHandler -EventName On_SizeChanged -Handler {
if ($_.PreviousSize.Width -eq 0 -and $_.PreviousSize.Height -eq 0) {
$visual = $This
$window | Add-EventHandler -EventName On_LocationChanged -Handler { $window.Close() }
$waitScript = [ScriptBlock]::Create("
Start-Sleep -Milliseconds $($ScreenshotTimer.TotalMilliseconds); `$true
")
$this.DataContext = Get-PowerShellDataSource -On_OutputChanged {
$visual = $This
if (-not $visual.Background -and
-not ($AsPng -or $AsGif)) {
if ($visual -and $visual.GetType().GetProperty("Background")) {
try {
# $visual.Background = "White"
} catch {
}
}
}
if (-not $DotsPerInch) { $DotsPerInch = 72 }
$visual.UpdateLayout()
$actualWidth = $visual.ActualWidth
$actualHeight = $visual.ActualHeight
#$visual | select *height* | Out-Host
#$actualWidth, $actualHeight, $DotsPerInch | Out-Host
$renderBitmap =
New-Object Windows.Media.Imaging.RenderTargetBitmap $actualWidth , $actualHeight, $DotsPerInch, $DotsPerInch, ([Windows.Media.PixelFormats]::Pbgra32)
$sourceBrush = New-Object Windows.Media.VisualBrush $visual
#$sourceBrush | Out-Host
$drawingVisual = New-Object Windows.Media.DrawingVisual
$drawingContext = $drawingVisual.RenderOpen()
$rect = New-Object Windows.Rect ((New-Object Windows.Point),(
New-Object Windows.Point $actualWidth, $actualHeight
))
$drawingContext.DrawRectangle($sourceBrush, $null, $rect)
$drawingContext.Close()
$renderBitmap.Render($drawingVisual)
$frame =[Windows.Media.Imaging.BitmapFrame]::Create($renderBitmap)
$fileOrInMemory = {
param($this, $encoder, $inMemory, $outputPath)
$null = $encoder.Frames.Add($frame)
if ($InMemory) {
$memStream = New-Object IO.MemoryStream
$encoder.Save($memStream)
$memStream.Seek(0,0)
$bytes = New-Object Byte[] $memStream.Length
$memStream.Read($bytes, 0, $memStream.Length)
$this.Parent.Tag = $bytes
} else {
$fileStream = [IO.File]::Create($outputPath)
$encoder.Save($fileStream)
$fileStream.Close()
}
}
if ($AsJpeg) {
$jpegEncoder = New-Object Windows.Media.Imaging.JpegBitmapEncoder
$jpegEncoder.QualityLevel = $jpegquality
& $fileOrInMemory $this $jpegEncoder $inMemory $outputPath
} elseif ($AsPng) {
$pngEncoder = New-Object Windows.Media.Imaging.PngBitmapEncoder
if ($interlace) {
$pngEncoder.Interlace = 'On'
}
& $fileOrInMemory $this $pngEncoder $inMemory $outputPath
} elseif ($AsBmp) {
$bmpEncoder = New-Object Windows.Media.Imaging.BmpBitmapEncoder
& $fileOrInMemory $this $bmpEncoder $inMemory $outputPath
} elseif ($asTiff) {
$TiffEncoder = New-Object Windows.Media.Imaging.TiffBitmapEncoder
$TiffEncoder.Compression = $TiffCompression
& $fileOrInMemory $this $TiffEncoder $inMemory $outputPath
} elseif ($asgif) {
$GifEncoder = New-Object Windows.Media.Imaging.GifBitmapEncoder
& $fileOrInMemory $this $GifEncoder $inMemory $outputPath
} elseif ($aswmp) {
$WmpEncoder = New-Object Windows.Media.Imaging.WmpBitmapEncoder
& $fileOrInMemory $this $WmpEncoder $inMemory $outputPath
} elseif ($AsFrame) {
$frame
$this.Parent.Tag = $frame
}
$window.Close()
} -Script $waitScript
}
}
$bytes = $inputObject | Show-Window -WindowProperty @{Sizetocontent='WidthAndHeight'; Top = -10000; Left = -10000}
}
if ($byteS -and ($InMemory -or $asFrame)) {
$bytes
}
$params = $psBoundParameters
if ($psBoundparameters.OutputPath) {
Get-Item -ErrorAction SilentlyContinue $psBoundParameters.OutputPath
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Get-Screenshot.ps1
|
Get-Screenshot.ps1
|
function Get-ScreenShot
{
<#
.Synopsis
Gets a screen capture
.Description
Captures the current screen
.Example
# Capture the whole screen
Get-ScreenShot
.Example
# Capture the current window
Get-ScreenShot -OfWindow
.Example
# Capture a set of coordinates
Get-ScreenShot -OfCoordinates 320, 240
.Link
http://stackoverflow.com/questions/2969321/how-can-i-do-a-screen-capture-in-windows-powershell
#>
[CmdletBinding(DefaultParameterSetName='OfWholeScreen')]
param(
# If set, takes a screen capture of the current window
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='OfWindow')]
[Switch]$OfWindow,
# If set, takes a screenshot of a location on the screen.
# If two numbers are passed, the screenshot will be from 0,0 to first (left), second (top)
# If four numbers are passed, the screenshot will be from first (Left), second(top), third (width), fourth (height)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='OfLocation')]
[Double[]]$OfLocation,
# The path for the screenshot.
# If this isn't set, the screenshot will be automatically saved to a file in the current directory named ScreenCapture
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
$Path,
# The image format used to store the screen capture
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateSet('PNG', 'JPEG', 'TIFF', 'GIF', 'BMP')]
[string]
$ImageFormat = 'JPEG',
# The time before and after each screenshot
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Timespan]$ScreenshotTimer = "0:0:0.125"
)
begin {
Add-Type -AssemblyName System.Drawing, System.Windows.Forms
$saveScreenshotFromClipboard = {
if ([Runspace]::DefaultRunspace.ApartmentState -ne 'STA') {
# The clipboard isn't accessible in MTA, so save the image in background runspace
$cmd = [PowerShell]::Create().AddScript({
$bitmap = [Windows.Forms.Clipboard]::GetImage()
$bitmap.Save($args[0], $args[1], $args[2])
$bitmap.Dispose()
}).AddParameters(@("${screenCapturePathBase}${c}.$ImageFormat",$Codec, $ep))
$runspace = [RunspaceFactory]::CreateRunspace()
$runspace.ApartmentState = 'STA'
$runspace.ThreadOptions = 'ReuseThread'
$runspace.Open()
$cmd.Runspace = $runspace
$cmd.Invoke()
$runspace.Close()
$runspace.Dispose()
$cmd.Dispose()
} else {
$bitmap = [Windows.Forms.Clipboard]::GetImage()
$bitmap.Save("${screenCapturePathBase}${c}.$ImageFormat", $Codec, $ep)
$bitmap.Dispose()
}
}
}
process {
#region Codec Info
$Codec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object { $_.FormatDescription -eq $ImageFormat }
$ep = New-Object Drawing.Imaging.EncoderParameters
if ($ImageFormat -eq 'JPEG') {
$ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
}
#endregion Codec Info
#region PreScreenshot timer
if ($ScreenshotTimer -and $ScreenshotTimer.TotalMilliseconds) {
Start-Sleep -Milliseconds $ScreenshotTimer.TotalMilliseconds
}
#endregion Prescreenshot Timer
#region File name
if (-not $Path) {
$screenCapturePathBase = "$pwd\ScreenCapture"
} else {
$screenCapturePathBase = $Path
}
$c = 0
while (Test-Path "${screenCapturePathBase}${c}.$ImageFormat") {
$c++
}
#endregion
if ($psCmdlet.ParameterSetName -eq 'OfWindow') {
[Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")
#region PostScreenshot timer
if ($ScreenshotTimer -and $ScreenshotTimer.TotalMilliseconds) {
Start-Sleep -Milliseconds $ScreenshotTimer.TotalMilliseconds
}
#endregion Postscreenshot Timer
. $saveScreenshotFromClipboard
Get-Item -ErrorAction SilentlyContinue -Path "${screenCapturePathBase}${c}.$ImageFormat"
} elseif ($psCmdlet.ParameterSetName -eq 'OfLocation') {
if ($OfLocation.Count -ne 2 -and $OfLocation.Count -ne 4) {
Write-Error "Must provide either a width and a height, or a top, left, width, and height"
return
}
if ($OfLocation.Count -eq 2) {
$bounds = New-Object Drawing.Rectangle -Property @{
Width = $OfLocation[0]
Height = $OfLocation[1]
}
} else {
$bounds = New-Object Drawing.Rectangle -Property @{
X = $OfLocation[0]
Y = $OfLocation[1]
Width = $OfLocation[2]
Height = $OfLocation[3]
}
}
$bitmap = New-Object Drawing.Bitmap $bounds.width, $bounds.height
$graphics = [Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)
#region PostScreenshot timer
if ($ScreenshotTimer -and $ScreenshotTimer.TotalMilliseconds) {
Start-Sleep -Milliseconds $ScreenshotTimer.TotalMilliseconds
}
#endregion Postscreenshot Timer
$bitmap.Save("${screenCapturePathBase}${c}.$ImageFormat", $Codec, $ep)
$graphics.Dispose()
$bitmap.Dispose()
Get-Item -ErrorAction SilentlyContinue -Path "${screenCapturePathBase}${c}.$ImageFormat"
} elseif ($psCmdlet.ParameterSetName -eq 'OfWholeScreen') {
[Windows.Forms.Sendkeys]::SendWait("{PrtSc}")
#region PostScreenshot timer
if ($ScreenshotTimer -and $ScreenshotTimer.TotalMilliseconds) {
Start-Sleep -Milliseconds $ScreenshotTimer.TotalMilliseconds
}
#endregion Postscreenshot Timer
. $saveScreenshotFromClipboard
Get-Item -ErrorAction SilentlyContinue -Path "${screenCapturePathBase}${c}.$ImageFormat"
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Get-BusinessCard.ps1
|
Get-BusinessCard.ps1
|
function Get-BusinessCard
{
<#
.Synopsis
Gets a business card
.Description
Gets a business card design on demand.
Select a font and card text, or put in important information and use an automatic layout.
.Example
# Raw Layout
Get-BusinessCard -TextAlignment Center -FontSize 17 -Font "Verdana" -Text @"
Hiro Protagonist
Music.Movies.Microcode.
"@ |
Invoke-Item
.Example
Get-BusinessCard -TextAlignment Center -FontSize 15 -Font "Lucida Console" -Text @"
James Brundage
Start-Automating
"@ |
Invoke-Item
.Notes
|HideParameterOnline AsJob, AsType, InMemory, OutputUI
.Link
Show-Logo
#>
[CmdletBinding(DefaultParameterSetName='CardText')]
param(
# The font to use for the business card
#|Default Kartika
#|Options Get-Font | Sort-Object
[ValidateScript({
$fonts = Get-Font
if ($fonts-contains $_) {
return $true
} else {
throw "$_ is not an installed font. Installed fonts: $fonts"
}
})]
[Parameter(ValueFromPipelineByPropertyName=$true,Position=1)]
[string]$Font = "Kartika",
# The text for the whole card. If you enter in a complete card text, all other fields are ignored.
#|LinesForInput 12
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=0)]
[string]$Text,
# The text alignment for the whole card
[ValidateSet('Left','Center','Right')]
[string]
$TextAlignment = 'Left',
# The text alignment for the whole card
[ValidateSet('Top','Center','Bottom')]
[string]
$VerticalAlignment = 'Center',
# The card font size.
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=2)]
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=2)]
[ValidateRange(8,72)]
[Uint32]$FontSize = 14,
# The the text left position
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=3)]
[Double]$TextLeftPercent = 3,
# The the text top position
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=4)]
[Double]$TextTopPercent = 3,
# The person's name
#|Default John Doe
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=0)]
[string]$Name,
# The person's title
#|Default Administrator of Something
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=2)]
[string]$Title,
# The company name
#|Default SomeCompany, Inc
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=3)]
[string]$Company,
# One or more phone numbers for the card
#|Default 206.555.1212 (m)
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=4)]
[string[]]$PhoneNumber,
# The email address for the business card
#|Default john.doe@thatssomecompany.com
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=5)]
[string]$Email,
# Contacts on social media networks. One per line.
#|Default @somebodyfromsomecompany (twitter)
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=6)]
[string[]]$SocialMedia,
# The URL for a logo
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=7)]
[Uri]$Logo,
# The URL for a background image
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=8)]
[Uri]$BackgroundImage,
# The foreground color
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=8)]
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=3)]
[string]$ForegroundColor,
# The background color
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='AutoLayout',Position=9)]
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName='CardText',Position=4)]
[string]$BackgroundColor,
# The alignment for the name and title
[ValidateSet('Left','Center','Right')]
[string]
$NameAndTitleAlignment = 'Center',
# The alignment for the contact information
[ValidateSet('Left','Center','Right')]
[string]
$ContactInfoAlignment = 'Left',
# The number of dots per inch
#|Default 72
[ValidateRange(72, 300)]
[int]$DotsPerInch = 72,
#If Set, makes a vertical business card
[Switch]
$Vertical,
[ValidateSet('Jpeg','Png','Tiff', 'Gif')]
[string]
$AsType = "Png",
[switch]$InMemory,
[Switch]$OutputUi,
[Switch]$Show
)
process {
if (-not $Vertical) {
$width = 3 * $DotsPerInch
$height = 2 * $DotsPerInch
} else {
$width = 2 * $DotsPerInch
$height = 3 * $DotsPerInch
}
if (-not $backgroundColor) {
$backgroundColor = 'White'
}
if (-not $foregroundColor) {
$foregroundColor = 'Black'
}
$dimensions = @{Width=$Width;Height=$height}
$fontInfo = @{FontFamily=$font;FontSize=$fontSize}
$solidBackground = New-Rectangle -Fill $backgroundColor -Width $width -Height $height
$children = if ($psCmdlet.ParameterSetName -eq 'CardText') {
$solidBackground
$realTop = ($textTopPercent / 100) * $height
$realLeft = ($textLeftPercent / 100) * $width
New-TextBlock -ZIndex 1 -Foreground $foregroundColor -TextAlignment $textAlignment -VerticalAlignment $VerticalAlignment -Background Transparent -FontFamily $font -FontSize $fontSize -Text $text -Top $realTop -Left $realLeft -Width ($width - $realLeft) -Height ($height - $realTop)
if ($backgroundImage) {
$backgroundImage = New-Image -Source $backgroundImage @dimensions
}
} elseif ($psCmdlet.ParameterSetName -eq 'AutoLayout') {
$solidBackground
if ($backgroundImage) {
$backgroundImage = New-Image -Source $backgroundImage @dimensions
}
New-Grid -Columns 2 -Rows 3 @dimensions -Children {
New-TextBlock @fontinfo -TextWrapping Wrap -Text $Name
New-TextBlock @fontinfo -TextWrapping Wrap -Row 1 -Text $Title
New-TextBlock @fontinfo -TextWrapping Wrap -Row 2 -Text $Company
New-TextBlock @fontinfo -TextWrapping Wrap -Column 1 -Text "$PhoneNumber"
New-TextBlock @fontinfo -TextWrapping Wrap -Column 1 -Row 1 -Text "$Email"
New-TextBlock @fontinfo -TextWrapping Wrap -Column 1 -Row 2 -Text "$SocialMedia"
}
}
$cardCanvas =
New-Canvas -Background $backgroundColor @dimensions
$children |
Add-ChildControl -parent $cardCanvas
if ($psBoundParameters.Show) {
New-Window -Content $cardCanvas -SizeToContent WidthAndHeight -Show
} elseif ($psBoundParameters.InMemory) {
$as = @{}
$as."As${AsType}" = $true
$cardCanvas | Save-Screenshot -InMemory @as
} else {
$as = @{}
$as."As${AsType}" = $true
$cardCanvas | Save-Screenshot @as
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Show-Logo.ps1
|
Show-Logo.ps1
|
function Show-Logo
{
<#
.Synopsis
Shows a simple text logo
.Description
Creates a logo out of any text, with a ton of options.
.Example
Show-Logo "A Logo" -FeelingLucky
.Notes
|HideParameterOnline Show, AsJob, AsType, InMemory, OutputUI, NoGuid, Row, Column, RowSpan, ColumnSpan, Name, Width, Height, Top, Left
#>
[OutputType([IO.FileInfo], [byte[]])]
param(
# The text to show in the logo
#|Default: Show-Logo
[Parameter(ValueFromPipelineByPropertyName=$true,Position=0)]
[string]$Text = "Show-Logo",
# The font to use for the logo
#|Default Kartika
#|Options Get-Font | Sort-Object
[ValidateScript({
$fonts = Get-Font
if ($fonts-contains $_) {
return $true
} else {
throw "$_ is not an installed font. Installed fonts: $fonts"
}
})]
[Parameter(ValueFromPipelineByPropertyName=$true,Position=1)]
[string]$Font = "Kartika",
# The font size
#|Default 14
#|MaxLength 120
[Parameter(ValueFromPipelineByPropertyName=$true,Position=2)]
[int]
$Size = 36,
# The number of dots per inch
#|Default 72
[ValidateRange(72, 300)]
[int]$DotsPerInch = 72,
# Changes the font stretching used in the logo.
# Not all fonts support font stretching.
#|Default Normal
[Parameter(ValueFromPipelineByPropertyName=$true,Position=7)]
[ValidateSet('Condensed', 'Expanded','ExtraCondensed',
'ExtraExpanded','Medium','Normal','SemiCondensed',
'SemiExpanded','UltraCondensed','UltraExpanded')]
[string]
$Stretch = "Normal",
# Changes the font stretching used in the logo.
# Not all fonts support font stretching.
#|Default Normal
[Parameter(ValueFromPipelineByPropertyName=$true,Position=6)]
[ValidateSet('Black', 'Bold','DemiBold',
'ExtraBlack','ExtraBold','ExtraLight','Heavy',
'Light','Medium','Normal', 'Regular', 'SemiBold',
'Thin', 'UltraBlack', 'UltraBold', 'UltraLight')]
[string]
$Weight = "Normal",
# If set, attempts to use the italic font style
[Parameter(ValueFromPipelineByPropertyName=$true,Position=11)]
[switch]$Italic,
# If set, uses the oblique font style.
# Oblique slants fonts to the right, like italics, but uses the normal font glyph.
# This results text with stronger edges than most italics.
[Parameter(ValueFromPipelineByPropertyName=$true,Position=12)]
[switch]$Oblique,
# If set, underlines the logo
[Parameter(ValueFromPipelineByPropertyName=$true,Position=13)]
[switch]$Underline,
# Overlines the logo
[Parameter(ValueFromPipelineByPropertyName=$true,Position=14)]
[switch]$Overline,
# Strikethrus the lgoo
[Parameter(ValueFromPipelineByPropertyName=$true,Position=15)]
[switch]$StrikeThru,
# The foreground color
[Parameter(ValueFromPipelineByPropertyName=$true,Position=9)]
[string]$ForegroundColor,
# The background color
[Parameter(ValueFromPipelineByPropertyName=$true,Position=10)]
[string]$BackgroundColor,
# The foreground brush
[Parameter(ValueFromPipelineByPropertyName=$true,Position=21)]
[string]$ForegroundBrush,
# The background brush
[Parameter(ValueFromPipelineByPropertyName=$true,Position=22)]
[string]$BackgroundBrush,
# The rotation of the image
[Parameter(ValueFromPipelineByPropertyName=$true,Position=8)]
[Double]$Rotation,
# The Horizontal Skew Angle
[Parameter(ValueFromPipelineByPropertyName=$true,Position=16)]
[Double]$SkewAngleHorizontal,
# The Skew Angle
[Parameter(ValueFromPipelineByPropertyName=$true,Position=17)]
[Double]$SkewAngleVertical,
# The horizontal center point of the rotation or the skew.
[Parameter(ValueFromPipelineByPropertyName=$true,Position=18)]
[Double]$HorizontalCenter,
# The vertical center point of the rotation or the skew.
[Parameter(ValueFromPipelineByPropertyName=$true,Position=19)]
[Double]$VerticalCenter,
# The margin surrounding the image
[Parameter(ValueFromPipelineByPropertyName=$true,Position=20)]
[int]$Margin,
# If set, will randomly pick a font and size
[Parameter(ValueFromPipelineByPropertyName=$true,Position=4)]
[switch]$FeelingLucky,
# If set, will randomly pick a font, size, weight, and style
[Parameter(ValueFromPipelineByPropertyName=$true,Position=5)]
[switch]$FeelingReallyLucky,
# If set, will randomly pick a font
[Parameter(ValueFromPipelineByPropertyName=$true,Position=3)]
[switch]$RandomFont,
[ValidateSet('Jpeg','Png','Tiff', 'Gif')]
[string]
$AsType = "Png",
[Double]$Top,
[Double]$Left,
[int]$Row,
[int]$Column,
[int]$RowSpan,
[int]$ColumnSpan,
[switch]$Show,
[switch]$AsJob,
[switch]$InMemory,
[Double]$Width,
[Double]$Height,
[string]$Name,
# If set, outputs the UI Element instead of a screenshot.
[switch]$OutputUI,
# If set, omits the guid from the outputted file
[switch]$NoGuid
)
process {
#region Feeling Lucky Comes first
if ($FeelingReallyLucky) {
$psBoundParameters.Stretch =
'Condensed', 'Expanded','ExtraCondensed',
'ExtraExpanded','Medium','Normal','SemiCondensed',
'SemiExpanded','UltraCondensed','UltraExpanded' |
Get-Random
$psBoundParameters.Weight =
'Condensed', 'Expanded','ExtraCondensed',
'ExtraExpanded','Medium','Normal','SemiCondensed',
'SemiExpanded','UltraCondensed','UltraExpanded' |
Get-Random
$Font = Get-Font | Get-Random
$Size = 12..48 | Get-Random
} elseif ($feelingLucky) {
$Font = Get-Font | Get-Random
$Size = 12..48 | Get-Random
} elseif ($RandomFont) {
$Font = Get-Font | Get-Random
}
#endregion
#region Copy Core UI Parameters
$coreUIParameters = @{}
foreach ($parameter in 'Top', 'Left', 'Width', 'Height', 'RowSpan',
'ColumnSpan', 'Row','Column', 'Name', 'Show', 'AsJob') {
if ($psBoundParameters.$parameter) {
$coreUIParameters.$parameter = $psBoundParameters.$parameter
}
}
#endregion
$textBlockParameters = @{
Text = $text
FontFamily = $font
FontSize = $size
}
if ($psBoundParameters.Stretch) {
$textBlockParameters.FontStretch = $Stretch
}
if ($psBoundParameters.Weight) {
$textBlockParameters.FontStretch = $Weight
}
if ($Italic) {
$textBlockParameters.FontStyle = "Italic"
} elseif ($Oblique) {
$textBlockParameters.FontStyle = "Oblique"
}
if ($OverLine) {
$textBlockParameters.TextDecoration = [Windows.TextDecorations]::OverLine
} elseif ($Underline) {
$textBlockParameters.TextDecoration = [Windows.TextDecorations]::Underline
} elseif ($strikeout) {
$textBlockParameters.TextDecoration = [Windows.TextDecorations]::Strikethrough
}
if ($psBoundParameters.foregroundBrush) {
$textBlockParameters.Foreground = try {
[Windows.Markup.XamlReader]::Parse($psBoundParameters.foregroundBrush)
} catch {
}
} elseif ($psBoundParameters.foregroundColor) {
$textBlockParameters.Foreground= $psBoundParameters.foregroundColor
}
if ($psBoundParameters.backgroundBrush) {
$textBlockParameters.background = try {
[Windows.Markup.XamlReader]::Parse($psBoundParameters.backgroundBrush)
} catch {
}
} elseif ($psBoundParameters.backgroundColor) {
$textBlockParameters.background= $psBoundParameters.backgroundColor
}
if ($Rotation) {
$textBlockParameters.LayoutTransform = New-RotateTransform -Angle $rotation -CenterX $HorizontalCenter -CenterY $VerticalCenter
} elseif ($SkewAngleHorizontal -or $SkewAngleVertical) {
$textBlockParameters.LayoutTransform = New-SkewTransform -AngleX $SkewAngleHorizontal -AngleY $SkewAngleVertical -CenterX $HorizontalCenter -CenterY $VerticalCenter
}
if ($outputUI) {
[Windows.Markup.XamlReader]::Parse((New-TextBlock @textblockParameters -OutputXaml))
} else {
$screenShotParameters = @{}
$screenShotParameters."As${asType}" = $true
$safeText = $text -ireplace "[\/\?<>\\\:\*\|`"]", "_"
$guidText = if ($noGuid) {"" } else {
".$([GUID]::NewGuid().ToString().Replace('-',''))"
}
$screenShotParameters.OutputPath = "${safeText}${guidText}.${asType}"
$screenShotParameters.DotsPerInch = $dotsPerInch
$screenShotParameters.InMemory = $InMemory
[Windows.Markup.XamlReader]::Parse((New-TextBlock @textblockParameters -OutputXaml)) |
Save-Screenshot @screenShotParameters
}
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/RoughDraft.ezformat.ps1
|
RoughDraft.ezformat.ps1
|
$moduleRoot = "$home\documents\windowspowershell\modules\RoughDraft"
Write-FormatView -TypeName System.Windows.Media.FontFamily -Action {
if ($request -and $response) {
$fileFound = Get-ChildItem -Path "$($_.Source).png" -ErrorAction SilentlyContinue
if ($fileFound) {
"<h3>$($_.SOurce)</h3><img src='data:image/png;base64,$([Convert]::ToBase64String([io.FILE]::ReadAllBytes($fileFound.FullName)))' />"
} else {
$_.Source
}
} else {
$_.Source
}
} | Out-FormatData |
Set-Content "$moduleRoot\RoughDraft.Format.ps1xml"
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Switch-Color.ps1
|
Switch-Color.ps1
|
function Switch-Color
{
<#
.Synopsis
Switches a color up
.Description
Switches a color up by changing ratios of a given part or inverting the color
.Example
#>
[CmdletBinding(DefaultParameterSetName='Shift')]
param(
# A color
#|Color
[ValidateScript({
$_ -like "??????"
})]
[Parameter(Mandatory=$true,Position=0)]
[string]
$Color,
# If set, will invert the color
[Parameter(Mandatory=$true,ParameterSetName='Invert')]
[Switch]
$Invert,
# If set, will skip processing red
[switch]$SkipRed,
# If set, will skip processing blue
[switch]$skipBlue,
# If set, will skip processing green
[switch]$skipGreen,
# The ratio of change to apply to the color
#|Default 1
[Double]$Ratio = 1
)
process {
$redPart = [int]::Parse($color[1..2]-join'',
[Globalization.NumberStyles]::HexNumber)
$greenPart = [int]::Parse($color[3..4]-join '',
[Globalization.NumberStyles]::HexNumber)
$bluePart = [int]::Parse($color[5..6] -join'',
[Globalization.NumberStyles]::HexNumber)
$newr = $redPart
$newB = $bluePart
$newg = $greenPart
if ($psCmdlet.PArameterSetName -eq 'Invert') {
if (-not $skipRed) {
$newr = (255 - $redPart) * $ratio
}
if (-not $skipGreen) {
$newg = (255 - $greenPart) * $ratio
}
if (-not $skipBLue) {
$newb = (255 - $bluePart) * $ratio
}
} elseif ($psCmdlet.PArameterSetName -eq 'Shift') {
$newr = $redPart * $ratio
$newb = $bluePart * $ratio
$newg = $greenPart * $ratio
}
if ($newr -gt 255) {
$newr = 255
}
if ($newg -gt 255) {
$newg = 255
}
if ($newb -gt 255) {
$newb = 255
}
"#" + ("{0:x}" -f ([int]$newr)).PadLeft(2, "0") + ("{0:x}" -f ([int]$newg)).PadLeft(2, "0") + ("{0:x}" -f ([int]$newb)).PadLeft(2, "0")
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/ConvertTo-Icon.ps1
|
ConvertTo-Icon.ps1
|
function ConvertTo-Icon
{
<#
.Synopsis
Converts image to icons
.Description
Converts an image to an icon
.Example
ConvertTo-Icon -File .\Logo.png -OutputFile .\Favicon.ico
#>
[CmdletBinding()]
param(
# The file
[Parameter(Mandatory=$true, Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias('Fullname')]
[string]$File,
# If set, will output bytes instead of creating a file
[switch]$InMemory,
# If provided, will output the icon to a location
[Parameter(Position=1, ValueFromPipelineByPropertyName=$true)]
[string]$OutputFile
)
begin {
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
}
process {
#region Load Icon
$resolvedFile = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($file)
if (-not $resolvedFile) { return }
$loadedImage = [Drawing.Image]::FromFile($resolvedFile)
$intPtr = New-Object IntPtr
$thumbnail = $loadedImage.GetThumbnailImage(72, 72, $null, $intPtr)
$bitmap = New-Object Drawing.Bitmap $thumbnail
$bitmap.SetResolution(72, 72);
$icon = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon());
#endregion Load Icon
#region Save Icon
if ($InMemory) {
$memStream = New-Object IO.MemoryStream
$icon.Save($memStream)
$memStream.Seek(0,0)
$bytes = New-Object Byte[] $memStream.Length
$memStream.Read($bytes, 0, $memStream.Length)
$bytes
} elseif ($OutputFile) {
$resolvedOutputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile)
$fileStream = [IO.File]::Create("$resolvedOutputFile")
$icon.Save($fileStream)
$fileStream.Close()
}
#endregion Save Icon
#region Cleanup
$icon.Dispose()
$bitmap.Dispose()
#endregion Cleanup
}
}
|
PowerShellCorpus/PowerShellGallery/RoughDraft/0.1/Get-Thumbnail.ps1
|
Get-Thumbnail.ps1
|
function Get-Thumbnail
{
<#
.Synopsis
Gets file thumbnails
.Description
Gets thumbnail images for a file
.Example
Get-ThumbNail .\a.jpg -SaveThumbnail
#>
param(
# The path to the file
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[Alias('Fullname')]
[string]$FilePath,
# The width of the thumbnail
[Uint32]$Width = 250,
# The height of the thumbnail
[Uint32]$Height = 250,
# If set, the thumbnail will be saved to the same location, with the name file.thumbnail.jpg. If not set, the bytes in the file will be returned.
[Switch]$SaveThumbnail
)
begin {
if (-not ('StartAutomating2.ShellThumbnail' -as [type])) {
Add-Type -ignorewarnings -ReferencedAssemblies ([System.Drawing.Bitmap].Assembly) -TypeDefinition @'
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace StartAutomating2
{
public class ShellThumbnail : IDisposable
{
[Flags]
private enum ESTRRET
{
STRRET_WSTR = 0,
STRRET_OFFSET = 1,
STRRET_CSTR = 2
}
[Flags]
private enum ESHCONTF
{
SHCONTF_FOLDERS = 32,
SHCONTF_NONFOLDERS = 64,
SHCONTF_INCLUDEHIDDEN = 128,
}
[Flags]
private enum ESHGDN
{
SHGDN_NORMAL = 0,
SHGDN_INFOLDER = 1,
SHGDN_FORADDRESSBAR = 16384,
SHGDN_FORPARSING = 32768
}
[Flags]
private enum ESFGAO
{
SFGAO_CANCOPY = 1,
SFGAO_CANMOVE = 2,
SFGAO_CANLINK = 4,
SFGAO_CANRENAME = 16,
SFGAO_CANDELETE = 32,
SFGAO_HASPROPSHEET = 64,
SFGAO_DROPTARGET = 256,
SFGAO_CAPABILITYMASK = 375,
SFGAO_LINK = 65536,
SFGAO_SHARE = 131072,
SFGAO_READONLY = 262144,
SFGAO_GHOSTED = 524288,
SFGAO_DISPLAYATTRMASK = 983040,
SFGAO_FILESYSANCESTOR = 268435456,
SFGAO_FOLDER = 536870912,
SFGAO_FILESYSTEM = 1073741824,
SFGAO_HASSUBFOLDER = -2147483648,
SFGAO_CONTENTSMASK = -2147483648,
SFGAO_VALIDATE = 16777216,
SFGAO_REMOVABLE = 33554432,
SFGAO_COMPRESSED = 67108864,
}
private enum EIEIFLAG
{
IEIFLAG_ASYNC = 1,
IEIFLAG_CACHE = 2,
IEIFLAG_ASPECT = 4,
IEIFLAG_OFFLINE = 8,
IEIFLAG_GLEAM = 16,
IEIFLAG_SCREEN = 32,
IEIFLAG_ORIGSIZE = 64,
IEIFLAG_NOSTAMP = 128,
IEIFLAG_NOBORDER = 256,
IEIFLAG_QUALITY = 512
}
[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 0, CharSet = CharSet.Auto)]
private struct STRRET_CSTR
{
public ESTRRET uType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 520)]
public byte[] cStr;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
private struct STRRET_ANY
{
[FieldOffset(0)]
public ESTRRET uType;
[FieldOffset(4)]
public IntPtr pOLEString;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct SIZE
{
public int cx;
public int cy;
}
[ComImport(), Guid("00000000-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IUnknown
{
[PreserveSig()]
IntPtr QueryInterface(ref Guid riid, ref IntPtr pVoid);
[PreserveSig()]
IntPtr AddRef();
[PreserveSig()]
IntPtr Release();
}
[ComImportAttribute()]
[GuidAttribute("00000002-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMalloc
{
[PreserveSig()]
IntPtr Alloc(int cb);
[PreserveSig()]
IntPtr Realloc(IntPtr pv, int cb);
[PreserveSig()]
void Free(IntPtr pv);
[PreserveSig()]
int GetSize(IntPtr pv);
[PreserveSig()]
int DidAlloc(IntPtr pv);
[PreserveSig()]
void HeapMinimize();
}
[ComImportAttribute()]
[GuidAttribute("000214F2-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IEnumIDList
{
[PreserveSig()]
int Next(int celt, ref IntPtr rgelt, ref int pceltFetched);
void Skip(int celt);
void Reset();
void Clone(ref IEnumIDList ppenum);
}
[ComImportAttribute()]
[GuidAttribute("000214E6-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellFolder
{
void ParseDisplayName(IntPtr hwndOwner, IntPtr pbcReserved,
[MarshalAs(UnmanagedType.LPWStr)]string lpszDisplayName,
ref int pchEaten, ref IntPtr ppidl, ref int pdwAttributes);
void EnumObjects(IntPtr hwndOwner,
[MarshalAs(UnmanagedType.U4)]ESHCONTF grfFlags,
ref IEnumIDList ppenumIDList);
void BindToObject(IntPtr pidl, IntPtr pbcReserved, ref Guid riid,
ref IShellFolder ppvOut);
void BindToStorage(IntPtr pidl, IntPtr pbcReserved, ref Guid riid, IntPtr ppvObj);
[PreserveSig()]
int CompareIDs(IntPtr lParam, IntPtr pidl1, IntPtr pidl2);
void CreateViewObject(IntPtr hwndOwner, ref Guid riid,
IntPtr ppvOut);
void GetAttributesOf(int cidl, IntPtr apidl,
[MarshalAs(UnmanagedType.U4)]ref ESFGAO rgfInOut);
void GetUIObjectOf(IntPtr hwndOwner, int cidl, ref IntPtr apidl, ref Guid riid, ref int prgfInOut, ref IUnknown ppvOut);
void GetDisplayNameOf(IntPtr pidl,
[MarshalAs(UnmanagedType.U4)]ESHGDN uFlags,
ref STRRET_CSTR lpName);
void SetNameOf(IntPtr hwndOwner, IntPtr pidl,
[MarshalAs(UnmanagedType.LPWStr)]string lpszName,
[MarshalAs(UnmanagedType.U4)] ESHCONTF uFlags,
ref IntPtr ppidlOut);
}
[ComImportAttribute(), GuidAttribute("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IExtractImage
{
void GetLocation([Out(), MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszPathBuffer, int cch, ref int pdwPriority, ref SIZE prgSize, int dwRecClrDepth, ref int pdwFlags);
void Extract(ref IntPtr phBmpThumbnail);
}
private class UnmanagedMethods
{
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetMalloc(ref IMalloc ppMalloc);
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetDesktopFolder(ref IShellFolder ppshf);
[DllImport("shell32", CharSet = CharSet.Auto)]
internal extern static int SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);
[DllImport("gdi32", CharSet = CharSet.Auto)]
internal extern static int DeleteObject(IntPtr hObject);
}
~ShellThumbnail()
{
Dispose();
}
private IMalloc alloc = null;
private bool disposed = false;
private Size _desiredSize = new Size(100, 100);
private Bitmap _thumbNail;
public Bitmap ThumbNail
{
get
{
return _thumbNail;
}
}
public Size DesiredSize
{
get { return _desiredSize; }
set { _desiredSize = value; }
}
private IMalloc Allocator
{
get
{
if (!disposed)
{
if (alloc == null)
{
UnmanagedMethods.SHGetMalloc(ref alloc);
}
}
else
{
Debug.Assert(false, "Object has been disposed.");
}
return alloc;
}
}
public Bitmap GetThumbnail(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return null;
if (!File.Exists(fileName) && !Directory.Exists(fileName))
{
throw new FileNotFoundException(string.Format("The file '{0}' does not exist", fileName), fileName);
}
if (_thumbNail != null)
{
_thumbNail.Dispose();
_thumbNail = null;
}
IShellFolder folder = null;
try
{
folder = getDesktopFolder;
}
catch (Exception ex)
{
throw ex;
}
if (folder != null)
{
IntPtr pidlMain = IntPtr.Zero;
try
{
int cParsed = 0;
int pdwAttrib = 0;
string filePath = Path.GetDirectoryName(fileName);
folder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, filePath, ref cParsed, ref pidlMain, ref pdwAttrib);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
throw ex;
}
if (pidlMain != IntPtr.Zero)
{
Guid iidShellFolder = new Guid("000214E6-0000-0000-C000-000000000046");
IShellFolder item = null;
try
{
folder.BindToObject(pidlMain, IntPtr.Zero, ref iidShellFolder, ref item);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
Allocator.Free(pidlMain);
throw ex;
}
if (item != null)
{
IEnumIDList idEnum = null;
try
{
item.EnumObjects(IntPtr.Zero, (ESHCONTF.SHCONTF_FOLDERS | ESHCONTF.SHCONTF_NONFOLDERS), ref idEnum);
}
catch (Exception ex)
{
Marshal.ReleaseComObject(folder);
Allocator.Free(pidlMain);
throw ex;
}
if (idEnum != null)
{
int hRes = 0;
IntPtr pidl = IntPtr.Zero;
int fetched = 0;
bool complete = false;
while (!complete)
{
hRes = idEnum.Next(1, ref pidl, ref fetched);
if (hRes != 0)
{
pidl = IntPtr.Zero;
complete = true;
}
else
{
if (_getThumbNail(fileName, pidl, item))
{
complete = true;
}
}
if (pidl != IntPtr.Zero)
{
Allocator.Free(pidl);
}
}
Marshal.ReleaseComObject(idEnum);
}
Marshal.ReleaseComObject(item);
}
Allocator.Free(pidlMain);
}
Marshal.ReleaseComObject(folder);
}
return ThumbNail;
}
private bool _getThumbNail(string file, IntPtr pidl, IShellFolder item)
{
IntPtr hBmp = IntPtr.Zero;
IExtractImage extractImage = null;
try
{
string pidlPath = PathFromPidl(pidl);
if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper()))
{
IUnknown iunk = null;
int prgf = 0;
Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1");
item.GetUIObjectOf(IntPtr.Zero, 1, ref pidl, ref iidExtractImage, ref prgf, ref iunk);
extractImage = (IExtractImage)iunk;
if (extractImage != null)
{
SIZE sz = new SIZE();
sz.cx = DesiredSize.Width;
sz.cy = DesiredSize.Height;
StringBuilder location = new StringBuilder(260, 260);
int priority = 0;
int requestedColourDepth = 32;
EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN;
int uFlags = (int)flags;
try
{
extractImage.GetLocation(location, location.Capacity, ref priority, ref sz, requestedColourDepth, ref uFlags);
extractImage.Extract(ref hBmp);
}
catch (System.Runtime.InteropServices.COMException ex)
{
}
if (hBmp != IntPtr.Zero)
{
_thumbNail = Bitmap.FromHbitmap(hBmp);
}
Marshal.ReleaseComObject(extractImage);
extractImage = null;
}
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
if (hBmp != IntPtr.Zero)
{
UnmanagedMethods.DeleteObject(hBmp);
}
if (extractImage != null)
{
Marshal.ReleaseComObject(extractImage);
}
throw ex;
}
}
private string PathFromPidl(IntPtr pidl)
{
StringBuilder path = new StringBuilder(260, 260);
int result = UnmanagedMethods.SHGetPathFromIDList(pidl, path);
if (result == 0)
{
return string.Empty;
}
else
{
return path.ToString();
}
}
private IShellFolder getDesktopFolder
{
get
{
IShellFolder ppshf = null;
int r = UnmanagedMethods.SHGetDesktopFolder(ref ppshf);
return ppshf;
}
}
public void Dispose()
{
if (!disposed)
{
if (alloc != null)
{
Marshal.ReleaseComObject(alloc);
}
alloc = null;
if (_thumbNail != null)
{
_thumbNail.Dispose();
}
disposed = true;
}
}
}
}
'@
}
$shellThumb = New-Object StartAutomating2.ShellThumbnail
Add-Type -AssemblyName System.Windows.Forms
}
process {
$resolvedFile = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($FilePath)
if (-not $resolvedFile) { return }
$shellThumb.DesiredSize = New-Object Drawing.Size $Width, $Height
$bitmap = $shellThumb.GetThumbnail("$resolvedFile")
$Codec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object { $_.FormatDescription -eq 'JPEG' }
$ep = New-Object Drawing.Imaging.EncoderParameters
$ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
if ($SaveThumbnail) {
$fileItem = Get-Item -literalPath $resolvedFile
$thumbFile = $fileItem.FullName + ".thumbnail.jpg"
$bitmap.Save($thumbFile, $codec, $ep)
} else {
$memStream = New-Object IO.MemoryStream
$bitmap.Save($memStream, $Codec, $ep)
$null = $memStream.Seek(0,0)
$bytes = New-Object Byte[] $memStream.Length
$null = $memStream.Read($bytes, 0, $memStream.Length)
$memStream.Close()
$memStream.Dispose()
$bytes
}
}
}
|
PowerShellCorpus/PowerShellGallery/Remoting/0.2.2.90/imports.ps1
|
imports.ps1
|
# grab functions from files
get-childitem $psscriptroot\functions\ -filter "*.ps1" |
? { -not ($_.name.Contains(".Tests.")) } |
? { -not (($_.name).StartsWith("_")) } |
% { . $_.fullname }
|
PowerShellCorpus/PowerShellGallery/Remoting/0.2.2.90/functions/Get-RemoteCert.ps1
|
Get-RemoteCert.ps1
|
function Get-RemoteCert {
[cmdletbinding()]
param
(
[parameter(Mandatory=$true)][string]$computername,
[parameter(Mandatory=$false)]$port = 443,
$outfile,
[switch][bool]$accept,
$certstorelocation
)
if ($port -in "powershell","rps","winrm") {
$port = 5986
}
write-host "connecting to $computername on port $port"
$tcpsocket = $null
try {
#Create a TCP Socket to the computer and a port number
$tcpsocket = New-Object Net.Sockets.TcpClient($computerName, $port)
} catch {
write-error $_
}
#test if the socket got connected
if(!$tcpsocket)
{
throw "Error Opening Connection: $port on $computername Unreachable"
}
else
{
#Socket Got connected get the tcp stream ready to read the certificate
write-host "Successfully Connected to $computername on $port" -ForegroundColor Green -BackgroundColor Black
$tcpstream = $tcpsocket.GetStream()
Write-host "Reading SSL Certificate...." -ForegroundColor Yellow -BackgroundColor Black
#Create an SSL Connection
$sslStream = New-Object System.Net.Security.SslStream($tcpstream,$false, {
param($sender, $certificate, $chain, $sslPolicyErrors)
return $true
})
#Force the SSL Connection to send us the certificate
$sslStream.AuthenticateAsClient($computerName)
#Read the certificate
$certinfo = New-Object system.security.cryptography.x509certificates.x509certificate2($sslStream.RemoteCertificate)
if ($accept -and $outfile -eq $null) {
$outfile = "$computername.crt"
}
if ($outfile -ne $null) {
$certinfo | Export-Certificate -FilePath $outfile -Verbose
}
if ($accept) {
if ($certstorelocation -eq $null) {
$certstorelocation = "Cert:\CurrentUser\Trust"
}
Import-Certificate $outfile -CertStoreLocation $certstorelocation
}
return $certinfo
}
}
|
PowerShellCorpus/PowerShellGallery/Remoting/0.2.2.90/functions/Find-SessionMap.ps1
|
Find-SessionMap.ps1
|
function Find-SessionMap {
[CmdletBinding()]
param ([switch][bool] $reload = $true)
if ($Global:psSessionsMap -eq $null -or $reload) {
write-verbose "looking for sessionmap.ps1"
$searchPAths = "$home\Documents\WindowsPowerShell\sessionmap.config.ps1","$home\Documents\sessionmap.config.ps1","$home\sessionmap.config.ps1","$(_get-syncdir)\sessionmap.config.ps1","$(_get-syncdir)\Documents\sessionmap.config.ps1"
foreach($p in $searchpaths) {
if (test-path $p) {
write-verbose "found sessionmap at $p"
$map = . $p
if ($map -ne $null) {
$Global:psSessionsMap = $map
$Global:psSessionsMapPath = $p
break
}
}
}
} else {
write-verbose "global session map exists. NOT looking for sessionmap.ps1"
}
return $Global:psSessionsMap
}
function find-rdp {
param($name)
$searchPAths = "$home\Documents\WindowsPowerShell\rdp","$home\Documents\rdp","$home\rdp","$(_get-syncdir)\rdp","$(_get-syncdir)\Documents\rdp"
foreach($p in $searchpaths) {
$p = join-path $p "$name.rdp"
if (test-path $p) {
write-verbose "found rdp file at $p"
return $p
}
}
}
|
PowerShellCorpus/PowerShellGallery/Remoting/0.2.2.90/functions/New-RemoteSession.ps1
|
New-RemoteSession.ps1
|
function New-RemoteSession {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)] $ComputerName,
[switch][bool] $NoSsl,
[switch][bool] $Ssl,
[switch][bool] $Reuse = $true,
$ServerInfo = $null,
[switch][bool] $ClearCredentials,
$port,
[switch][bool] $cim,
[parameter(Mandatory=$false)]
[pscredential]
#[System.Management.Automation.Credential()]
$credential = [pscredential]::Empty,
[System.Management.Automation.Runspaces.AuthenticationMechanism] $Authentication = [System.Management.Automation.Runspaces.AuthenticationMechanism]::negotiate,
[switch][bool] $reloadSessionMap = $false
)
$map = find-sessionmap -reload:$reloadSessionMap
$bound = $PSBoundParameters
if ($bound.reloadSessionMap -ne $null) { $null = $bound.Remove("reloadSessionMap") }
if ($bound.ErrorAction -ne $null) { $null = $bound.Remove("ErrorAction") }
try {
$Error.Clear()
write-verbose "===> connecting with Negotiate auth method"
$s = $null
$s = _new-remotesession @bound -ErrorAction:SilentlyContinue
}
catch {
# this was the first try, ignore erorrs
write-verbose $_
}
if ($s -ne $null) {
write-verbose "I have some session:"
$s | format-table | out-string | write-verbose
}
else {
if ($Error.Count -eq 0) {
}
}
if ($Error.Count -gt 0 -or $s -eq $null) {
write-verbose "===> fallback: connecting with manual credentials"
#$bound["Authentication"] = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Basic
try {
$s = _new-remotesession @bound -ErrorAction:Continue
} catch {
if ($_.Exception.Message.Contains(" Basic,")) {
write-warning "have you enabled basic authentication method, like this:"
write-warning 'set-item WSMan:\localhost\Client\Auth\Basic -Value true -Confirm:$false'
}
throw
}
}
return $s
}
function _New-RemoteSession {
param(
[parameter(Mandatory=$true)] $ComputerName,
[switch][bool] $NoSsl,
[switch][bool] $Ssl,
[switch][bool] $Reuse = $true,
$ServerInfo = $null,
[switch][bool] $ClearCredentials,
[System.Management.Automation.Runspaces.AuthenticationMechanism] $Authentication = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Negotiate,
$port,
[switch][bool] $cim,
[Parameter(Mandatory=$false)]
[pscredential]
$credential = [pscredential]::Empty
)
# ssl is the default
$use_ssl_by_default = $true
if ($Ssl.IsPresent) {
$NoSsl = !$Ssl
}
elseif (!$NoSsl.IsPresent) {
$NoSsl = !$use_ssl_by_default
if ($port -eq 5985) { $NoSsl = $true }
if ($port -eq 5986) { $NoSsl = $false }
}
$sessionVar = $ComputerName
if ($cim) { $sessionVar = "$($ComputerName)_cim" }
if ($ClearCredentials) { $Reuse = $false }
if ($Reuse -and (Test-Path variable:global:$sessionVar)) {
$currentSession = (Get-Variable -Name "$sessionVar").Value
if ($currentSession -ne $null -and ($cim -or ($currentSession.State -eq "Opened" -and $currentSession.Availability -eq "Available"))) {
write-verbose "retrieving exisitng session for '$computername'"
return $currentSession
}
}
$hash = @{
"-UseSSL" = !$NoSsl
"-ComputerName" = $ComputerName
}
$found = $false
if ($global:psSessionsMap -ne $null) {
$null = ipmo publishmap -Verbose:$false
$ServerInfo = get-entry $ComputerName -map $global:psSessionsMap
$found = $ServerInfo -ne $null
}
if ($found) {
write-verbose "found '$ComputerName' in session map at '$Global:psSessionsMapPath'"
} elseif ($ServerInfo -ne $null) {
if ($global:psSessionsMap -eq $null) {
$global:psSessionsMap = @{}
}
$global:psSessionsMap[$ComputerName] = $ServerInfo
}
else {
write-verbose "'$ComputerName' not found in session map"
}
if ($ServerInfo -ne $null) {
$ServerInfo.Keys | % {
if ($hash.ContainsKey("-$_")) {
$hash["-$_"] = $ServerInfo[$_]
} elseif (!$_.StartsWith("_") -and $_ -ne "vars") {
$hash["-$_"] = $ServerInfo[$_]
}
}
if ($ServerInfo.UseSSL -ne $null) { $NoSsl = !$ServerInfo.UseSSL }
if ($ServerInfo.Port -ne $null) { $port = $ServerInfo.Port }
if ($port -eq $null) {
if ($nossl) {
$port = 5985
} else {
$port = 5986
}
}
} else {
if ($port -eq $null) {
$hasSsl = test-port $ComputerName 5986
if($hasSsl -and !$NoSsl) {
$hash["-UseSSL"] = $true
$port = 5986
} else {
$hasPlain = test-port $ComputerName 5985
if ($hasPlain) {
$hash["-UseSSL"] = $false
$port = 5985
} else {
throw "no entry in sessionmap for '$computername'. some Default ports are not available (5986[ssl]=$hasSsl and 5985[nossl]=$NoSsl)"
}
}
} else {
$hash["-UseSSL"] = !$NoSsl
}
}
if ($ClearCredentials) {
Cache\Remove-CredentialsCached -container "$ComputerName.cred"
}
$bound = $PSBoundParameters
$useCredentials = $ServerInfo -ne $null `
-or ($Authentication -eq [System.Management.Automation.Runspaces.AuthenticationMechanism]::Basic) `
-or $ComputerName.endswith("cloudapp.net") `
-or ($credential -ne [pscredential]::Empty) `
-or ($bound.credential -eq $null)
#$useCredentials = $credential -ne [pscredential]::Empty
if ($useCredentials) {
write-verbose "will use credentials"
<#
if ($username -ne $null -and $password -ne $null) {
$secpass = ConvertTo-SecureString $password -AsPlainText -force
$cred = new-object System.Management.Automation.pscredential -ArgumentList @($username,$secpass)
$hash["-Credential"] = $cred
}
#>
if ($bound.credential -eq $null) {
write-verbose "trying cached credentials"
# auto credentials
$cred = Cache\Get-CredentialsCached -Message "Enter credentials for $ComputerName" -container "$ComputerName.cred" -verbose
if ($cred -eq $null) {
throw "credentials are required for remote connection to '$ComputerName', but there are no cached credentials in container '$ComputerName.cred'!"
}
}
else {
# use provided credentials
write-verbose "using provided credentials"
$cred = $credential
}
if ($cred -eq $null) {
throw "credentials are required for remote connection to '$ComputerName', but none given!"
}
write-verbose "passing credentials for user $($cred.username)"
$hash["-Credential"] = $cred
} else {
write-verbose "not using credentials"
}
if ($port -ne $null) {
$hash["-Port"] = $port
}
if ($PSBoundParameters["Authentication"] -ne $null) {
$hash["-Auth"] = $Authentication
}
$Error.Clear()
write-verbose "connecting with parameters:"
$hash | format-table -AutoSize | out-string -Stream | write-verbose
$session = $null
if ($cim) {
if ($hash.ContainsKey("-UseSSL")) {
$hash.Remove("-UseSSL")
}
$opts = New-CimSessionOption -SkipRevocationCheck -SkipCACheck -SkipCNCheck -UseSsl:$(!$nossl)
$session = New-CimSession @hash -SessionOption $opts
if ($session -eq $null) { throw "failed to create remote CIM sesssion" }
} else {
$opts = New-PSSessionOption -SkipRevocationCheck -SkipCACheck -SkipCNCheck
$session = New-PSSession @hash -ErrorAction:$ErrorActionPreference -SessionOption $opts
if ($session -eq $null) { throw "failed to create remote powershell sesssion" }
if ($Error.Count -ne 0) {
if ($Error[0] -match "SSL certificate is signed by an unknown certificate authority" -or $Error[0].Exception.ErrorCode -eq 12175) {
write-host "getting remote cert"
$p = $port
if ($p -eq $null) { $p = "rps" }
$crt = Get-RemoteCert -computername $ComputerName -port $p
write-host "found certificate for $($crt.Subject) issuer=$($crt.issuer). Installing to Cert:\CurrentUser\Root"
$crt | Export-Certificate -FilePath "$ComputerName.cer"
Import-Certificate -FilePath "$ComputerName.cer" -CertStoreLocation Cert:\CurrentUser\Root -Confirm:$false
$Error.Clear()
$session = New-PSSession @hash -SessionOption $opts
}
if ($Error.Count -ne 0) {
$err = @()
$error | % { $err += $_ }
throw $error[0]
}
}
}
Write-Verbose "storing session to '$ComputerName' in 'global:$sessionVar'"
Set-Variable -Name "global:$sessionVar" -Value $session
if ($session -eq $null) { throw "Cannot enter remote session, because it has not been initialized" }
if ($ServerInfo -ne $null -and ![string]::IsNullOrEmpty($ServerInfo._defaultdir) -and !$cim) {
$r = icm -Session $session -ScriptBlock { param($dir) cd $dir } -ArgumentList @($ServerInfo._defaultdir)
}
return $session
}
function Test-Port
{
[cmdletbinding()]
Param(
[parameter(ParameterSetName='ComputerName', Position=0)]
[string]
$ComputerName,
[parameter(ParameterSetName='IP', Position=0)]
[System.Net.IPAddress]
$IPAddress,
[parameter(Mandatory=$true , Position=1)]
[int]
$Port,
[parameter(Mandatory=$false, Position=2)]
[ValidateSet("TCP", "UDP")]
[string]
$Protocol = "TCP",
$timeout = 1000
)
$RemoteServer = If ([string]::IsNullOrEmpty($ComputerName)) {$IPAddress} Else {$ComputerName};
If ($Protocol -eq 'TCP')
{
$test = New-Object System.Net.Sockets.TcpClient;
Try
{
Write-verbose "Connecting to $RemoteServer :$Port (TCP)..";
$r = $test.BeginConnect($RemoteServer, $Port, $null, $null);
$s = $r.AsyncWaitHandle.WaitOne([timespan]::FromMilliseconds($timeout));
if (!$s) {
throw "connection timed out after $timeout"
}
Write-verbose "Connection successful";
return $true
}
Catch
{
Write-verbose "Connection failed: $_";
return $false
}
Finally
{
$test.Dispose();
}
}
If ($Protocol -eq 'UDP')
{
Write-warning "UDP port test functionality currently not available."
<#
$test = New-Object System.Net.Sockets.UdpClient;
Try
{
Write-Host "Connecting to "$RemoteServer":"$Port" (UDP)..";
$test.Connect($RemoteServer, $Port);
Write-Host "Connection successful";
}
Catch
{
Write-Host "Connection failed";
}
Finally
{
$test.Dispose();
}
#>
}
}
function Enter-RemoteSession {
param(
[parameter(Mandatory=$true)] $ComputerName,
[switch][bool] $NoSsl,
[switch][bool] $Ssl,
[switch][bool] $ClearCredentials,
$port,
[switch][bool] $Reuse = $true,
[switch][bool] $reloadSessionMap = $true,
[switch][bool] $NoEnter = $false,
[switch][bool] $cim,
[pscredential]
[System.Management.Automation.Credential()]
$credential = [PSCredential]::Empty
)
$bound = $PSBoundParameters
$null = $bound.Remove("NoEnter")
$s = new-remotesession @bound
if ($s -eq $null) {
throw "failed to connect to '$computername'"
}
if (!$NoEnter -and !$cim) {
$s | Enter-PSSession
} else {
return $s
}
}
set-alias rps Enter-RemoteSession
function _get-syncdir() {
if (test-path "HKCU:\Software\Microsoft\OneDrive")
{
$prop = get-itemproperty "HKCU:\Software\Microsoft\OneDrive\" "UserFolder"
if ($prop -ne $null) {
$dir = $prop.userfolder
}
}
return $dir
}
function enter-rdp ($name) {
$file = find-rdp $name
if ($file -eq $null -and $name.contains(".")) {
write-host "running mstsc /v:$name"
mstsc /v:$name
return
}
if ($file -eq $null) { throw "rdp profile '$name' not found" }
write-host "running mstsc '$file'..."
mstsc $file
}
new-alias rdp enter-rdp -force
|
PowerShellCorpus/PowerShellGallery/OfficeOnlineServerDsc/1.0.0.0/Examples/FullExamples/NewFarm.ps1
|
NewFarm.ps1
|
<#
.EXAMPLE
This example shows how to install the prerequisites, binaries and set up a new
farm on the local server.
#>
Configuration Example
{
param()
Import-DscResource -ModuleName OfficeOnlineServerDsc
$requiredFeatures = @(
"Web-Server",
"Web-Mgmt-Tools",
"Web-Mgmt-Console",
"Web-WebServer",
"Web-Common-Http",
"Web-Default-Doc",
"Web-Static-Content",
"Web-Performance",
"Web-Stat-Compression",
"Web-Dyn-Compression",
"Web-Security",
"Web-Filtering",
"Web-Windows-Auth",
"Web-App-Dev",
"Web-Net-Ext45",
"Web-Asp-Net45",
"Web-ISAPI-Ext",
"Web-ISAPI-Filter",
"Web-Includes",
"InkandHandwritingServices",
"NET-Framework-Features",
"NET-Framework-Core",
"NET-HTTP-Activation",
"NET-Non-HTTP-Activ",
"NET-WCF-HTTP-Activation45",
"Windows-Identity-Foundation"
)
foreach ($feature in $requiredFeatures)
{
WindowsFeature "WindowsFeature-$feature"
{
Ensure = 'Present'
Name = $feature
}
}
$prereqDependencies = $RequiredFeatures | ForEach-Object -Process {
return "[WindowsFeature]WindowsFeature-$_"
}
OfficeOnlineServerInstall InstallBinaries
{
Ensure = "Present"
Path = "C:\Installer\setup.exe"
DependsOn = $prereqDependencies
}
OfficeOnlineServerFarm LocalFarm
{
InternalURL = "https://officeonline.contoso.com"
EditingEnabled = $true
DependsOn = "[OfficeOnlineServerInstall]InstallBinaries"
}
}
|
PowerShellCorpus/PowerShellGallery/OfficeOnlineServerDsc/1.0.0.0/Examples/Resources/OfficeOnlineServerFarm/1-NewFarm.ps1
|
1-NewFarm.ps1
|
<#
.EXAMPLE
This example shows how to create a basic web apps farm. There are many more options
that can be configured on this resource, but this minimum configuration will deploy
a farm that has editing enabled.
#>
Configuration Example
{
param()
Import-DscResource -ModuleName OfficeOnlineServerDsc
OfficeOnlineServerFarm LocalFarm
{
InternalURL = "https://officeonline.contoso.com"
EditingEnabled = $true
}
}
|
PowerShellCorpus/PowerShellGallery/OfficeOnlineServerDsc/1.0.0.0/Examples/Resources/OfficeOnlineServerMachine/1-JoinFarm.ps1
|
1-JoinFarm.ps1
|
<#
.EXAMPLE
This example shows how to join a machine to an Office Web Apps farm. This
shows that the new server will use all roles (it is not recommended to
split roles out to dedicated servers for Office Online Server farms of
less than 50 servers).
#>
Configuration Example
{
param()
Import-DscResource -ModuleName OfficeOnlineServerDsc
OfficeOnlineServerMachine JoinFarm
{
MachineToJoin = "office1.contoso.com"
Roles = "All"
}
}
|
PowerShellCorpus/PowerShellGallery/OfficeOnlineServerDsc/1.0.0.0/Examples/Resources/OfficeOnlineServerInstall/1-InstallBinaries.ps1
|
1-InstallBinaries.ps1
|
<#
.EXAMPLE
This example shows how to install the binaries for office online server to the local server.
#>
Configuration Example
{
param()
Import-DscResource -ModuleName OfficeOnlineServerDsc
OfficeOnlineServerInstall InstallBinaries
{
Ensure = "Present"
Path = "C:\Installer\setup.exe"
}
}
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/scan/foreach-project.ps1
|
foreach-project.ps1
|
function Use-Projects {
[CmdletBinding(DefaultParameterSetName="default",SupportsShouldProcess=$true)]
param(
[Parameter(ParameterSetName="scan")]
[switch][bool] $scan,
[Parameter(ParameterSetName="default")]
[switch][bool] $all,
[Parameter(ParameterSetName="default")]
[switch][bool] $AllowNoNuspec = $true,
[Parameter(ParameterSetName="default")]
[switch][bool] $force,
[Parameter(Mandatory=$true, ParameterSetName="default")]
[ScriptBlock] $cmd
)
DynamicParam
{
$paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
if ($true -or (test-path ".projects.json")) {
$paramname = "Project"
$paramType = [string[]]
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $false
#$attributes.Position = 0
$attributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
if ((test-path ".projects.json")) {
$script:projects = get-content ".projects.json" | out-string | convertfrom-jsonnewtonsoft
$validvalues = $projects.Keys
$validateset = new-object System.Management.Automation.ValidateSetAttribute -ArgumentList @($validvalues)
$attributeCollection.Add($validateset)
$attributeCollection.Add((new-object System.Management.Automation.AllowEmptyStringAttribute))
}
$dynParam1 = new-object -Type System.Management.Automation.RuntimeDefinedParameter($paramname, $paramType, $attributeCollection)
$paramDictionary.Add($paramname, $dynParam1)
}
$c = get-command "push-nuget"
$cmdlet = $pscmdlet
foreach($p in $c.Parameters.GetEnumerator()) {
if ($p.Key -in [System.Management.Automation.PSCmdlet]::OptionalCommonParameters -or `
$p.Key -in [System.Management.Automation.PSCmdlet]::CommonParameters) {
continue
}
$dynParam1 = new-object -Type System.Management.Automation.RuntimeDefinedParameter($p.Key, $p.Value.ParameterType, $p.Value.Attributes)
$paramDictionary.Add($p.key, $dynParam1)
}
return $paramDictionary
}
begin {
function filter-BoundParameters($cmd, $bound) {
$c = get-command $cmd
$cmdlet = $pscmdlet
if ($bound -eq $null) {
$bound = $cmdlet.MyInvocation.BoundParameters
}
$r = @{}
foreach($p in $c.Parameters.GetEnumerator()) {
if ($p.key -in $bound.Keys) {
$r += @{ $p.key = $bound[$p.key] }
}
}
return $r
}
}
process {
if ($scan -or !(test-path ".projects.json")) {
scan-projects
if ($scan) { return }
}
$project = $PSBoundParameters["Project"]
if ($script:projects -eq $null) { $projects = get-content ".projects.json" | out-string | convertfrom-jsonnewtonsoft }
if ($all) {
$project = $projects.Keys
}
elseif ($project -eq $null) {
$project = $projects.Keys
if (!$AllowNoNuspec) {
$project = $project | ? { $projects[$_].hasNuspec -eq "true" }
if ($project.count -eq 0) {
write-host "no projects with nuspec found! try using -allownonuspec"
}
write-verbose "found $($project.count) projects with nuspec"
}
else {
write-verbose "processing $($project.count) projects"
}
}
#. ./pack-nugets.ps1 -Filter $Filter
function process-project {
param($project)
$path = $projects[$project].path
$projects[$project].name = $project
if ($projects[$project].hasNuspec -ne "true" -and !$force -and !$AllowNoNuspec) {
write-host "skipping project '$project' with no nuspec"
continue
}
pushd
try {
cd (split-path -parent $path)
$curr = $projects[$project]
@($curr) | % {
$o = Invoke-Expression $cmd.ToString()
}
#$o = Invoke-Command $cmd -ArgumentList @($projects[$project]) -InputObject $projects[$project] -NoNewScope
return $o
}
catch {
#write-error $_
#return $_
#throw $_
throw
}
finally {
popd
}
}
$r = @{}
foreach($p in @($project)) {
$r += @{ $p = (process-project $p) }
}
$r
}
}
new-alias Foreach-Project Use-Projects
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/scan/scan-projects.ps1
|
scan-projects.ps1
|
import-module newtonsoft.json
function Initialize-Projects {
[CmdletBinding()]
param ($Path = ".")
$_path = $path
ipmo pathutils
$projectFiles = Get-Listing -Path $_path -files -include "*.csproj","*.xproj" -Recursive `
-Excludes "node_modules/","artifacts/","bin/","obj/",".hg/","dnx-packages/","packages/","/common/","bower_components/","reader-content/","publish/","^\..*/"
$projects = @{}
$projectFiles | % {
$name = [System.IO.Path]::GetFileNameWithoutExtension($_.Name)
$path = Get-RelativePath (gi .).fullname $_.fullname
# $false and $true cause trouble when serializing with newtonsoft
$hasNuspec = "false"
try {
$foundNuspec = test-path (join-path (split-path $path -Parent) "$name.nuspec")
if ($foundNuspec) { $hasNuspec = "true" }
} catch {
}
if ($projects.ContainsKey($name)) {
write-warning "duplicate projects found: $($projects[$name].path)"
write-warning " and $path"
$guid = [guid]::NewGuid().ToString("n")
$projects += @{ "$($name)_$guid" = @{ path = $path; hasNuspec = $hasNuspec }}
} else {
write-verbose "found project '$name' at '$path'"
$projects += @{ "$name" = @{ path = $path; hasNuspec = $hasNuspec }}
}
}
$projects | convertto-jsonnewtonsoft | out-file (join-path $_path ".projects.json")
#$s =new-object -type "Newtonsoft.Json.JsonSerializerSettings"
#$s.ReferenceLoopHandling = [Newtonsoft.Json.ReferenceLoopHandling]::Ignore
write-host "Found $($projects.Count) projects"
}
New-Alias Scan-Projects Initialize-Projects
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/scan/push-nugets.ps1
|
push-nugets.ps1
|
import-module newtonsoft.json
function Push-Nugets {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[switch][bool] $scan,
[switch][bool] $all,
[switch][bool] $AllowNoNuspec,
[switch][bool] $force
)
DynamicParam
{
$paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
if ($true -or (test-path ".projects.json")) {
$paramname = "Project"
$paramType = [string[]]
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $false
#$attributes.Position = 0
$attributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
if ((test-path ".projects.json")) {
$script:projects = get-content ".projects.json" | out-string | convertfrom-jsonnewtonsoft
$validvalues = $projects.Keys
$validateset = new-object System.Management.Automation.ValidateSetAttribute -ArgumentList @($validvalues)
$attributeCollection.Add($validateset)
}
$dynParam1 = new-object -Type System.Management.Automation.RuntimeDefinedParameter($paramname, $paramType, $attributeCollection)
$paramDictionary.Add($paramname, $dynParam1)
}
$c = get-command "push-nuget"
$cmdlet = $pscmdlet
foreach($p in $c.Parameters.GetEnumerator()) {
if ($p.Key -in [System.Management.Automation.PSCmdlet]::OptionalCommonParameters -or `
$p.Key -in [System.Management.Automation.PSCmdlet]::CommonParameters) {
continue
}
$dynParam1 = new-object -Type System.Management.Automation.RuntimeDefinedParameter($p.Key, $p.Value.ParameterType, $p.Value.Attributes)
$paramDictionary.Add($p.key, $dynParam1)
}
return $paramDictionary
}
begin {
function filter-BoundParameters($cmd, $bound) {
$c = get-command $cmd
$cmdlet = $pscmdlet
if ($bound -eq $null) {
$bound = $cmdlet.MyInvocation.BoundParameters
}
$r = @{}
foreach($p in $c.Parameters.GetEnumerator()) {
if ($p.key -in $bound.Keys) {
$r += @{ $p.key = $bound[$p.key] }
}
}
return $r
}
}
process {
if ($scan -or !(test-path ".projects.json")) {
scan-projects
if ($scan) { return }
}
$b = $cmdlet.MyInvocation.BoundParameters
$project = $PSBoundParameters["Project"]
function push-project($project) {
$path = $project.path
if ($project.hasNuspec -ne "true" -and !$force -and !$AllowNoNuspec) {
write-host "skipping project '$($project.name)' with no nuspec. use -AllowNoNuspec to override"
continue
}
if ($project.path.startswith("test\")) {
write-host "skipping TEST project '$($project.name)'"
continue
}
$p = filter-BoundParameters "push-nuget" -bound $b
return push-nuget @p
}
$a = @{
AllowNoNuspec = ($AllowNoNuspec -or $force)
}
if ($project -ne $null) {
$a += @{
project = $project
}
}
foreach-project @a -cmd {
try {
push-project $_
} catch {
#Write-Error "$($_.Exception.Message) $($_.ScriptStackTrace)"
#throw
throw "$($_.Exception.Message) $($_.ScriptStackTrace)"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/sln-verification.ps1
|
sln-verification.ps1
|
import-module pathutils
import-module publishmap
function get-slndependencies {
[CmdletBinding(DefaultParameterSetName = "sln")]
param(
[Parameter(Mandatory=$true, ParameterSetName="sln",Position=0)][Sln]$sln,
[Parameter(Mandatory=$true, ParameterSetName="slnfile",Position=0)][string]$slnfile
)
if ($sln -eq $null) { $sln = import-sln $slnfile }
$projects = get-slnprojects $sln | ? { $_.type -eq "csproj" }
$deps = $projects | % {
if (test-path $_.fullname) {
$p = import-csproj $_.fullname
$refs = @()
$refs += @($p | get-projectreferences)
$refs += @($p | get-nugetreferences)
} else {
$p = $null
$refs = $null
}
return new-object -type pscustomobject -property @{ project = $_; csproj = $p; refs = $refs }
}
$result = @()
foreach($p in $deps) {
if ($p.refs -ne $null -and $p.refs.length -gt 0) {
foreach($r in $p.refs) {
$path = $r.path
$path = join-path (split-path -parent $p.project.fullname) $r.path
$slnrel = get-relativepath (split-path -parent $sln.fullname) $path
$slnproj = $projects | ? { $_.path -eq $slnrel }
$existsInSln = $slnproj -ne $null
$exists = test-path $path
#$null = $r | add-property -name "Valid" -value $existsInSln
if ($r.type -eq "project") {
$r.IsValid = $r.IsValid -and $existsInSln
}
$version = $null
if ($r.type -eq "nuget") {
if ($r.path -ne $null -and $r.path.replace("\","/") -match "/.*?(?<version>[0-9]+\.[0-9]+\.[0-9]+.*?)/") {
$version = $Matches["version"]
}
}
$props = [ordered]@{ project = $p.project; ref = $r; refType = $r.type; version = $version; IsProjectValid = $true }
$result += new-object -type pscustomobject -property $props
}
} else {
$isvalid = $true
if ($p.csproj -eq $null) { $isvalid = $false }
$props = [ordered]@{ project = $p.project; ref = $null; refType = $null; version = $null; IsProjectValid = $isvalid }
$result += new-object -type pscustomobject -property $props
}
}
return $result
}
function test-sln {
[CmdletBinding(DefaultParameterSetName = "sln")]
param(
[Parameter(Mandatory=$false, ParameterSetName="sln",Position=0)][Sln]$sln,
[Parameter(Mandatory=$false, ParameterSetName="slnfile",Position=0)][string]$slnfile,
[switch][bool] $missing,
[switch][bool] $validate,
$filter = $null
)
if ($sln -eq $null) {
if ([string]::IsNullOrEmpty($slnfile)) {
$slns = @(get-childitem "." -Filter "*.sln")
if ($slns.Length -eq 1) {
$slnfile = $slns[0].fullname
}
else {
if ($slns.Length -eq 0) {
throw "no sln file given and no *.sln found in current directory"
}
else {
throw "no sln file given and more than one *.sln file found in current directory"
}
}
}
if ($slnfile -eq $null) { throw "no sln file given and no *.sln found in current directory" }
$sln = import-sln $slnfile
}
$deps = get-slndependencies $sln
if ($filter -ne $null) {
$deps = $deps | ? {
if (!($_.ref.ShortName -match $filter)) { write-verbose "$($_.ref.ShortName) does not match filter:$filter" }
return $_.ref.ShortName -match $filter
}
}
$missingdeps = @($deps | ? { $_.IsProjectValid -eq $false -or ($_.ref -ne $null -and $_.ref.IsValid -eq $false) })
if ($missing) {
return $missingdeps
}
if ($validate) {
return $missingdeps.length -eq 0
}
return $deps
}
function test-slndependencies {
[CmdletBinding(DefaultParameterSetName = "sln")]
param(
[Parameter(Mandatory=$true, ParameterSetName="sln",Position=0)][Sln]$sln,
[Parameter(Mandatory=$true, ParameterSetName="slnfile",Position=0)][string]$slnfile
)
if ($sln -eq $null) { $sln = import-sln $slnfile }
$deps = get-slndependencies $sln
$valid = $true
$missing = @()
foreach($d in $deps) {
if ($d.ref -ne $null -and $d.ref.IsValid -eq $false) {
$valid = $false
$missing += new-object -type pscustomobject -property @{ Ref = $d.ref; In = $d.project.fullname }
}
if ($d.isprojectvalid -eq $false) {
$valid = $false
$missing += new-object -type pscustomobject -property @{ Ref = $d.project; In = $sln.fullname }
}
}
return $valid,$missing
}
function find-reporoot($path = ".") {
$found = find-upwards ".git",".hg" -path $path
if ($found -ne $null) { return split-path -Parent $found }
else { return $null }
}
function find-globaljson($path = ".") {
return find-upwards "global.json" -path $path
}
function find-matchingprojects {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]$missing,
[Parameter(Mandatory=$true)]$reporoot
)
if (test-path (join-path $reporoot ".projects.json")) {
$script:projects = get-content (join-path $reporoot ".projects.json") | out-string | convertfrom-jsonnewtonsoft
write-verbose "getting csproj from cached file .projects.json"
$csprojs = $script:projects.GetEnumerator() | ? {
#ignore non-existing projects from ".projects.json"
test-path (join-path $reporoot $_.value.path)
} | % {
get-item (join-path $reporoot $_.value.path)
}
} else {
$csprojs = get-childitem "$reporoot" -Filter "*.csproj" -Recurse
}
#$csprojs | select -expandproperty name | format-table | out-string | write-verbose
$packagesdir = find-packagesdir $reporoot
write-verbose "found $($csprojs.length) csproj files in repo root '$reporoot' and subdirs. pwd='$(pwd)'. Packagesdir = '$packagesdir'"
$missing = $missing | % {
$m = $_
$matching = $null
if ($m.ref.type -eq "project" -or $m.ref.type -eq "csproj") {
$matching = @($csprojs | ? { [System.io.path]::GetFilenameWithoutExtension($_.Name) -eq $m.ref.Name })
$null = $m | add-property -name "matching" -value $matching
#write-verbose "missing: $_.Name matching: $matching"
}
if ($m.ref.type -eq "nuget") {
if ($m.ref.path -match "^(?<packages>.*packages[/\\])(?<pkg>.*)") {
$matchingpath = join-path $packagesdir $matches["pkg"]
if (test-path $matchingpath) {
$matching = get-item $matchingpath
} else {
$matching = new-object -type pscustomobject -property @{
fullname = $matchingpath
}
}
$null = $m | add-property -name "matching" -value $matching
#write-verbose "missing: $_.Name matching: $matching"
}
}
if ($matching -eq $null) {
write-verbose "no project did match '$($m.ref.Name)' reference of type $($m.ref.type)"
} else {
write-verbose "found $(@($matching).Length) matching projects for '$($m.ref.Name)' reference of type $($m.ref.type):"
$matching | % {
write-verbose " $($_.fullname)"
}
}
return $m
}
return $missing
}
function repair-slnpaths {
[CmdletBinding(DefaultParameterSetName = "sln")]
param(
[Parameter(Mandatory=$false, ParameterSetName="sln",Position=0)][Sln]$sln,
[Parameter(Mandatory=$false, ParameterSetName="slnfile",Position=0)][string]$slnfile,
[Parameter(Position=1)] $reporoot,
[Parameter(Position=2)] $filter = $null,
[switch][bool] $tonuget,
[switch][bool] $insln,
[switch][bool] $incsproj,
[switch][bool] $removemissing,
[switch][bool] $prerelease
)
if ($sln -eq $null) {
if ([string]::IsNullOrEmpty($slnfile)) {
$slns = @(get-childitem "." -Filter "*.sln")
if ($slns.Length -eq 1) {
$slnfile = $slns[0].fullname
}
else {
if ($slns.Length -eq 0) {
throw "no sln file given and no *.sln found in current directory"
}
else {
throw "no sln file given and more than one *.sln file found in current directory"
}
}
}
if ($slnfile -eq $null) { throw "no sln file given and no *.sln found in current directory" }
$sln = import-sln $slnfile
}
if (!$incsproj.IsPresent -and !$insln.ispresent) {
$incsproj = $true
$insln = $true
}
if ($insln) {
$valid,$missing = test-slndependencies $sln
write-verbose "SLN: found $($missing.length) missing projects"
if ($reporoot -eq $null) {
$reporoot = find-reporoot $sln.fullname
if ($reporoot -ne $null) {
write-host "auto-detected repo root at $reporoot"
}
}
if ($reporoot -eq $null) {
throw "No repository root given and none could be detected"
}
write-host "Fixing SLN..."
write-verbose "looking for csprojs in reporoot..."
$missing = find-matchingprojects $missing $reporoot
if ($filter -ne $null) {
$missing = $missing | ? {
#if (!($_.ref.ShortName -match $filter)) { write-verbose "$($_.ref.ShortName) does not match filter:$filter" }
return $_.ref.ShortName -match $filter
}
}
$fixed = @{}
foreach($_ in $missing) {
if ($fixed.ContainsKey($_.ref.name)) {
write-verbose "skipping fixed reference $($_.ref.name)"
continue
}
if ($_.ref.Type -ne "project" -and $_.ref.Type -ne "csproj") {
write-verbose "skipping non-project reference '$($_.ref.name)' of type '$($_.ref.type)'"
continue
}
write-verbose "trying to fix missing SLN reference '$($_.ref.name)'"
if ($_.matching -eq $null -or $_.matching.length -eq 0) {
write-warning "no matching project found for SLN item $($_.ref.name)"
if ($removemissing) {
write-warning "removing $($_.ref.Path)"
remove-slnproject $sln $($_.ref.Name) -ifexists
$sln.Save()
}
}
else {
$matching = $_.matching
if (@($matching).length -gt 1) {
write-host "found $($matching.length) matching projects for $($_.ref.name). Choose one:"
$i = 1
$matching = $matching | sort FullName
$matching | % {
write-host " $i. $($_.fullname)"
$i++
}
$c = read-host
$matching = $matching[[int]$c-1]
}
if ($_.ref -is [slnproject]) {
$relpath = get-relativepath $sln.fullname $matching.fullname
write-host "Fixing bad SLN reference: $($_.ref.Path) => $relpath"
$_.ref.Path = $relpath
update-slnproject $sln $_.ref
$fixed[$_.ref.name] = $true
}
elseif ($_.ref -isnot [referencemeta]) {
$relpath = get-relativepath $sln.fullname $matching.fullname
write-host "Adding missing SLN reference: $($_.ref.Path) => $relpath"
$csp = import-csproj $matching.fullname
add-slnproject $sln -name $csp.Name -path $relpath -projectguid $csp.guid
$fixed[$_.ref.name] = $true
} else {
$relpath = get-relativepath $sln.fullname $matching.fullname
write-host "Adding missing SLN reference: $($_.ref.Path) => $relpath"
$csp = import-csproj $matching.fullname
add-slnproject $sln -name $csp.Name -path $relpath -projectguid $csp.guid
$fixed[$_.ref.name] = $true
#write-warning "Don't know what to do with $($_.ref) of type $($_.ref.GetType())"
}
}
}
write-host "saving sln"
$sln.Save()
}
if ($incsproj) {
write-host "Fixing CSPROJs..."
$projects = get-slnprojects $sln | ? { $_.type -eq "csproj" }
if ($tonuget) {
$pkgdir =(find-packagesdir $reporoot)
if (!(test-path $pkgdir)) {
$null = new-item -type Directory $pkgdir
}
$missing = test-sln $sln -missing
$missing = @($missing | ? { $_.ref.type -eq "project"})
$missing = $missing | % { $_.ref.name } | sort -Unique
$missing | % {
try {
write-host "replacing $_ with nuget"
$found = find-nugetPath $_ $pkgdir
if ($found -eq $null) {
write-host "installing package $_"
nuget install $_ -out $pkgdir -pre
}
convert-referencestonuget $sln -projectName $_ -packagesDir $pkgdir -filter $filer
} catch {
write-error $_
}
}
}
foreach($_ in $projects) {
if (test-path $_.fullname) {
$csproj = import-csproj $_.fullname
if (!$tonuget) {
$null = repair-csprojpaths $csproj -reporoot $reporoot -prerelease:$prerelease
}
}
}
}
# $valid,$missing = test-slndependencies $sln
# $valid | Should Be $true
}
function get-csprojdependencies {
[CmdletBinding(DefaultParameterSetName = "csproj")]
param(
[Parameter(Mandatory=$true, ParameterSetName="csproj",Position=0)][Csproj]$csproj,
[Parameter(Mandatory=$true, ParameterSetName="csprojfile",Position=0)][string]$csprojfile
)
if ($csproj -eq $null) { $csproj = import-csproj $csprojfile }
$refs = @()
$refs += get-projectreferences $csproj
$refs += get-nugetreferences $csproj
$refs = $refs | % {
$r = $_
$props = [ordered]@{ ref = $r; refType = $r.type; path = $r.path }
return new-object -type pscustomobject -property $props
}
return $refs
}
function repair-csprojpaths {
[CmdletBinding(DefaultParameterSetName = "csproj")]
param(
[Parameter(Mandatory=$true, ParameterSetName="csproj",Position=0)][Csproj]$csproj,
[Parameter(Mandatory=$true, ParameterSetName="csprojfile",Position=0)][string]$csprojfile,
$reporoot = $null,
[switch][bool] $prerelease
)
if ($csproj -eq $null) { $csproj = import-csproj $csprojfile }
$deps = get-csprojdependencies $csproj
$missing = @($deps | ? { $_.ref.IsValid -eq $false })
write-verbose "($($csproj.name)): CSPROJ found $($missing.length) missing projects"
if ($reporoot -eq $null) {
$reporoot = find-reporoot $csproj.fullname
if ($reporoot -ne $null) {
write-verbose "($($csproj.name)): auto-detected repo root at $reporoot"
}
}
if ($reporoot -eq $null) {
throw "($($csproj.name)): No repository root given and none could be detected"
}
if ($missing.length -gt 0) {
write-verbose "($($csproj.name)): looking for projects matching missing references"
$missing = find-matchingprojects $missing $reporoot
$missing | % {
if ($_.matching -eq $null -or $_.matching.length -eq 0) {
write-warning "($($csproj.name)): no matching project found for CSPROJ reference $($_.ref.Path)"
}
else {
$relpath = get-relativepath $csproj.fullname $_.matching.fullname
$_.ref.Path = $relpath
if ($_.ref.type -eq "project" -and $_.ref.Node.Include -ne $null) {
write-verbose "($($csproj.name)): fixing CSPROJ reference in $($csproj.name): $($_.ref.Path) => $relpath"
$_.ref.Node.Include = $relpath
}
if ($_.ref.type -eq "nuget" -and $_.ref.Node.HintPath -ne $null) {
write-verbose "($($csproj.name)): fixing NUGET reference in $($csproj.name): $($_.ref.Path) => $relpath"
$_.ref.Node.HintPath = $relpath
}
}
}
$csproj.Save()
write-verbose "($($csproj.name)): missing references done"
}
$pkgdir = find-packagesdir $reporoot
$dir = split-path -parent $csproj.FullName
if (test-path (Join-Path $dir "packages.config")) {
write-verbose "($($csproj.name)): checking packages.config"
$pkgs = get-packagesconfig (Join-Path $dir "packages.config")
$pkgs = $pkgs.packages
$isInsideVS = (get-command "install-package" -Module nuget -errorAction Ignore) -ne $null
if ($isInsideVS) {
write-verbose "($($csproj.name)): detected Nuget module. using Nuget/install-package"
foreach($dep in $pkgs) {
nuget\install-package -ProjectName $csproj.name -id $dep.id -version $dep.version -prerelease:$prerelease
}
} else {
$refs = get-nugetreferences $csproj
foreach($pkgref in $pkgs) {
$ref = $refs | ? { $_.ShortName -eq $pkgref.id }
if ($ref -eq $null) {
$nugetpath = find-nugetpath $pkgref.id $pkgdir -versionhint $pkgref.version
if ($nugetpath -ne $null) {
$dllname = [System.IO.Path]::GetFileNameWithoutExtension($nugetpath.PAth)
$ref = $refs | ? { $_.ShortName -eq $dllname }
if ($ref -ne $null) {
#write-verbose "$($pkgref.id) maps to $($nugetpath.PAth)"
}
}
if ($ref -eq $null) {
write-warning "($($csproj.name)): missing csproj reference for package $($pkgref.id)"
}
}
if ($ref.path -notmatch "$($pkgref.version)\\") {
# bad reference in csproj? try to detect current version
if ($ref.path -match "$($pkgref.id).(?<version>.*?)\\") {
Write-Warning "($($csproj.name)): version of package '$($pkgref.id)' in csproj: '$($matches["version"])' doesn't match packages.config version: '$($pkgref.version)'. Fixing"
# fix it
$ref.path = $ref.path -replace "$($pkgref.id).(?<version>.*?)\\","$($pkgref.id).$($pkgref.version)\"
write-verbose "corrected path: $($ref.path)"
$ref.Node.HintPath = $ref.path
$inc = $ref.Node.Include
if ($inc -ne $null -and $inc -match "$($pkgref.id),\s*Version=(.*?),") {
write-verbose "($($csproj.name)): fixing include tag"
$inc = $inc -replace "($($pkgref.id)),\s*Version=(.*?),",'$1,'
write-verbose "corrected include: $($ref.path)"
$ref.Node.Include = $inc
}
$csproj.save()
}
}
}
}
}
# $valid,$missing = test-slndependencies $sln
# $valid | Should Be $true
}
function update-nuget {
param([Parameter(mandatory=$true,ValueFromPipeline=$true)]$id, $version)
process {
write-verbose "checking packages.config"
$pkgconfig = get-packagesconfig ("packages.config")
$pkgs = $pkgconfig.packages
$changed = $false
foreach($pkgid in @($id)) {
$ver = $version
if ($pkgid -match "(?<id>.*)\.(?<version>[0-9]+\.[0-9]+\.[0-9]+.*)") {
$ver = $matches["version"]
$pkgid = $matches["id"]
}
else {
write-warning "please specify package version with -version or in package id (like '$pkgid.1.0.0')"
continue
}
if ($ver -eq $null) {
}
$ref = $pkgs | ? { $_.id -eq $pkgid }
if ($ref -ne $null) {
$changed = $true
$ref.version = $ver
} else {
write-warning "package $pkgid not found in packages.config"
continue
}
}
if ($changed) {
$pkgconfig | set-packagesconfig -outfile "packages.config"
get-childitem . -filter "*.csproj" | %{
fix-csproj $_.FullName
}
}
}
}
new-alias fix-sln repair-slnpaths
new-alias fixsln fix-sln
new-alias fix-csproj repair-csprojpaths
new-alias fixcsproj fix-csproj
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/conversion.ps1
|
conversion.ps1
|
function get-referencesTo {
[CmdletBinding(DefaultParameterSetName="sln")]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0, ParameterSetName="sln")][Sln] $sln,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0, ParameterSetName="csproj")][Csproj] $csproj,
[Alias("project")][Parameter(Mandatory=$true, Position=1)][string]$projectName
)
$r = @()
if ($csproj -ne $null) {
$proj = $csproj
$p = $csproj
$projpath = $proj.fullname
#$projpath = (gi ($projpath)).fullname
$nugetrefs = get-nugetreferences $proj
$n = $nugetrefs | ? { $_.Name -eq $projectname }
if ($n -ne $null) {
write-verbose "$($p.name) => $projectname [nuget]"
$r += @{ project = $proj; ref = $n; type = "nuget"; projectname = $p.name; name = $p.name; projectpath = $projpath }
}
$projrefs = get-projectreferences $proj
$pr = $projrefs | ? { $_.Name -eq $projectName }
if ($pr -ne $null) {
write-verbose "$($p.name) => $projectname [project]"
$r += @{ project = $proj; ref = $pr; type = "project"; projectname = $p.name; name = $p.name; projectpath = $projpath }
}
if ($n -eq $null -and $pr -eq $null) {
write-verbose "$($p.name) => (none)"
}
} elseif ($sln -ne $null) {
$projects = $sln | get-slnprojects | ? { $_.type -eq "csproj" }
$slndir = split-path $sln.path -parent
foreach($p in $projects) {
$projpath = join-path $slndir $p.path
if(!(test-path $projpath)) {
#write-warning "SLN project $($p.name) not found"
continue
}
$projpath = (gi ($projpath)).fullname
$proj = import-csproj $projpath
$r += get-referencesTo $proj $projectname
}
}
#if ($project -is [string]) {
# $project = $sln | get-slnprojects | ? { $_.name -eq $project }
#}
return $r
}
function convert-projectReferenceToNuget {
[CmdletBinding(DefaultParameterSetName="referencename",PositionalBinding=$true)]
param(
[Parameter(Mandatory=$true)][Csproj] $proj,
[Parameter(Mandatory=$true, ParameterSetName="referenceObj")][ReferenceMeta] $pr,
[Parameter(Mandatory=$true, ParameterSetName="referencename")][string] $projectname,
[Alias("pre")]
[switch][bool] $prerelease
)
if ($pr -eq $null) { throw "missing reference in $($proj.name)" }
write-verbose "found project reference to $projectname in $($proj.name)"
$result += $pr
if ((get-command install-package -Module nuget -erroraction ignore) -ne $null) {
write-verbose "detected Nuget module. using Nuget/install-package: install-package -ProjectName $($proj.name) -id $($pr.Name)"
nuget\install-package -ProjectName $proj.name -id $pr.Name -prerelease:$prerelease
return "converted with NuGet module"
}
else {
$converted = convertto-nugetreference $pr $packagesDir
if ($converted -eq $null) { throw "failed to convert referece $pr in project $($proj.name)" }
$null = replace-reference $proj $pr $converted
write-verbose "saving modified project $($proj.fullname)"
$null = $proj.save($proj.fullname)
return $converted
}
}
function convert-ReferencesToNuget {
[CmdletBinding(DefaultParameterSetName="slnobj")]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="slnobj", Position=0)][Sln] $sln,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="slnfile", Position=0)][string] $slnfile,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="csprojobj", Position=0)][csproj] $csproj,
[Alias("project")][Parameter(Mandatory=$true, Position=1)][string]$projectName,
[Parameter(Mandatory=$false, Position=2)] $packagesDir = $null,
$filter = $null,
[Alias("pre")]
[switch][bool] $prerelease
)
if (![string]::isnullorempty($slnfile)) {
$sln = import-sln $slnfile
}
if ($packagesdir -eq $null) {
if ($sln -ne $null) { $d = $sln.fullname }
if ($csproj -ne $null) { $d = $csproj.fullname }
$packagesdir = find-packagesdir (split-path -parent $d)
}
$converted = @()
$csprojs = @()
if ($sln -ne $null)
{
$projects = $sln | get-slnprojects
$slndir = split-path $sln.path -parent
# find all projects that reference $projectName
$references = get-referencesto $sln $projectname
}
elseif ($csproj -ne $null) {
$references = get-referencesto $csproj $projectname
}
foreach($r in $references) {
if ($r.type -ne "project") { continue }
if ($fiter -ne $null -and $r.shortname -notmatch $filter) { continue }
$converted = @(convert-projectReferenceToNuget -proj $r.project -pr $r.ref -prerelease:$prerelease)
$csprojs += get-content $r.projectpath
$converted += $converted
}
if ($sln -ne $null) {
$sln.Save()
remove-slnproject $sln $projectName -ifexists
}
write-verbose "converted $($converted.length) references"
return $converted
#return $csprojs
}
function convert-nugetToProjectReference {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
param([Parameter(Mandatory=$false)] $referencename, [Parameter(Mandatory=$false)] $targetProject, [Parameter(Mandatory=$false)] $csproj)
$path = $csproj
if ($path -eq $null) {
$items = @(get-childitem -filter "*.csproj")
if ($items -eq $null -or $items.length -eq 0) {
throw "no csproj given and no csproj found in current dir"
}
if ($items.length -ne $null -and $items.length -gt 1) {
throw "more than one csproj file found. please select one"
}
$path = $items.fullname
}
$csproj = import-csproj $path
$refs = ($csproj | get-externalreferences) + ($csproj | get-nugetreferences)
if ($referenceName -eq $null){
write-host "Choose one reference:"
$refs | select -expand ShortName
return
}
if ($targetproject -eq $null) {
write-host "please provide target project location"
return
}
$r = $refs | ? { $_.shortname -eq $referencename }
$converted = convertto-projectreference $r $targetProject
replace-reference $csproj $r $converted
if ($pscmdlet.ShouldProcess("saving csproj $path")) {
$csproj.Save()
}
}
new-alias convert-ReferencesToNugets convert-ReferencesToNuget
new-alias tonuget convert-ReferencesToNuget
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/packagestoprojectjson.ps1
|
packagestoprojectjson.ps1
|
function Convert-PackagesToProjectJson {
# Script to generate project.json for all packages.config file in the solution.
# Run from root solution folder
# execute this script with powershell:
# powershell -File <filepath>
# [-f <targetframework] net4
Param
(
$Path = ".",
[alias("f")]
[string] $TargetFramework = "net451",
[alias("r")]
[switch]
$redo
)
$ScriptPath = $path
$ScriptDir = Split-Path -Parent $ScriptPath
$PackagesConfigFileName = 'packages.config'
if($redo){
$PackagesConfigFileName = 'packages_old.config'
}
#Create project.json from packages.config
Get-ChildItem -path '.' -Recurse -Include $PackagesConfigFileName |
ForEach {
$PackageFilePath = $_.FullName
$ProjectFilePath = $_.Directory.FullName + '\project.json'
Write-Output $PackageFilePath
Write-Output $ProjectFilePath
'{
"dependencies": {' | Out-File $ProjectFilePath
(Select-xml -xpath '//package' -Path $PackageFilePath | % { """{0}"": ""{1}""" -f $_.Node.id,$_.Node.version }) -join ",`n" | Out-File $ProjectFilePath -Append
' },
"frameworks": {
"' + $TargetFramework + '": {}
},
"runtimes": {
"win-anycpu": {},
"win": {}
}
}' | Out-File $ProjectFilePath -Append
Rename-Item -Path $PackageFilePath -NewName 'packages_old.config'
}
$MsbNS = @{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'}
Get-ChildItem -path '.' -Recurse -Include '*.csproj' | ForEach {
$CsProjFilePath = $_.FullName
$ProjectFilePath = $_.Directory.FullName + '\project.json'
$proj = [xml] (Get-Content $CsProjFilePath)
#Remove all references to ..packages files
$xpath = "//msb:Reference/msb:HintPath[contains(.,'..\packages')]"
$nodes = @(Select-Xml -xpath $xpath $proj -Namespace $MsbNS | foreach {$_.Node})
if (!$nodes) { Write-Verbose "RemoveElement: XPath $XPath not found" }
Write-Output 'Reference Nodes found: ' $nodes.Count
foreach($node in $nodes) {
$referenceNode = $node.ParentNode
$itemGroupNode = $referenceNode.ParentNode
[void]$itemGroupNode.RemoveChild($referenceNode)
}
[System.XML.XMLElement] $itemGroupNoneNode = $null
#Find itemgroup with None Elements, if not found add.
$itemGroupNoneNodes = @(Select-Xml -xpath "//msb:ItemGroup/msb:None" $proj -Namespace $MsbNS | foreach {$_.Node})
Write-Output '$itemGroupNoneNode found: ' $itemGroupNoneNodes.Count
if($itemGroupNoneNodes.Count -eq 0){
# create itemgroup element for None nodes.
Write-Output 'Adding ItemGroup for None Nodes'
$itemGroupNoneNode = $proj.CreateElement('ItemGroup',$proj.DocumentElement.NamespaceURI)
$itemGroupNodes = @(Select-Xml -xpath "//msb:ItemGroup" $proj -Namespace $MsbNS | foreach {$_.Node})
$itemGroupNodes.Count
[void]$proj.DocumentElement.InsertAfter($itemGroupNoneNode,$itemGroupNodes[$itemGroupNodes.Count-1])
}else{
$itemGroupNoneNode = $itemGroupNoneNodes[0].ParentNode
}
#Remove packages.config from ItemGroup
$nodes = @(Select-Xml -xpath "//msb:ItemGroup/msb:None[@Include='packages.config']" $proj -Namespace $MsbNS | foreach {$_.Node})
Write-Output 'packages.config Nodes found: ' $nodes.Count
foreach($node in $nodes) {
$itemGroupNode = $node.ParentNode
[void]$itemGroupNode.RemoveChild($node)
}
#Remove build target EnsureNuGetPackageBuildImports from csproj
$nodes = @(Select-Xml -xpath "//msb:Target[@Name='EnsureNuGetPackageBuildImports']" $proj -Namespace $MsbNS | foreach {$_.Node})
Write-Output 'EnsureNuGetPackageBuildImports target found: ' $nodes.CountAd
foreach($node in $nodes) {
$itemGroupNode = $node.ParentNode
[void]$itemGroupNode.RemoveChild($node)
}
#Add project.json to itemGroup
if( Test-Path $ProjectFilePath){
$nodes = @(Select-Xml -xpath "//msb:ItemGroup/msb:None[@Include='project.json']" $proj -Namespace $MsbNS | foreach {$_.Node})
if($nodes.Count -eq 0){
$projectJsonNoneNode = $proj.CreateElement("None", $proj.DocumentElement.NamespaceURI)
$projectJsonNoneNode.SetAttribute("Include","project.json")
[void]$itemGroupNoneNode.AppendChild($projectJsonNoneNode)
Write-Output 'Adding None node for project.json'
}
}
#add PropertyGroup nodes targetFrameworkProfile, CopyNuGetImplementations, PlatformTarget
# Find the TargetFrameworkVersion to be used to find the parent PropertyGroup node
$xpath = "//msb:PropertyGroup/msb:TargetFrameworkVersion"
$nodes = @(Select-Xml -xpath $xpath $proj -Namespace $MsbNS | foreach {$_.Node})
if ($nodes.Count -gt 0) {
[System.XML.XMLElement] $node = $nodes[0]
$propertyGroupNode = $node.ParentNode
$nodes = @(Select-Xml -xpath "//msb:PropertyGroup/msb:TargetFrameworkProfile" $proj -Namespace $MsbNS | foreach {$_.Node})
if($nodes.Count -eq 0){
$node = $proj.CreateElement("TargetFrameworkProfile", $proj.DocumentElement.NamespaceURI)
[void]$propertyGroupNode.AppendChild($node)
Write-Output 'Adding TargetFrameworkProfile node for PropertyGroup'
}
#$nodes = @(Select-Xml -xpath "//msb:PropertyGroup/msb:CopyNuGetImplementations" $proj -Namespace $MsbNS | foreach {$_.Node})
#if($nodes.Count -eq 0){
# $node = $proj.CreateElement("CopyNuGetImplementations", $proj.DocumentElement.NamespaceURI)
# $textnode = $proj.CreateTextNode("true")
# $node.AppendChild($textnode)
# [void]$propertyGroupNode.AppendChild($node)
# Write-Output 'Adding CopyNuGetImplementations node for PropertyGroup'
#}
$nodes = @(Select-Xml -xpath "//msb:PropertyGroup/msb:PlatformTarget[not(@*)]" $proj -Namespace $MsbNS | foreach {$_.Node})
if($nodes.Count -eq 0){
$node = $proj.CreateElement("PlatformTarget", $proj.DocumentElement.NamespaceURI)
$textnode = $proj.CreateTextNode("AnyCPU")
$node.AppendChild($textnode)
[void]$propertyGroupNode.AppendChild($node)
Write-Output 'Adding PlatformTarget node for PropertyGroup'
}
}
# replace ToolsVersion with 14.0
$attibutes = Select-Xml -xpath "//@ToolsVersion" $proj -Namespace $MsbNS
foreach ($attribute in $attibutes){
$attribute.Node.value = "14.0"
Write-Output 'Setting ToolsVersion to 14.0'
}
$proj.Save($CsProjFilePath)
}
}
function repair-ProjectJSonProjectReferences
{
[CmdletBinding()]
param($path = ".")
if ((get-item $path).psiscontainer) {
$path = "$path/project.json"
}
$p = get-content $path | out-string | ConvertFrom-JsonNewtonsoft
$p.dependencies = $p.dependencies.GetEnumerator() | % { $r = @{} }{ if ($_.value -eq "") {
$_.value = @{ target = "project" }
write-verbose "fixing dependency '$($_.key)'"
}; $r += @{"$($_.Key)" = $_.Value}}{$r}
$p | ConvertTo-JsonNewtonsoft | out-file $path
}
new-alias fix-ProjectJSon repair-ProjectJSonProjectReferences
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/packagesconfig-utils.ps1
|
packagesconfig-utils.ps1
|
function Copy-BindingRedirects {
[CmdletBinding()]
param($from = "app.config", $to = "app.orig.config")
$fromXml = [xml](get-content $from)
$toXml = [xml](get-content $to)
$src = $fromxml.configuration.runtime.assemblyBinding
$runtime = $toxml.SelectNodes('//configuration/runtime') | select -first 1
if ($runtime -eq $null) {
write-verbose "adding 'runtime' node to $to"
$node = [System.Xml.XmlElement]$toxml.CreateElement("runtime")
$null = $toxml.configuration.AppendChild($node)
$runtime = $toxml.SelectNodes('//configuration/runtime') | select -first 1
}
if ($toxml.configuration.runtime.assemblyBinding -ne $null) {
write-verbose "removing old assemblyBinding section from $to"
$null = $toxml.configuration.runtime.RemoveChild($toxml.configuration.runtime.assemblyBinding)
}
write-verbose "copying assemblyBinding section from $from to $to"
$node = $toxml.ImportNode($src, $true)
$null = $runtime.AppendChild($node)
$toXml.OuterXml | out-string | write-verbose
write-verbose "saving $to"
$null = $toXml.Save((get-item $to).FullName)
}
function add-packagetoconfig {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$packagesconfig,
[Parameter(Mandatory=$true)][string]$package,
[Parameter(Mandatory=$true)][string]$version,
[switch][bool] $ifnotexists
)
$existing = $packagesconfig.packages | ? { $_.Id -eq $package }
if ($existing -ne $null) {
if ($ifnotexists) { return }
else {
throw "Packages.config already contains reference to package $package : $($existing | out-string)"
}
}
$node = new-packageNode -document $packagesconfig.xml
$node.id = $package
$node.version = $version
$null = $packagesconfig.xml.DocumentElement.AppendChild($node)
$packagesconfig.packages = $packagesconfig.xml.packages.package
}
function remove-packagefromconfig {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$packagesconfig,
[Parameter(Mandatory=$true)][string]$package
)
$existing = $packagesconfig.packages | ? { $_.Id -eq $package }
if ($existing -ne $null) {
$packagesconfig.xml.packages
$xmlel = ([System.Xml.XmlElement]$packagesconfig.xml.packages)
$null = $xmlel.RemoveChild($existing)
$packagesconfig.packages = $packagesconfig.xml.packages.package
}
else {
throw "package $package not found in packages.config"
}
}
function set-packagesconfig {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$pkgconfig,
[Parameter(Mandatory=$true)]$outfile
)
if ($pkgconfig.xml -eq $null) {
throw "please provide a pkgconfig object from get-packagesconfig"
}
if (!([system.io.path]::IsPathRooted($outfile))) {
$outfile = join-path (get-item ".").FullName $outfile
}
$pkgconfig.xml.Save($outfile)
}
function get-packagesconfig {
param(
[Parameter(Mandatory=$true)]$packagesconfig,
[switch][bool] $createifnotexists
)
if ($packagesconfig.startswith('<?xml')) {
$xml = [xml]$packagesconfig
}
else {
if ($packagesconfig.EndsWith('.csproj')) {
$dir = split-path -parent $packagesconfig
$packagesconfig = "$dir/packages.config"
}
if (test-path $packagesconfig) {
$c = get-content $packagesconfig | Out-String
$xml = [xml]$c
}
elseif ($createifnotexists) {
$content = @'
<?xml version="1.0" encoding="utf-8"?>
<packages>
</packages>
'@
$content | out-file $packagesconfig -encoding utf8
$xml = [xml]$content
}
}
if ($xml.packages -is [string]) {
# weird, when <packages> are empty, .packages is a string!
}
$obj = new-object -type pscustomobject -Property @{ packages = $xml.packages.package; xml = $xml }
return $obj
}
function new-packageNode([Parameter(Mandatory=$true, ValueFromPipeline=$true)][System.Xml.xmldocument]$document) {
$package = [System.Xml.XmlElement]$document.CreateElement("package")
$null = $package.Attributes.Append([System.Xml.XmlAttribute]$document.CreateAttribute("id"))
$null = $package.Attributes.Append($document.CreateAttribute("targetFramework"))
$null = $package.Attributes.Append($document.CreateAttribute("version"))
return $package
}
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/sln-utils.ps1
|
sln-utils.ps1
|
$script:types = @"
public class Sln {
public string OriginalPath {get;set;}
public string Path {get;set;}
public string Fullname { get { return Path; }}
public string[] Content {get;set;}
public SlnProject[] projects {get;set;}
public void Save() {
System.IO.File.WriteAllLines(Fullname, Content);
}
}
public class SlnProject {
public string Name {get;set;}
public string Path {get;set;}
public string Guid {get;set;}
public int Line {get;set;}
public string Type { get;set;}
public string FullName {get;set;}
public string TypeGuid {get;set;}
public override string ToString() {
return Name;
}
}
"@
add-type -TypeDefinition $types
function import-sln {
[OutputType([Sln])]
param($path)
if (!(test-path $path)) {
throw "file not found: '$path'"
}
$content = get-content $path
$sln = new-object -type "sln"
$sln.originalpath = $path
$sln.path = (get-item $path).FullName
$sln.content = $content
return $sln
}
function get-slnprojects {
[OutputType([SlnProject[]])]
param([Parameter(ValueFromPipeline=$true)][Sln]$sln)
$result = @()
# Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Legimi.Core.Utils.Diag", "..\..\..\src\Core\Legimi.Core.Utils.Diag\Legimi.Core.Utils.Diag.csproj", "{678181A1-BF92-46F2-8D71-E3F5057042AB}"
$regex = 'Project\((?<typeguid>.*?)\)\s*=\s*"(?<name>.*?)",\s*"(?<path>.*?)",\s*"(?<guid>.*?)"'
$i = 0
$slndir = (get-item (split-path -parent $sln.path)).fullname
foreach($line in $sln.content) {
if ($line -match $regex) {
$type = "?"
if ([System.io.path]::GetExtension($Matches["path"]) -eq ".csproj") {
$type = "csproj"
}
$result += @( new-object -type SlnProject -Property @{
name = $Matches["name"]
path = $Matches["path"]
guid = $Matches["guid"]
typeguid = $matches["typeguid"]
line = $i
type = $type
fullname = join-path $slndir $Matches["path"]
} )
}
$i++
}
$sln.projects = $result
return $result
}
function find-slnproject {
[OutputType([SlnProject])]
param ([Sln]$sln, [string]$projectname)
if ($sln.projects -eq $null) { $sln.projects = get-slnprojects $sln }
$proj = $sln.projects | ? { $_.name -ieq $projectname }
return $proj
}
function Update-SlnProject {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][Sln]$sln,
[Parameter(Mandatory=$true)][SlnProject] $project
)
# Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Legimi.Core.Utils.Diag", "..\..\..\src\Core\Legimi.Core.Utils.Diag\Legimi.Core.Utils.Diag.csproj", "{678181A1-BF92-46F2-8D71-E3F5057042AB}"
$regex = 'Project\((?<typeguid>.*?)\)\s*=\s*"(?<name>.*?)",\s*"(?<path>.*?)",\s*"(?<guid>.*?)"'
$line = "Project($($project.typeguid)) = ""$($project.Name)"", ""$($project.Path)"", ""$($project.guid)"""
write-verbose "replacing line:"
write-verbose "$($sln.content[$project.line])"
write-verbose "=> $line"
$sln.content[$project.line] = $sln.content[$project.line] -replace $regex,$line
}
function Add-SlnProject {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][Sln]$sln,
[Parameter(Mandatory=$true)]$Name,
[Parameter(Mandatory=$true)]$Path,
[Parameter(Mandatory=$true)]$ProjectGuid,
[Parameter(Mandatory=$false)]$TypeGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
)
# Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Legimi.Core.Utils.Diag", "..\..\..\src\Core\Legimi.Core.Utils.Diag\Legimi.Core.Utils.Diag.csproj", "{678181A1-BF92-46F2-8D71-E3F5057042AB}"
#EndProject
$line = "Project(""$($TypeGuid)"") = ""$($Name)"", ""$($Path)"", ""$ProjectGuid"""
$pos = -1
for($i = $sln.content.length-1; $i -ge 0; $i--) {
if ($sln.content[$i] -match "EndProject") {
$pos = $i + 1
break;
}
}
if ($pos -lt 0) {
throw "failed to found last 'EndProject' node"
}
write-verbose "adding line: at pos $pos"
write-verbose "=> $line"
$c = { $sln.content }.Invoke()
$c.Insert($pos, "EndProject")
$c.Insert($pos, $line)
$sln.content = $c
}
function remove-slnproject {
[CmdletBinding()]
param ([Sln]$sln, $projectname, [switch][bool] $ifexists)
$proj = find-slnproject $sln $projectname
if ($proj -eq $null) {
if ($ifexists) {
return
} else {
throw "project '$projectname' not found in solution"
}
}
$regex = "EndProject"
$endi = -1
for($i = $proj.line; $i -lt $sln.content.length; $i++) {
$line = $sln.content[$i]
if ($line -match $regex) {
$endi = $i
break;
}
}
if ($endi -eq -1) { throw "failed to find line matching /$regex/"}
$newcontent = new-object -type "System.Collections.ArrayList"
for($i = 0; $i -lt $sln.content.length; $i++) {
if ($i -ge $proj.line -and $i -le $endi) {
continue
}
else {
$null = $newcontent.Add($sln.content[$i])
}
}
$referencingLines = @()
for($i = 0; $i -lt $newcontent.Count; $i++) {
if ($newcontent[$i] -match "$($proj.Guid)") {
$referencingLines += @{ line = $i; text = $newcontent[$i] }
}
}
for ($i = $referencingLines.length - 1; $i -ge 0; $i--) {
write-verbose "Removing referencing line $($referencingLines[$i].line): $($referencingLines[$i].text)"
$null = $newcontent.RemoveAt($referencingLines[$i].line)
}
$sln.content = @() + $newcontent
$sln.projects = get-slnprojects $sln
return
}
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/csproj-utils.ps1
|
csproj-utils.ps1
|
$script:ns = 'http://schemas.microsoft.com/developer/msbuild/2003'
$script:types = @"
using System.Xml;
public class Csproj {
public System.Xml.XmlDocument Xml {get;set;}
public string Path {get;set;}
public string FullName { get { return Path; } }
public string Name {get;set;}
public string Guid {get;set;}
public override string ToString() {
return Name;
}
public void Save() {
this.Xml.Save(this.Path);
}
public void Save(string path) {
this.Xml.Save(path);
}
public void Save(System.IO.TextWriter w) {
this.Xml.Save(w);
}
}
public class ReferenceMeta {
public System.Xml.XmlElement Node {get;set;}
public string Name {get;set;}
public string Version {get;set;}
public string ShortName {get;set;}
public string Type {get;set;}
public string Path {get;set;}
public bool? IsValid {get;set;}
public override string ToString() {
return string.Format("-> {1}{0}", ShortName, IsValid != null ? ((IsValid.Value ? "[+]" : "[-]") + " ") : "");
}
}
"@
add-type -TypeDefinition $types -ReferencedAssemblies "System.Xml"
function import-csproj {
[OutputType([Csproj])]
param([Parameter(ValueFromPipeline=$true)]$file)
$path = $null
if (test-path $file) {
$content = get-content $file
$path = (get-item $file).FullName
$name = [System.IO.Path]::GetFilenameWithoutExtension($file)
}
elseif ($file.Contains("<?xml") -or $file.Contains("<Project")) {
$content = $file
}
else {
throw "csproj file not found: '$file'"
}
try {
$xml =[xml]$content
} catch {
throw "failed to parse project '$file': $_"
}
try {
$guidNode = $xml | get-nodes -nodeName "ProjectGuid"
$guid = $guidnode.Node.InnerText
} catch {
Write-Warning $_
throw "failed to find ProjectGuid: $($_.Exception.Message)"
}
$csproj = new-object -type csproj -Property @{
xml = $xml
path = $path
name = $name
guid = $guid
}
return $csproj
}
function get-referenceName($node) {
if ($node.HasAttribute("Name")) {
return $node.GetAttribute("Name")
}
if ($node.GetElementsByTagName("Name") -ne $null) {
return $node.Name
}
if ($node.Include -ne $null) {
return $node.Include
}
}
function add-metadata {
param(
[parameter(ValueFromPipeline=$true)]$nodes,
[Csproj]$csproj
)
process {
$n = $nodes
if ($nodes.Node) { $n = $nodes.Node }
$name = get-referenceName $n
# $n.Name can be hidden by dynamic property from Name attribute/child
$type = switch($n.get_Name()) {
"ProjectReference" { "project" }
"Reference" { "dll" }
default { "?" }
}
$path = $null
#TODO: Reference node may have more than one HintPath!
if ($n.HintPath) { $path = $n.HintPath }
elseif ($n.Include) { $path = $n.Include }
if ($path -is [System.Array]) {
#hopefully, the last path will be a nuget package
$path = $path[$path.length -1]
}
$isvalid = $null
$abspath = $path
if ($abspath -ne $null `
-and (test-ispathrelative $abspath) `
-and $csproj -ne $null `
-and ![string]::IsNullOrEmpty($csproj.fullname))
{
try {
$abspath = join-path (split-path -parent $csproj.fullname) $abspath
} catch {
write-error $_.ScriptStackTrace
throw "failed to find abs path of $csproj ($($csproj.length)): $_"
}
}
if (!(test-ispathrelative $abspath)) {
$isvalid = test-path $abspath
}
return new-object -TypeName ReferenceMeta -Property @{
Node = $n
Name = $name
ShortName = get-shortname $name
Type = $type
Path = $path
IsValid = $isvalid
}
}
}
function get-nodes([Parameter(ValueFromPipeline=$true)][xml] $xml, $nodeName) {
$r = Select-Xml -Xml $xml.Project -Namespace @{ d = $ns } -XPath "//d:$nodeName"
return $r
}
function get-referencenodes([Parameter(ValueFromPipeline=$true)][xml] $xml, $nodeName, [switch][bool]$noMeta, [Csproj] $csproj) {
$r = get-nodes $xml $nodename
if (!$nometa) {
$meta = $r | add-metadata -csproj $csproj
}
return $meta
}
function get-projectreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][csproj] $csproj) {
return get-referencenodes $csproj.xml "ProjectReference" -csproj $csproj
}
function get-allexternalreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][csproj] $csproj) {
get-referencenodes $csproj.xml "Reference[d:HintPath]" -csproj $csproj
}
function get-externalreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][Csproj] $csproj) {
$refs = get-allexternalreferences $csproj
$refs = $refs | ? {
$_.Node.HintPath -notmatch "[""\\/]packages[/\\]"
}
return $refs
}
function get-nugetreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][csproj] $csproj) {
$refs = get-allexternalreferences $csproj
$refs = $refs | ? {
$_.Node.HintPath -match "[""\\/]packages[/\\]"
}
$refs = $refs | % {
$_.type = "nuget"
$_
}
return $refs
}
function get-systemreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][csproj] $csproj) {
get-referencenodes $csproj.xml "Reference[not(d:HintPath)]" -csproj $csproj
}
function get-allreferences([Parameter(ValueFromPipeline=$true, Mandatory=$true)][csproj] $csproj) {
$refs = @()
$refs += get-systemreferences $csproj
$refs += get-nugetreferences $csproj
$refs += get-externalreferences $csproj
return $refs
}
function remove-node([Parameter(ValueFromPipeline=$true)]$node) {
$node.ParentNode.RemoveChild($node)
}
function new-projectReferenceNode([System.Xml.xmldocument]$document) {
<#
<ProjectReference Include="..\xxx\xxx.csproj">
<Project>{89c414d8-0258-4a94-8e45-88b338c15e7a}</Project>
<Name>xxx</Name>
</ProjectReference>
#>
$projectRef = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "ProjectReference", $ns)
$includeAttr = [System.Xml.XmlAttribute]$document.CreateAttribute("Include")
#$nugetref = [System.Xml.XmlElement]$document.CreateElement("Reference");
$projectGuid = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "Project", $ns)
$projectName = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "Name", $ns)
$null = $projectRef.Attributes.Append($includeAttr)
$null = $projectRef.AppendChild($projectName)
$null = $projectRef.AppendChild($projectGuid)
return $projectRef
}
function new-referenceNode([System.Xml.xmldocument]$document) {
$nugetref = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "Reference", $ns)
#$nugetref = [System.Xml.XmlElement]$document.CreateElement("Reference");
$includeAttr = [System.Xml.XmlAttribute]$document.CreateAttribute("Include")
$hint = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "HintPath", $ns)
$hint.InnerText = "hint"
$null = $nugetref.Attributes.Append($includeAttr)
$null = $nugetref.AppendChild($hint)
return $nugetref
}
function add-projectItem {
[CmdletBinding()]
param ([Parameter(Mandatory=$true)] $csproj, [Parameter(Mandatory=$true)] $file)
ipmo pathutils
if ($csproj -is [string]) {
$csprojPath = $csproj
$document = (import-csproj $csprojPath).xml
}
else {
$document = $csproj.xml
}
if ($csprojPath -ne $null) {
$file = Get-RelativePath -Dir (split-path -Parent $csprojPath) $file
}
<# <ItemGroup>
<None Include="NowaEra.XPlatform.Sync.Client.nuspec">
<SubType>Designer</SubType>
</None>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
#>
$itemgroup = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "ItemGroup", $ns);
$none = [System.Xml.XmlElement]$document.CreateNode([System.Xml.XmlNodeType]::Element, "", "None", $ns);
$null = $itemgroup.AppendChild($none)
$includeAttr = [System.Xml.XmlAttribute]$document.CreateAttribute("Include");
$null = $none.Attributes.Append($includeAttr);
$none.Include = "$file"
write-verbose "adding item '$file': $($itemgroup.OuterXml)"
$other = get-nodes $document -nodeName "ItemGroup"
if ($other.Count -gt 0) {
$last = ([System.Xml.XmlNode]$other[$other.Count - 1].Node)
$null = $last.ParentNode.InsertAfter($itemgroup, $last)
} else {
$null = $document.AppendChild($itemgroup)
}
if ($csprojPath -ne $null) {
write-verbose "saving project '$csprojPath'" -verbref $VerbosePreference
$document.Save($csprojPath)
}
}
function convertto-nugetreference {
[OutputType([ReferenceMeta])]
param(
[Parameter(Mandatory=$true)]
[ReferenceMeta] $ref,
[Parameter(Mandatory=$true)]
[string ]$packagesRelPath
)
$node = get-asnode $ref
$projectPath = $node.Include
$projectId = $node.Project
$projectName = $node.Name
$nuget = find-nugetPath $projectName $packagesRelPath
$path = $nuget.Path
$version = $nuget.LatestVersion
$framework = $nuget.Framework
if ($path -eq $null) {
throw "package '$projectName' not found in packages dir '$packagesRelPath'"
}
$nugetref = new-referenceNode $node.OwnerDocument
$nugetref.Include = $projectName
$hintNode = $nugetref.ChildNodes | ? { $_.Name -eq "HintPath" }
$hintNode.InnerText = $path
#$nugetref.hintpath = $path
$meta = $nugetref | add-metadata
$meta.Version = $version
return $meta
}
function convertto-projectreference {
[OutputType([ReferenceMeta])]
param(
[Parameter(Mandatory=$true)]
[ReferenceMeta] $ref,
[Parameter(Mandatory=$true)]
[string ]$targetProject
)
$node = get-asnode $ref
<#
<ProjectReference Include="..\xxx\xxx.csproj">
<Project>{89c414d8-0258-4a94-8e45-88b338c15e7a}</Project>
<Name>xxx</Name>
</ProjectReference>
#>
# TODO: handle relative path
$targetcsproj = import-csproj $targetProject
$guidNode = $targetcsproj.xml | get-nodes -nodeName "ProjectGuid"
$guid = $guidnode.Node.InnerText
$projectRef = new-projectReferenceNode $node.OwnerDocument
$projectRef.Include = $targetProject
$projectRef.Name = [System.IO.Path]::GetFilenameWithoutExtension($targetProject)
$projectRef.Project = $guid
$meta = $projectRef | add-metadata
return $meta
}
function convert-reference {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][csproj] $csproj,
[Parameter(Mandatory=$true)][referenceMeta] $originalref,
[Parameter(Mandatory=$true)][referenceMeta] $newref
)
#$originalref = $originalref | get-asnode
#$newref = $newref | get-asnode
$null = $originalref.Node.parentNode.AppendChild($newref.Node)
$null = $originalref.Node.parentNode.RemoveChild($originalref.Node)
write-verbose "replacing:"
write-verbose "`r`n$($originalref.Node.OuterXml)"
write-verbose "with:"
write-verbose "`r`n$($newref.Node.OuterXml)"
if ($csproj.path -ne $null -and $newref.Type -ne "project") {
$dir = split-path -Parent $csproj.path
$pkgs = get-packagesconfig (Join-Path $dir "packages.config") -createifnotexists
add-packagetoconfig -packagesconfig $pkgs -package $newref.Name -version $newref.Version -ifnotexists
#make sure paths are relative
$newref.Node.HintPath = (Get-RelativePath $dir $newref.Node.HintPath)
$pkgs.xml.Save( (Join-Path $dir "packages.config") )
}
else {
write-warning "passed csproj path==null. Cannot edit packages.config"
}
}
function get-asnode {
param([Parameter(Mandatory=$true, ValueFromPipeline=$true)]$ref)
if ($ref -is [System.Xml.XmlNode]) {return $ref }
elseif ($ref.Node -ne $null) { return $ref.Node }
else { throw "$ref is not a node and has no 'Node' property"}
}
function get-project($name, [switch][bool]$all) {
$projs = gci -Filter "*.csproj"
if ($name -ne $null) {
$projs = $projs | ? { $_.Name -eq "$name.csproj" }
}
$projs = $projs | % {
new-object -type pscustomobject -Property @{
FullName = $_.FullName
File = $_
Name = $_.Name
}
}
return $projs
}
new-alias replace-reference convert-reference
new-alias convertto-nuget convertto-nugetreference
|
PowerShellCorpus/PowerShellGallery/csproj/1.0.23.304/functions/nuget-utils.ps1
|
nuget-utils.ps1
|
function get-shortName($package) {
$m = $package -match "(?<shortname>.*?)(,(?<specificversion>.+)){0,1}$"
return $Matches["shortname"]
}
<# this is duplicated from nupkg module #>
function find-packagesdir {
[CmdletBinding()]
param ($path, [switch][bool]$all)
if ($path -eq $null) {
$path = "."
}
$result = @()
if (!(get-item $path).PsIsContainer) {
$dir = split-path -Parent (get-item $path).fullname
}
else {
$dir = (get-item $path).fullname
}
while(![string]::IsNullOrEmpty($dir)) {
if (test-path "$dir/nuget.config") {
$nugetcfg = [xml](get-content "$dir/nuget.config" | out-string)
write-verbose "found nuget.config in dir $dir"
$node = ($nugetcfg | select-xml -XPath "//configuration/config/add[@key='repositoryPath']")
if ($node -ne $null) {
$packagesdir = $node.node.value
if ([System.IO.Path]::IsPathRooted($packagesdir)) {
$result += @($packagesdir)
if (!$all) { return $result }
}
else {
$result += @((get-item (join-path $dir $packagesdir)).fullname)
if (!$all) { return $result}
}
}
}
if ((test-path "$dir/packages") -or (Test-Path "$dir/packages")) {
write-verbose "found 'packages' in dir $dir"
$result += @("$dir/packages")
if (!$all) { return $result }
}
if ((test-path "$dir/dnx-packages") -or (Test-Path "$dir/dnx-packages")) {
write-verbose "found 'dnx-packages' in dir $dir"
$result += @("$dir/dnx-packages")
if (!$all) { return $result }
}
$dir = split-path -Parent $dir
if ($result.Count -gt 0) { return $result }
}
return $null
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/APUtil.ps1
|
APUtil.ps1
|
$APAdapterParameters = @{
"Server" = "APPlusServer";
"Port" = "APPlusPort";
"WebServer" = "APPlusWebServer";
"WebPort" = "APPlusWebPort";
"WebSite" = "APPlusWebSite";
"WebServiceUrl" = "APPlusWebServiceUrl";
"WebServiceLogon" = "APPlusWebServiceLogOn";
"WebServicePassword" = "APPlusWebServicePassword";
"AuthorizationWebServiceUrl" = "APPlusAuthorizationWebServiceUrl";
"BulkFilePath" = "BulkFilePath";
"CalendarDelta" = "CalendarDelta";
"DefaultTransferMode" = "DefaultTransferMode";
"EntityCountToSwitchBatchMode" = "EntityCountToSwitchBatchMode";
"IdleTimeOnCapacityChange" = "IdleTimeOnCapacityChange";
"MaterialFixStartDateInTasks" = "MaterialFixStartDateInTasks";
}
$APAdapterParametersType = @{
"Server" = "string";
"Port" = "int";
"WebServer" = "string";
"WebPort" = "int";
"WebSite" = "string";
"WebServiceUrl" = "string";
"WebServiceLogon" = "string";
"WebServicePassword" = "string";
"AuthorizationWebServiceUrl" = "string";
"BulkFilePath" = "string";
"CalendarDelta" = "int";
"terialFixStartDateInTasks DefaultTransferMode" = "string";
"EntityCountToSwitchBatchMode" = "int";
"IdleTimeOnCapacityChange" = "bool";
"MaterialFixStartDateInTasks" = "bool";
}
function Set-APParameters(
[string]$Tenant,
[string]$Server,
[int]$Port,
[string]$Login,
[string]$Password,
[string]$WebServer,
[int]$WebPort,
[string]$WebSite,
[string] $BulkPath) {
if ($Server -eq "") {
$Server = $Env:COMPUTERNAME
}
if ($Port -eq 0) {
$Port = 2039
}
if ($WebPort -eq 0) {
$WebPort = 80
}
if ($WebServer -eq "") {
$WebServer = $Env:COMPUTERNAME
}
$webServiceUrl = 'http://' + $Server + ':' + $Port + "/ortems/MinimalPlanningDataService.jws"
$entityCountSwitch = 50;
$calendarDelta = 20;
$transfertMode = "WebService";
$webAuthorization = "/Core/Authorization.asmx"
$configuration = @{
UId = [System.Guid]::NewGuid();
Version = 0;
APPlusServer = $Server;
APPlusPort = $Port;
APPlusWebServer = $WebServer;
APPlusWebPort = $WebPort;
APPLusWebSite = $WebSite;
APPlusWebServiceUrl = $webServiceUrl;
APPlusWebServiceLogOn = $Login;
APPlusWebServicePassword = $Password;
APPlusAuthorizationWebServiceUrl = $webAuthorization;
BulkFilePath = $BulkPath;
CalendarDelta = $calendarDelta;
EntityCountToSwitchBatchMode = $entityCountSwitch;
DefaultTransfertMode = $transfertMode;
LastModificationDate = [System.DateTime]::UtcNow;
}
Write-APParameters $Tenant $configuration
}
function Write-APParameters($Tenant,$configuration) {
$data = $configuration | ConvertTo-Json
$storePath = Get-APConfigurationPath $Tenant
[System.IO.File]::WriteAllText($storePath, $data)
Write-Verbose "AP configuration stored in $storePath"
}
function Get-APConfigurationPath($Tenant) {
return Get-ConfigurationPath $Tenant "AP.json"
}
function Set-APAdapterParameter([string] $Tenant, [string] $Name, [string] $Value) {
$storePath = Get-APConfigurationPath $Tenant
$parameters = Get-AdapterParameters $Tenant $storePath
if ($parameters -eq $null) {
$parameters = New-APAdapterParameters $Tenant $storePath
}
if ($parameters -eq $null) {
Write-Warning "Cannot create or get AP parameters for tenant $Tenant"
return
}
Set-AdapterParameter $Name $Value $parameters $APAdapterParameters $APAdapterParametersType "AP"
Write-APParameters $Tenant $parameters
Write-Verbose "Parameter set"
}
function New-APAdapterParameters([string] $Tenant, $StorePath) {
if (!(Test-Path $StorePath)) {
Set-APParameters
}
return Get-AdapterParameters $Tenant $StorePath
}
function Write-APValidParameters {
Write-ValidParameters "AP" $APAdapterParameters
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/ServiceUtil.ps1
|
ServiceUtil.ps1
|
# Determines if a Service exists with a name as defined in $ServiceName.
# Returns a boolean $True or $False.
Function Test-ServiceExists([string] $ServiceName) {
[bool] $Return = $False
if ( Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'" ) {
$Return = $True
}
Return $Return
}
# Deletes a Service with a name as defined in $ServiceName.
# Returns a boolean $True or $False. $True if the Service didn't exist or was
# successfully deleted after execution.
Function Remove-Service([string] $ServiceName) {
[bool] $Return = $False
$Service = Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'"
if ( $Service ) {
Remove-CimInstance -InputObject $Service
if ( -Not ( Test-ServiceExists $ServiceName ) ) {
$Return = $True
}
} else {
$Return = $True
}
Return $Return
}
function Get-PlanningVersion($version) {
$vstr = "NA | NA | NA"
if ($version -ne $null)
{
$V = $version.Version
$S = $version.StaticDataVersion
$D = $version.DynamicDataVersion
$vstr = "$V | $S | $D"
}
return $vstr
}
function Get-PlanningVersionWeb($version) {
$vstr = "NA`t| NA`t| NA"
if ($version -ne $null)
{
$V = $version.Planning
$S = $version.Static
$D = $version.Dynamic
$vstr = "$V`t| $S`t| $D"
}
return $vstr
}
function Stop-ServiceAndProcess([string] $ServiceName) {
Write-Verbose "Looking for service $ServiceName"
$id = Get-WmiObject Win32_Service -Filter "Name LIKE '$ServiceName'" | Select-Object -expand ProcessId
if ($id -ne 0) {
Write-Verbose "Found service with process ID: $id"
Stop-Service -Name $ServiceName -Force
Write-Verbose "Wait for complete stop."
Start-Sleep -s 10
if (Get-Process -Id $id -ErrorAction SilentlyContinue) {
Stop-Process -Id $id -Force -Confirm:$false
Write-Warning "Process has been stopped (forced)."
} else {
Write-Verbose "Service stopped normaly."
}
} else {
Write-Verbose "No service found for the given instance."
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/RegistryUtil.ps1
|
RegistryUtil.ps1
|
function Uninstall-registryKey($Key) {
msiexec /x $Key /quiet
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/ContextUtil.ps1
|
ContextUtil.ps1
|
function Write-Context() {
if (!$NavVersionCode) {
Write-Warning "Context doesn't exist! It can't be written."
return
}
$P1context = @{
NavVersionCode = $NavVersionCode
NavVersion = $NavVersion
NavInstance = $NavInstance
NavDatabase = $NavDatabase
}
$data = $P1context | ConvertTo-Json
if (!(Test-Path -Path $ContextStorePath)) {
New-Item -Path $ContextStorePath
}
[System.IO.File]::WriteAllText($ContextStorePath, $data)
Write-Verbose "Context registered in $ContextStorePath"
}
function Read-Context() {
Write-Verbose "Reading context from $ContextStorePath"
if (!(Test-Path -Path $ContextStorePath)) {
Write-Warning "Context file doesn't exist! It can't be read."
return
}
$data = [System.IO.File]::ReadAllText($ContextStorePath)
$P1context = $data | ConvertFrom-Json
Write-Output "Curent context has the following values:"
Write-Output "- NavVersionCode = $NavVersionCode"
Write-Output "- NavVersion = $NavVersion"
Write-Output "- NavInstance = $NavInstance"
Write-Output "- NavDatabase = $NavDatabase"
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/RESTUtil.ps1
|
RESTUtil.ps1
|
$RESTAdapterParameters = @{
"Server" = "Server";
"RESTPort" = "Port";
"AuthenticationMode" = "AuthenticationMode";
"SSL" = "SSL";
"Instance" = "InstanceName";
"ServiceAccountDomain" = "ServiceDomain";
"ServiceAccountLogin" = "ServiceLogin";
"ServiceAccountPassword" = "UnencryptedServicePassword";
"SynchronizationTick" = "SynchronizationTimerStep";
"MapOperationOnIgnoreResources" = "MapOperationOnIgnoreResourcesPS";
"Tenant" = "TenantName";
"WebServer" = "WebServerName";
"WebPort" = "WebSitePort";
"DefaultCulture" = "DefaultCultureCode";
"UntrustedCARoot" = "AcceptUntrustedRoot";
"ClientCertificatePath" = "ClientCertificatePath";
"ClientCertificatePassword" = "UnencryptedClientCertificateKeyPassword";
"ServerCAPath" = "ServerCertificateAuthorityPath";
}
$RESTAdapterParametersType = @{
"Server" = "string";
"RESTPort" = "int";
"AuthenticationMode" = "string";
"SSL" = "bool";
"Instance" = "string";
"ServiceAccountDomain" = "string";
"ServiceAccountLogin" = "string";
"ServiceAccountPassword" = "string";
"SynchronizationTick" = "int";
"MapOperationOnIgnoreResources" = "bool";
"Tenant" = "string";
"WebServer" = "string";
"WebPort" = "string";
"DefaultCulture" = "string";
"UntrustedCARoot" = "bool";
"ClientCertificatePath" = "string";
"ClientCertificatePassword" = "string";
"ServerCAPath" = "string";
}
function Set-RESTParameters(
[string]$Tenant,
[string]$Server,
[int]$SOAPPort,
[string]$AuthenticationMode,
[bool]$SSL,
[string]$InstanceName,
[string]$Domain,
[string]$Login,
[string]$Password,
[string]$TenantName) {
if ($Server -eq "") {
$Server = $Env:COMPUTERNAME
}
if ($SOAPPort -eq 0) {
$SOAPPort = 7047
}
if ($AuthenticationMode -eq "") {
$AuthenticationMode = "Negotiate"
if ($Domain -eq "") {
$Domain = $Env:COMPUTERNAME
}
}
if ($ClientPort -eq 0) {
$ClientPort = -1;
}
$configuration = @{
UId = [System.Guid]::NewGuid();
Version = 0;
Server = $Server;
Port = $SOAPPort;
AuthenticationMode = $AuthenticationMode;
SSL = $SSL;
InstanceName = $InstanceName;
ServiceDomain = $Domain;
ServiceLogin = $Login;
UnencryptedServicePassword = $Password;
SynchronizerTimerStep = 3000;
MapOperationsOnIgnoredResourcesPS = $true;
KeepAlive = $true;
RetryInitRatio = 5;
TenantName = $TenantName;
WebServerName = "";
WebSitePort = 8080;
LastModificationDate = [System.DateTime]::UtcNow;
}
Write-RESTParameters $Tenant $configuration
}
function Write-RESTParameters($Tenant,$configuration) {
$data = $configuration | ConvertTo-Json
$storePath = Get-RESTConfigurationPath $Tenant
[System.IO.File]::WriteAllText($storePath, $data)
Write-Verbose "REST configuration stored in $storePath"
}
function Get-RESTConfigurationPath($Tenant) {
return Get-ConfigurationPath $Tenant "REST.json"
}
function Set-RESTAdapterParameter([string] $Tenant, [string] $Name, [string] $Value) {
$storePath = Get-RESTConfigurationPath $Tenant
$parameters = Get-AdapterParameters $Tenant $storePath
if ($parameters -eq $null) {
$parameters = New-RESTAdapterParameters $Tenant $storePath
}
if ($parameters -eq $null) {
Write-Warning "Cannot create or get REST parameters for tenant $Tenant"
return
}
Set-AdapterParameter $Name $Value $parameters $RESTAdapterParameters $RESTAdapterParametersType "REST"
Write-RESTParameters $Tenant $parameters
Write-Verbose "Parameter set"
}
function New-RESTAdapterParameters([string] $Tenant, $StorePath) {
if (!(Test-Path $StorePath)) {
Set-RESTParameters
}
return Get-AdapterParameters $Tenant $StorePath
}
function Write-RESTValidParameters {
Write-ValidParameters "REST" $RESTAdapterParameters
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/FileUtil.ps1
|
FileUtil.ps1
|
# Unzip file
function Expand-ZIPFile($file, $destination) {
$shell = new-object -com shell.application
$zip = $shell.NameSpace($file)
foreach($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
function Get-PackageFolder($packageName) {
$packageSrc = (Get-Package $packageName).Source
$position = $PackageSrc.LastIndexOf("\")
return $packageSrc.Substring(0, $position)
}
function Get-PackageFolderForVersion($packageName, $packageVersion) {
$packageSrc = (Get-Package -Name $packageName -RequiredVersion $packageVersion).Source
$position = $PackageSrc.LastIndexOf("\")
return $packageSrc.Substring(0, $position)
}
function Get-PackageName($packageBase, $Adapter) {
$name = $packageBase.replace('[Adapter]', $Adapter)
return $name
}
function Get-version($packageBase, $Version) {
$name = $packageBase.replace('[Version]', $Version)
return $name
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/test.ps1
|
test.ps1
|
<#
Import-Module servermanager
$featureNames = ('Web-Server', 'Web-Mgmt-Console', 'Web-Request-Monitor', 'Web-Windows-Auth', 'Web-Asp-Net45', 'Web-Net-Ext45', 'Web-ISAPI-Filter', 'Web-ISAPI-Ext', 'NET-WCF-HTTP-Activation45', 'NET-Framework-45-ASPNET')
$features = Get-WindowsFeature $featureNames
Write-Host "Not Installed"
$features | Where-Object InstallState -ne Installed
Write-Host "Installed"
$features | Where-Object InstallState -eq Installed
#>
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/LinkUtil.ps1
|
LinkUtil.ps1
|
function Resolve-PathForced {
<#
.SYNOPSIS
Calls Resolve-Path but works for files that don't exist.
.REMARKS
From http://devhawk.net/2010/01/21/fixing-powershells-busted-resolve-path-cmdlet/
#>
param (
[string] $FileName
)
$FileName = Resolve-Path $FileName -ErrorAction SilentlyContinue `
-ErrorVariable _frperror
if (-not($FileName)) {
$FileName = $_frperror[0].TargetObject
}
return $FileName
}
function Remove-Symlink {
<#
.SYNOPSIS
Removes a symbolic link.
#>
param (
[Parameter(Position=0, Mandatory=$true)]
[string] $Link
)
# Remove-Item cannot be used to remove symbolic link to directory as it
# will remove the content of the directory it points to.
[System.IO.Directory]::Delete($Link, $true)
}
function New-Symlink {
<#
.SYNOPSIS
Creates a symbolic link.
#>
param (
[Parameter(Position=0, Mandatory=$true)]
[string] $Link,
[Parameter(Position=1, Mandatory=$true)]
[string] $Target,
[Parameter(Position=2)]
[switch] $Force
)
Invoke-MKLINK -Link $Link -Target $Target -Symlink -Force $Force
}
function New-Hardlink {
<#
.SYNOPSIS
Creates a hard link.
#>
param (
[Parameter(Position=0, Mandatory=$true)]
[string] $Link,
[Parameter(Position=1, Mandatory=$true)]
[string] $Target,
[Parameter(Position=2)]
[switch] $Force
)
Invoke-MKLINK -Link $Link -Target $Target -HardLink -Force $Force
}
function New-Junction {
<#
.SYNOPSIS
Creates a directory junction.
#>
param (
[Parameter(Position=0, Mandatory=$true)]
[string] $Link,
[Parameter(Position=1, Mandatory=$true)]
[string] $Target,
[Parameter(Position=2)]
[switch] $Force
)
Invoke-MKLINK -Link $Link -Target $Target -Junction -Force $Force
}
function Invoke-MKLINK {
<#
.SYNOPSIS
Creates a symbolic link, hard link, or directory junction.
#>
[CmdletBinding(DefaultParameterSetName = "Symlink")]
param (
[Parameter(Position=0, Mandatory=$true)]
[string] $Link,
[Parameter(Position=1, Mandatory=$true)]
[string] $Target,
[Parameter(ParameterSetName = "Symlink")]
[switch] $Symlink = $true,
[Parameter(ParameterSetName = "HardLink")]
[switch] $HardLink,
[Parameter(ParameterSetName = "Junction")]
[switch] $Junction,
[Parameter()]
[bool] $Force
)
# Resolve the paths incase a relative path was passed in.
$Link = (Resolve-PathForced $Link)
$Target = (Resolve-PathForced $Target)
# Ensure target exists.
if (-not(Test-Path $Target)) {
throw "Target does not exist.`nTarget: $Target"
}
# Ensure link does not exist.
if (Test-Path $Link) {
if ($Force) {
Remove-Item $Link -Recurse -Force
}
else {
throw "A file or directory already exists at the link path.`nLink: $Link"
}
}
$isDirectory = (Get-Item $Target).PSIsContainer
$mklinkArg = ""
if ($Symlink -and $isDirectory) {
$mkLinkArg = "/D"
}
if ($Junction) {
# Ensure we are linking a directory. (Junctions don't work for files.)
if (-not($isDirectory)) {
throw "The target is a file. Junctions cannot be created for files.`nTarget: $Target"
}
$mklinkArg = "/J"
}
if ($HardLink) {
# Ensure we are linking a file. (Hard links don't work for directories.)
if ($isDirectory) {
throw "The target is a directory. Hard links cannot be created for directories.`nTarget: $Target"
}
$mkLinkArg = "/H"
}
# Capture the MKLINK output so we can return it properly.
# Includes a redirect of STDERR to STDOUT so we can capture it as well.
$output = cmd /c mklink $mkLinkArg `"$Link`" `"$Target`" 2>&1
if ($lastExitCode -ne 0) {
throw "MKLINK failed. Exit code: $lastExitCode`n$output"
}
else {
Write-Verbose $output
}
}
function mklink {
<#
.SYNOPSIS
Helper function for calling mklink directly.
All arguments are piped through to mklink.
Hat tip to http://stackoverflow.com/questions/894430/powershell-hard-and-soft-links#comment9823010_5549583
#>
cmd /c mklink $args
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/LogUtil.ps1
|
LogUtil.ps1
|
$LogLevels = ("ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "OFF")
$logConfDir = "Logs\"
$logConfFile = "loglevel"
$log4NetFile = "Log4Net.config"
function Test-LogLevel([string] $Level) {
[bool]$found = $false
foreach($logLevel in $LogLevels) {
if ($Level -eq $logLevel) {
$found = $true
break
}
}
return $found
}
function Write-LogLevels() {
Write-Output "Available levels:"
Write-Output $LogLevels
}
function Get-LogConfigDirFromTenant([string]$Tenant) {
$configPath = Get-ConfigPathFromTenant $Tenant
$logConfPath = $configPath + $logConfDir
return $logConfPath
}
function Get-LogConfigPathFromTenant([string]$Tenant) {
$configDir = Get-LogConfigDirFromTenant $Tenant
$logConfPath = $configDir + $logConfFile
Write-Verbose "Log configuration path is $logConfPath"
return $logConfPath
}
function Read-LogLevel([string]$Tenant) {
$path = Get-LogConfigPathFromTenant $Tenant
if (!(Test-Path $path)) {
Write-Verbose "File $path does not exist. Returning default log level"
return "INFO"
}
$level = Get-Content $path
return $level
}
function Write-LogLevel([string]$Tenant, [string]$Level) {
$path = Get-LogConfigPathFromTenant $Tenant
$dir = Get-LogConfigDirFromTenant $Tenant
if (!(Test-Path $dir)) {
Write-Verbose "Creating dir $dir"
mkdir $dir | Out-Null
}
$path = Get-LogConfigPathFromTenant $Tenant
Write-Verbose "Writing $Level to $path"
Set-Content $path $Level
}
function Get-Log4NetPath($dirPath) {
$path = $dirPath + "\" + $log4NetFile
return $path
}
function Write-Log4NetWeb([string]$dirPath, [string]$Level) {
$path = Get-Log4NetPath $dirPath
Write-Verbose "Reading $path"
[xml]$config = Get-Content $path
Write-Verbose "Setting root level to $Level"
$config.configuration.log4net.root.level.value = "$Level"
Write-Verbose "Saving Log4Net xml configuration"
$config.save($path)
}
function Write-Log4NetService([string]$dirPath, [string]$Level) {
$confServiceDirPath = $dirPath + "\Conf\Service"
$path = Get-Log4NetPath $confServiceDirPath
Write-Verbose "Reading $path"
[xml]$config = Get-Content $path
Write-Verbose "Setting root level to $Level"
$config.configuration.log4net.appender[0].threshold.value = "$Level"
Write-Verbose "Saving Log4Net xml configuration"
$config.save($path)
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/NavUtil.ps1
|
NavUtil.ps1
|
$NAVAdapterParameters = @{
"Server" = "Server";
"SOAPPort" = "Port";
"AuthenticationMode" = "AuthenticationMode";
"SSL" = "SSL";
"RTCPort" = "ClientPort"
"Instance" = "InstanceName";
"ServiceAccountDomain" = "ServiceDomain";
"ServiceAccountLogin" = "ServiceLogin";
"ServiceAccountPassword" = "UnencryptedServicePassword";
"SendBatchSize" = "SenderBatchSize";
"SynchronizationTick" = "SynchronizationTimerStep";
"MapOperationOnIgnoreResources" = "MapOperationOnIgnoreResourcesPS";
"MapReservations" = "MapReservations";
"KeepAlive" = "KeepAlive";
"Tenant" = "TenantName";
"WebServer" = "WebServerName";
"WebPort" = "WebSitePort";
}
$NAVAdapterParametersType = @{
"Server" = "string";
"SOAPPort" = "int";
"AuthenticationMode" = "string";
"SSL" = "bool";
"RTCPort" = "int"
"Instance" = "string";
"ServiceAccountDomain" = "string";
"ServiceAccountLogin" = "string";
"ServiceAccountPassword" = "string";
"SendBatchSize" = "int";
"SynchronizationTick" = "int";
"MapOperationOnIgnoreResources" = "bool";
"MapReservations" = "bool";
"KeepAlive" = "bool";
"Tenant" = "string";
"WebServer" = "string";
"WebPort" = "string";
}
function Set-NAVParameters(
[string]$Tenant,
[string]$Server,
[int]$SOAPPort,
[string]$AuthenticationMode,
[bool]$SSL,
[int]$ClientPort,
[string]$InstanceName,
[string]$Domain,
[string]$Login,
[string]$Password,
[string]$TenantName) {
if ($Server -eq "") {
$Server = $Env:COMPUTERNAME
}
if ($SOAPPort -eq 0) {
$SOAPPort = 7047
}
if ($AuthenticationMode -eq "") {
$AuthenticationMode = "Negotiate"
if ($Domain -eq "") {
$Domain = $Env:COMPUTERNAME
}
}
if ($ClientPort -eq 0) {
$ClientPort = -1;
}
$configuration = @{
UId = [System.Guid]::NewGuid();
Version = 0;
Server = $Server;
Port = $SOAPPort;
Digest = $false;
AuthenticationMode = $AuthenticationMode;
SSL = $SSL;
ClientPort = $ClientPort;
InstanceName = $InstanceName;
ServiceDomain = $Domain;
ServiceLogin = $Login;
UnencryptedServicePassword = $Password;
SenderBatchSize = 50;
SynchronizerTimerStep = 3000;
MapOperationsOnIgnoredResourcesPS = $true;
MapReservationsPS = $true;
KeepAlive = $true;
RetryInitRatio = 5;
TenantName = $TenantName;
WebServerName = "";
WebSitePort = 8080;
MigratedV5 = $false;
LastModificationDate = [System.DateTime]::UtcNow;
}
Write-NavParameters $Tenant $configuration
}
function Write-NavParameters($Tenant,$configuration) {
$data = $configuration | ConvertTo-Json
$storePath = Get-NAVConfigurationPath $Tenant
[System.IO.File]::WriteAllText($storePath, $data)
Write-Verbose "NAV configuration stored in $storePath"
}
function Get-NAVConfigurationPath($Tenant) {
return Get-ConfigurationPath $Tenant "NAV.json"
}
function Get-NAVParametersFromConfig($InstanceName,[switch]$DefaultInstance,$NAVVersion) {
$path = "$env:ProgramFiles\Microsoft Dynamics NAV"
if ($NAVVersion -ne "") {
$path += "\$NAVVersion\Service"
}
Write-Verbose "Searching for psm1 modules in $path"
$mod = (Get-ChildItem -Path $path -Filter '*.psm1' -Recurse).FullName
if ($null -eq $mod) {
Write-Warning "No Microsoft Dynamics NAV Powershell module found in $path"
return
}
Import-Module $mod
if ($DefaultInstance) {
$instance = Get-NAVServerInstance | Where-Object Default
} else {
$instance = Get-NAVServerInstance -ServerInstance $InstanceName
}
if ($null -eq $instance) {
Write-Warning "Microsoft Dynamics NAV instance not found with provided parameter."
return
}
$xmlConfig = $instance | Get-NAVServerConfiguration -AsXml
if ($null -eq $xmlConfig) {
Write-Warning "Microsoft Dynamics NAV server configuration does not exist or cannot be read."
return
}
$values = $xmlConfig.configuration.appSettings.add
<#InstanceName needed by PlannerOne can differ from the function parameter one if full service instance name has been provided as parameter"#>
$ServerInstance = ($values | Where-Object key -eq 'ServerInstance').value
Write-Verbose "Server Instance: $ServerInstance"
$SOAPServicesPort = ($values | Where-Object key -eq 'SOAPServicesPort').value
Write-Verbose "SOAP Port: $SOAPServicesPort"
$ClientServicesPort = ($values | Where-Object key -eq 'ClientServicesPort').value
Write-Verbose "Client Port: $ClientServicesPort"
$SOAPServicesEnabled = ($values | Where-Object key -eq 'SOAPServicesEnabled').value
Write-Verbose "SOAPServicesEnabled: $SOAPServicesEnabled"
$ServicesDefaultTimeZone = ($values | Where-Object key -eq 'ServicesDefaultTimeZone').value
Write-Verbose "ServicesDefaultTimeZone: $ServicesDefaultTimeZone"
$instanceConfig = @{
InstanceName = $ServerInstance;
SOAPPort = $SOAPServicesPort;
ClientPort = $ClientServicesPort;;
SOAPServicesEnabled = $SOAPServicesEnabled;
ServicesDefaultTimeZone = $ServicesDefaultTimeZone
}
return $instanceConfig
}
function Test-DBConfig($Role) {
$dbConfig = Get-LegacyDatabaseConfig $Role
if ($null -eq $dbConfig) {
return $false
}
return $true
}
function Test-DBConnection($Role) {
$dbConfig = Get-LegacyDatabaseConfig $Role
if ($null -eq $dbConfig) {
return $false
}
$connectionString = Get-ConnectionString -Server $dbConfig.Server -Database $dbConfig.Database -IntegratedSecurity "true"
Write-Verbose "Connection string: $connectionString"
try {
Get-DatabaseData -connectionString $connectionString -query "select 1" -isSQLServer
} catch {
Write-Warning "Cannot connect to database with connection string $connectionString"
return $false
}
Write-Verbose "Database connection OK"
return $true
}
function Migrate-Configuration($Role) {
$dbConfig = Get-LegacyDatabaseConfig $Role
if ($null -eq $dbConfig) {
return
}
$connectionString = Get-ConnectionString -Server $dbConfig.Server -Database $dbConfig.Database -IntegratedSecurity "true"
Write-Verbose "Connection string: $connectionString"
Migrate-Adapter $Role $connectionString
Migrate-UIParameter $Role $connectionString
Migrate-Criteria $Role $connectionString
}
function Migrate-UIParameter($Role,$connectionString) {
try {
$data = Get-DatabaseData -connectionString $connectionString -query "select * from dbo.UIParameters" -isSQLServer
} catch {
Write-Verbose "No ui parameters to migrate."
return
}
Write-Verbose "Migrating UI parameters..."
if ($null -eq $data) {
Write-Verbose "No ui parameters to migrate."
return
}
$src = $data[1]
if ($null -eq $src.UId) {
Write-Verbose "No ui parameters to migrate."
return
}
$parameters = @{
UId = $src.UId;
Version = $src.Version;
AdvanceDelayColorThresholdDuration = $src.AdvanceDelayColorThresholdDuration;
ProjectLinksDisplayThreshold = $src.ProjectLinksDisplayThreshold;
LastModificationDate = $src.LastModificationDate;
}
$storePath = Get-UIParamPathFromTenant $Role
if (!(Test-Path $storePath)) {
md $storePath | Out-Null
}
$storePath = $storePath + "parameters.json"
$json = $parameters | ConvertTo-Json
$json | Out-File $storePath
Write-Verbose "UI parameters stored in $storePath"
}
function Migrate-Adapter($Role,$connectionString) {
try {
$data = Get-DatabaseData -connectionString $connectionString -query "select * from dbo.NavConfiguration" -isSQLServer
} catch {
Write-Verbose "No adapter configuration to migrate."
return
}
Write-Verbose "Migrating adapter configuration..."
if ($null -eq $data) {
Write-Verbose "No adapter configuration to migrate."
return
}
$src = $data[1]
if ($null -eq $src.UId) {
Write-Verbose "No adapter configuration to migrate."
return
}
# Some PlannerOne version does not contains some boolean parameters
# Set default value to False instead of null if the data is not found
$migratedV5 = Get-Bool $src.MigratedV5
$ntlm = Get-Bool $src.NTLM
$digest = Get-Bool $src.Digest
$ssl = Get-Bool $src.SSL
$ignoredResource = Get-Bool $src.MapOperationsOnIgnoredResourcesPS
$mapReservation = Get-Bool $src.MapReservationsPS
$keepAlive = Get-Bool $src.KeepAlive
$port = Get-Int $src.Port 7047
$clientPort = Get-Int $src.ClientPort -1
$senderBatchSize = Get-Int $src.SenderBatchSize 50
$synchroStep = Get-Int $src.SynchronizerTimerStep 3000
$retryInit = Get-Int $src.RetryInitRatio 5
$webPort = Get-Int $src.WebSitePort 8080
$navConfiguration = @{
UId = $src.UId;
Version = $src.Version;
Server = $src.Server;
Port = $port;
NTLM = $ntlm;
Digest = $digest;
AuthenticationMode = $src.AuthenticationMode;
SSL = $ssl;
ClientPort = $clientPort;
InstanceName = $src.WebRoot;
ServiceDomain = $src.ServiceDomain;
ServiceLogin = $src.ServiceLogin;
ServicePassword = $src.ServicePassword;
SenderBatchSize = $senderBatchSize;
SynchronizerTimerStep = $synchroStep;
MapOperationsOnIgnoredResourcesPS = $ignoredResource;
MapReservationsPS = $mapReservation;
KeepAlive = $keepAlive;
RetryInitRatio = $retryInit;
TenantName = $src.TenantName;
WebServerName = $src.WebServerName;
WebSitePort = $webPort;
MigratedV5 = $migratedV5;
LastModificationDate = $src.LastModificationDate;
}
Write-NavParameters $Role $navConfiguration
Write-Verbose "Migration done"
}
function Get-Bool($value) {
if ($value -eq $null) {
return $false
} else {
return $value
}
}
function Get-Int($value, $default) {
if ($value -eq $null) {
return $default
} else {
return $value
}
}
function Migrate-Criteria($Role,$connectionString) {
Migrate-TypedCriteria $Role $connectionString "Placement"
Migrate-TypedCriteria $Role $connectionString "Task"
}
function Migrate-TypedCriteria($Role,$connectionString, $CriteriaType) {
$query = "select * from dbo.CombinedCriterionConfiguration where CombinedType='$CriteriaType'"
try {
$data = Get-DatabaseData -connectionString $connectionString -query $query -isSQLServer
} catch {
Write-Verbose "No $CriteriaType criteria to migrate."
return
}
Write-Verbose "Migrating criteria..."
if ($null -eq $data) {
Write-Verbose "No $CriteriaType criteria to migrate."
return
}
$TypeInt = 0
$ChoiceStrategy = "SC_FilteringChoiceStrategy"
if ($CriteriaType -eq "Placement") {
$TypeInt = 1
$ChoiceStrategy = "PC_FilteringChoiceStrategy"
}
$src = $data[1]
if ($null -eq $src.UId) {
Write-Verbose "No $CriteriaType criteria to migrate."
return
}
$Usages = Get-CriterionUsages $connectionString $src.UId
$Strategy = @{
UId = [System.Guid]::NewGuid();
Name = $ChoiceStrategy;
}
$parameters = @{
UId = $src.UId;
Version = $src.Version;
CombinedType = $TypeInt;
Name = $src.Name;
ChoiceStrategy = $Strategy;
CriterionUsageConfiguration = $Usages;
}
$storePath = Get-CriteriaPathFromTenant $Role
if (!(Test-Path $storePath)) {
md $storePath | Out-Null
}
$storePath = $storePath + "CombinedCriterion$CriteriaType.json"
$json = $parameters | ConvertTo-Json
$json | Out-File $storePath
Write-Verbose "Criteria stored in $storePath"
}
function Get-CriterionUsages($connectionString, $CriterionUId) {
$query = "select * from dbo.CriterionUsageConfiguration where CombinedCriterionConfiguration_UId='$CriterionUId'"
Write-Verbose $query
$data = Get-DatabaseData -connectionString $connectionString -query $query -isSQLServer
Write-Verbose "Migrating criterion usages..."
if ($null -eq $data) {
Write-Verbose "No criterion usages for $CriterionUId to migrate."
return
}
$usages = @()
$i = 0
foreach ($usage in $data) {
if ($i -gt 0) {
$usage = @{
UId = $usage.UId;
Version = $usage.Version;
Name = $usage.Name;
Position = $usage.Position;
Margin = $usage.Margin;
Unit = $usage.Unit;
LastModificationDate = $usage.LastModificationDate;
}
$usages += $usage
}
$i++
}
return $usages
}
# http://social.technet.microsoft.com/wiki/contents/articles/890.export-sql-server-blob-data-with-powershell.aspx
function Export-DBEnvironments([string] $connectionString, [string] $datatable, [string] $outDir, [switch] $useUId) {
$query = "select * from $datatable"
Write-Verbose $query
if (!(Test-Path $outDir)) {
md $outDir | Out-Null
}
$con = New-Object Data.SqlClient.SqlConnection;
$con.ConnectionString = $connectionString
$con.Open()
$cmd = New-Object Data.SqlClient.SqlCommand $query, $con
$rd = $cmd.ExecuteReader()
while ($rd.Read()) {
if ($ColIndexFetched -eq $null) {
$UIdCol = $rd.GetOrdinal("UId")
$VersionCol = $rd.GetOrdinal("Version")
$AutoPublishCol = $rd.GetOrdinal("AutoPublish")
$WorkingRawCol = $rd.GetOrdinal("WorkingRaw")
$PublishedRawCol = $rd.GetOrdinal("PublishedRaw")
$LastModifCol = $rd.GetOrdinal("LastModificationDateTicks")
$NameCol = $rd.GetOrdinal("Name")
$GroupCol = $rd.GetOrdinal("PlanningGroupContainer")
$ColIndexFetched = $true
}
if ($useUId) {
$envDirName = $rd.GetGuid($UIdCol)
} else {
$envName = Get-EscapedPath $rd.GetString($NameCol)
$envDirName = $envName
if(!($rd.IsDBNull($GroupCol))) {
$envGroup = $rd.GetString($GroupCol)
$escapedGroup = Get-EscapedPath $envGroup
$envDirName = $envDirName + "\" + $escapedGroup
}
}
Write-Output "Exporting environment $envDirName"
$envDir = $outDir + "\" + $envDirName
if (!(Test-Path $envDir)) {
md $envDir | Out-Null
}
$environment = @{
UId = $rd.GetGuid($UIdCol);
Version = $rd.GetInt32($VersionCol);
ModelVersion = "5.1";
LastModificationDate= $null
AutoPublish = $rd.GetBoolean($AutoPublishCol);
}
$filePath = $envDir + "\environment.json"
$json = $environment | ConvertTo-Json
$json | Out-File $filePath
Write-Verbose "Environment informations $envDirName exported"
Write-Verbose "Exporting working planning..."
$workingPath = $envDir + "\working.protobuf"
Write-Planning $rd $WorkingRawCol $workingPath
Write-Verbose "Working planning exported"
Write-Verbose "Exporting published planning..."
if(!($rd.IsDBNull($PublishedRawCol))) {
$publishedPath = $envDir + "\published.protobuf"
Write-Planning $rd $PublishedRawCol $publishedPath
Write-Verbose "Published planning exported"
} else {
Write-Verbose "No published planning"
}
Write-Verbose "Environment binaries $envDirName exported"
Write-Output "Environment $envDirName exported"
}
if ($fs -ne $null) {
$fs.Dispose()
}
if ($rd -ne $null) {
$rd.Close()
}
if ($cmd -ne $null) {
$cmd.Dispose()
}
if ($con -ne $null) {
$con.Close()
}
Write-Output "Export finished"
}
function Get-EscapedPath([string] $toEscape) {
$escaped = [System.Uri]::EscapeDataString($toEscape)
$escaped = $escaped.Replace("*", "__STAR__")
$escaped = $escaped.Replace(".", "__DOT__")
return $escaped
}
function Write-Planning($rd, $PlanningCol, $path) {
$fs = New-Object System.IO.FileStream $path, Create, Write
$bw = New-Object System.IO.BinaryWriter $fs
$bufferSize = 8192
$out = [array]::CreateInstance('Byte', $bufferSize)
$start = 0
$received = $rd.GetBytes($PlanningCol, $start, $out, 0, $bufferSize -1)
while ($received -gt 0) {
$bw.Write($out, 0, $received)
$bw.flush()
$start += $received
$received = $rd.GetBytes($WorkingRawCol, $start, $out, 0, $bufferSize - 1)
}
$bw.Close()
$fs.Close()
}
function Test-NavVersionCompatibility{
param ([Parameter(Mandatory=$True)] $year)
foreach($yVersion in $global:SupportedNavVersions){
if($yVersion -eq $year){
return $true
}
}
return $false
}
function Set-NAVAdapterParameter([string] $Tenant, [string] $Name, [string] $Value) {
$storePath = Get-NAVConfigurationPath $Tenant
$parameters = Get-AdapterParameters $Tenant $storePath
if ($parameters -eq $null) {
$parameters = New-NAVAdapterParameters $Tenant $storePath
}
if ($parameters -eq $null) {
Write-Warning "Cannot create or get NAV parameters for tenant $Tenant"
return
}
Set-AdapterParameter $Name $Value $parameters $NAVAdapterParameters $NAVAdapterParametersType "NAV"
Write-NavParameters $Tenant $parameters
Write-Verbose "Parameter set"
}
function New-NAVAdapterParameters([string] $Tenant, $StorePath) {
if (!(Test-Path $StorePath)) {
Set-NAVParameters
}
return Get-AdapterParameters $Tenant $StorePath
}
function Write-NAVValidParameters {
Write-ValidParameters "NAV" $NAVAdapterParameters
}
function Convert-NAVInstancesToArray([object] $NAVInstances) {
if ($NAVInstances.GetType().IsArray) {
[object] $NewInstances = @()
foreach ($instance in $NAVInstances) {
$xmlConfig = $instance | Get-NAVServerConfiguration -AsXml
$values = $xmlConfig.configuration.appSettings.add
$NAVServerInstance = ($values | Where-Object key -eq 'ServerInstance').value
$instanceConfig = Get-NAVParametersFromConfig $NAVServerInstance $global:NAVVersionCode
$NewInstances += $instanceConfig
}
return $NewInstances
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/WebUtil.ps1
|
WebUtil.ps1
|
Function Get-FreeWebPort {
<#
.Synopsis
Find a free port for web application.
.Description
Find a free port for web application, starting from a given port, and increment if needed.
.Parameter startingPort
The port to start with.
.Example
# find a free port starting with 8090
Get-FreeWebPort 8090
#>
[cmdletbinding()]
[OutputType([int])]
param(
[int] $startingPort
)
Process
{
$usedPorts = @()
Import-Module WebAdministration
foreach ($bind in (Get-WebBinding).bindingInformation) {
$port = Get-BindingPort $bind
$usedPorts += $port
}
$choosenPort = $startingPort
while ($usedPorts.contains($choosenPort)) {
$choosenPort += 10
}
return $choosenPort
}
}
function Get-BindingPort($bind) {
Write-Verbose "Extracting port from binding $bind"
$startIndex = $bind.indexof(':')+1
$endIndex = $bind.lastindexof(':')
if ($endIndex -gt $startIndex) {
$port = $bind.Substring($startIndex, ($endIndex-$startIndex))
} else {
$port = $bind.Substring($startIndex)
}
Write-Verbose "Extracted port = $port"
return [int] $port
}
function Find-WebSite($Port) {
$sites = Get-WebSite
foreach ($site in $sites) {
$matchSite = Find-SiteMatchPort $site $Port
if ($matchSite) {
return $site
}
}
return $null
}
function Find-SiteMatchPort($Site, $Port) {
$bindings = $Site.bindings.Collection.Where({$_.protocol.StartsWith('http')})
foreach ($binding in $bindings.bindingInformation) {
$sitePort = Get-BindingPort $binding
$siteName = $Site.Name
Write-Verbose "Comparing site $sitePort with $Port"
if ($sitePort -eq $Port) {
Write-Verbose "Site $siteName match port $Port"
return $true
}
}
return $false
}
function Set-WebAuthentication($Tenant, $WebSite, $AppName, $Value, [switch] $NoSave) {
$Path = $WebSite
$iisPath = "IIS:Sites\$Website"
Write-Verbose "Path is $Path"
if ($Value -eq "Windows") {
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value $true -PSPath IIS:\ -location "$Path"
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/AnonymousAuthentication -name enabled -value $false -PSPath IIS:\ -location "$Path"
$config = (Get-WebConfiguration system.web/authentication $iisPath)
$config.mode = "Windows"
$config | Set-WebConfiguration system.web/authentication
}
if ($Value -eq "Formular") {
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value $false -PSPath IIS:\ -location "$Path"
Set-WebConfigurationProperty -filter /system.webServer/security/authentication/AnonymousAuthentication -name enabled -value $true -PSPath IIS:\ -location "$Path"
$config = (Get-WebConfiguration system.web/authentication $iisPath)
$config.mode = "Forms"
$config | Set-WebConfiguration system.web/authentication
}
if (!($NoSave)) {
Store-WebConf $Tenant "Authentication" $Value
}
Write-Verbose "Configuration saved"
}
function Store-WebConf($Tenant, $Key, $Value) {
$path = Get-WebConfigPathFromTenant $Tenant
if (!(Test-Path $path)) {
mkdir $path | Out-Null
}
$filePath = "$path$Key"
Write-Verbose "Writing $Value to $filePath"
Set-Content $filePath $Value
}
function Get-WebConf($Tenant, $Key) {
$path = Get-WebConfigPathFromTenant $Tenant
$filePath = "$path$Key"
if (!(Test-Path $filePath)) {
Write-Verbose "Path $filePath does not exist"
return $null
}
Write-Verbose "Reading $filePath"
$value = Get-Content $filePath
Write-Verbose "$Key : $value"
return $value
}
function Get-SSLConf($Tenant) {
$ssljson = [string] (Get-WebConf $Tenant "SSL")
if ($ssljson -eq $null) {
$ssl = @{
"Enable" = $false;
}
} else {
$ssl = ConvertFrom-Json $ssljson
}
return $ssl
}
function Get-AuthenticationConf($Tenant) {
$authentication = Get-WebConf $Tenant "Authentication"
if ($authentication -eq $null) {
$authentication = "Windows"
}
return $authentication
}
function Apply-WebConfOnWebServices($webPath) {
$sslConf = Get-SSLConf $Tenant
if ($sslConf -eq $null) {
$ssl = "false"
} else {
$ssl = $sslConf.Enable
}
$authentication = Get-AuthenticationConf $Tenant
if ($authentication -eq $null) {
$authentication = "Windows"
}
Write-Output "Web configuration - SSL: $ssl, Authentication: $authentication"
$servicePath = "$webPath\services.config"
$backupPath = "$webPath\services.backup"
Backup-ServiceConfig $servicePath $backupPath
Write-ServiceInit $servicePath
Write-ServicesHeader $servicePath
Write-Services $servicePath $authentication $ssl
Write-ServicesFooter $servicePath
}
function Backup-ServiceConfig($Path, $Backup) {
if (Test-Path $Path) {
Write-Verbose "Creating backup of $Path to $Backup"
Copy-Item $Path $Backup -force | Out-Null
}
}
function Write-ServiceInit($Path) {
Write-Verbose "Initializing $Path"
New-Item $Path -force | Out-Null
}
function Write-ServicesHeader($Path) {
Add-Content $Path "<?xml version=`"1.0`"?>"
Add-Content $Path "<services>"
}
function Write-ServicesFooter($Path) {
Add-Content $Path "</services>"
}
function Write-Services($Path, $Authentication, $SSL) {
foreach($pair in $services.GetEnumerator()) {
$service = $($pair.Name)
$behavior = $($pair.Value)
$contract = $endpointContract[$service]
if ($contract -eq $null) {
$contract = $service
}
Write-Verbose "Registering service $service"
Write-ServiceHeader $Path $service
$binding = Get-Binding $Authentication "false"
Write-EndPoint $Path $behavior $binding $contract
if ($SSL -eq "true") {
$binding = Get-Binding $Authentication "true"
Write-EndPoint $Path $behavior $binding $contract
}
Write-ServiceFooter $Path
}
}
function Get-Binding($Authentication, $SSL) {
if ($Authentication -eq "Windows") {
if ($SSL -eq "true") {
return "securedWebBinding"
} else {
return "defaultWebBinding"
}
} else {
if ($SSL -eq "true") {
return "anoSecuredWebBinding"
} else {
return "anoWebBinding"
}
}
}
function Write-ServiceHeader($Path, $Service) {
$header = "`t" + $serviceHeaderTemplate.Replace("[SERVICE]", $Service)
Add-Content $Path $header
}
function Write-EndPoint($Path, $Behavior, $Binding, $Service) {
$endpoint = "`t`t" + $endPointTemplate.Replace("[BEHAVIOR]", $Behavior).Replace("[BINDING]", $Binding).Replace("[SERVICE]", $Service)
Add-Content $Path $endpoint
}
function Write-ServiceFooter($Path) {
Add-Content $Path "`t</service>"
}
$serviceHeaderTemplate = "<service behaviorConfiguration=`"httpGetEnablingBehavior`" name=`"[SERVICE]`">"
$endPointTemplate = "<endpoint address=`"`" behaviorConfiguration=`"[BEHAVIOR]`" binding=`"webHttpBinding`" bindingConfiguration=`"[BINDING]`" contract=`"[SERVICE]`"/>"
$services = @{
"Ortems.PlannerOne.Web.UserControl.CalendarExceptions.CalendarException" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Indicators.IndicatorsService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Scheduling.ConfirmationLoader" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Sequencing.SequencingService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.Custom.TaskColorService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Filter.FilterService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Views.ResourceSequence.ResourceSequenceService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.DetailsPanel.InfoService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Utilities.UtilitiesService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.RefreshService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.ViewsService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.Custom.RowService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.Custom.Task" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Robots.RobotsService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Search.SearchService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Action.ManageTask.TaskManagerService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Views.Calendar.Service" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.ActivityComputation.ActivityComputationService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Service.SelectionService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Views.JobOverview.JobOverviewService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.Display.Total.TotalService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Service.ViewsService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.SwitchPlanning.SwitchPlanningService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.MoveTasks.MoveTasksService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Api.PlanningProduction" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Api.PlanningProject" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.UserControl.WebGantt.Gantt" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Admin.PerformanceService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Admin.PerformanceSessionService" = "webHttp";
"Ortems.PlannerOne.Web.Admin.WebSecurityService" = "webHttp";
"Ortems.PlannerOne.Web.UserControl.Action.Assignment.ChooseResource" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Configure.ConfigurationService" = "webHttp";
"Ortems.PlannerOne.Web.Admin.ICalConfigurationService" = "webHttp";
"Ortems.PlannerOne.Web.UserControl.PinTasks.PinTasksService" = "webScriptEnablingBehavior";
"Ortems.PlannerOne.Web.Api.CacheInfo" = "webHttp";
}
$endpointContract = @{
"Ortems.PlannerOne.Web.Api.PlanningProduction" = "Ortems.PlannerOne.Web.Api.IPlanningProductionContract";
"Ortems.PlannerOne.Web.Api.PlanningProject" = "Ortems.PlannerOne.Web.Api.IPlanningContract"
}
function Get-P1WebApplication([string]$Tenant) {
$info = Get-P1Tenant $Tenant
$host = $info.WebHost
$port = $info.SitePort
$app = $info.WebApplicationName
Write-Output "Host: $host, Port: $port, Application name: $app"
$site = Find-WebSite $port
$siteName = $site.Name
if ($site -eq $null) {
Write-Warning "No site use binding $port configured for tenant Web Application $app of tenant $Tenant. Operation canceled."
return $null
} else {
Write-Verbose "Site found"
}
$webApp = Get-WebApplication -Name $app -Site $siteName
if ($webApp -eq $null) {
Write-Warning "Cannot find Web Application $app for port $port"
return $null
} else {
Write-Verbose "Web Application found"
}
return $webApp
}
function Register-P1WebServices($Tenant) {
Write-Section "Registering Web services for current security"
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return;
}
$info = Get-P1Tenant $Tenant
$host = $info.WebHost
$port = $info.SitePort
$app = $info.WebApplicationName
Write-Output "Host: $host, Port: $port, Application name: $app"
$site = Find-WebSite $port
if ($site -eq $null) {
Write-Warning "No site use binding $port configured for tenant Web Application $app of tenant $Tenant. Operation canceled."
return $null
} else {
Write-Verbose "Site found"
}
$path = $site.PhysicalPath
Write-Verbose "Physical path is $path"
Apply-WebConfOnWebServices $path
Write-OK "REST services registered with security for tenant $Tenant"
}
function Set-WebAuthenticationInternal([string] $Tenant, [switch] $Windows, [switch] $Formular, [switch] $NoSave) {
$info = Get-P1Tenant $Tenant
$host = $info.WebHost
$port = $info.SitePort
$app = $info.WebApplicationName
Write-Verbose "Host: $host, Port: $port, Application name: $app"
$site = Find-WebSite $port
$siteName = $site.Name
if ($site -eq $null) {
Write-Warning "No site use binding $port configured for tenant Web Application $app of tenant $Tenant. Operation canceled."
return
} else {
Write-Verbose "Site found"
}
$webApp = Get-WebApplication -Name $app -Site $siteName
if ($webApp -eq $null) {
Write-Warning "Cannot find Web Application $app for port $port"
} else {
Write-Verbose "Web Application found"
}
$webAppPath = $webApp.PhysicalPath
$sitePath = $site.PhysicalPath
$siteConfigSource = "$webAppPath\site.config"
$siteConfigTarget = "$sitePath\web.config"
Write-Verbose "Copying $siteConfigSource to $siteConfigTarget"
Copy-Item $siteConfigSource $siteConfigTarget -Force
$mode = ""
if ($Windows) {
$mode = "Windows"
}
if ($Formular) {
$mode = "Formular"
}
Write-Verbose "Mode will be set to $mode"
Set-WebAuthentication $Tenant $siteName $app $mode -NoSave:$NoSave.IsPresent
}
function Set-WebSSLInternal([string] $Tenant, [switch] $Enable, [switch] $Disable, [int] $SSLPort, [string] $CertificateStore, [string] $CertificateFriendlyName, [string] $CertificateThumbprint, [string] $HostedIP, [switch] $NoSave) {
if ($SSLPort -eq 0) {
Write-Warning "No SSL Port define, trying with 443."
$SSLPort = 443
}
$info = Get-P1Tenant $Tenant
$host = $info.WebHost
$port = $info.SitePort
$app = $info.WebApplicationName
Write-Verbose "Host: $host, Port: $port, Application name: $app"
$site = Find-WebSite $port
$siteName = $site.Name
if ($site -eq $null) {
Write-Warning "No site use binding $port configured for tenant Web Application $app of tenant $Tenant. Operation canceled."
return
} else {
Write-Verbose "Site found"
}
$bindingHostedIP = $HostedIP
if ($HostedIP -eq "" -or $HostedIP -eq "0.0.0.0") {
$HostedIP = "0.0.0.0"
$bindingHostedIP = "*"
}
# Disable binding for site
if ($Disable) {
Write-Verbose "Removing binding $SSLPort on site $siteName"
try {
Remove-WebBinding -Name "$siteName" -Port $SSLPort -ErrorAction Stop
} catch {
Write-KO "Web application binding for port $SSLPort does not exist"
}
Write-Verbose "Removing SSL binding record"
try {
Remove-Item "IIS:\SslBindings\$HostedIP!$SSLPort" -ErrorAction Stop
} catch {
Write-KO "SSL Binding IIS:\SslBindings\$HostedIP!$SSLPort does not exist"
}
if (!($NoSave)) {
$conf = @{
"Enable" = $false;
}
$jsonConf = ConvertTo-Json $conf
Store-WebConf $Tenant "SSL" $jsonConf
}
Write-OK "Web SSL disabled for tenant $Tenant"
return
}
# Create binding for site
Write-Verbose "Creating new binding $SSLPort on site $siteName"
try {
New-WebBinding -Name "$siteName" -IPAddress "$bindingHostedIP" -Port $SSLPort -Protocol https
} catch {
Write-KO "Port is already define on site"
return
}
# Create SSL Binding in IIS
if ($CertificateStore -eq "") {
$CertificateStore = "My"
}
if ($CertificateFriendlyName -ne "" -and $CertificateThumbprint -ne "" ) {
Write-Warning "You can only use one certificate option between CertificateFriendlyName and CertificateThumbprint"
return
}
if ($CertificateFriendlyName -eq "" -and $CertificateThumbprint -eq "" ) {
Write-Warning "You must choose one certificate option between CertificateFriendlyName and CertificateThumbprint"
return
}
$certificateLocation = "cert:\LocalMachine\$CertificateStore"
Write-Verbose "Certificate location is $certificateLocation"
if ($CertificateFriendlyName -ne "") {
Write-Verbose "Searching for certificate with friendly name $CertificateFriendlyName"
$certificate = Get-ChildItem $certificateLocation | where-object { $_.FriendlyName -eq "$CertificateFriendlyName" }
}
if ($CertificateThumbprint -ne "") {
Write-Verbose "Searching for certificate with thumbprint $CertificateThumbprint"
$certificate = Get-ChildItem $certificateLocation | where-object { $_.Thumbprint -eq "$CertificateThumbprint" }
}
if ($certificate -eq $null) {
Write-KO "Cannot find certificate $CertificateFriendlyName $CertificateThumbprint in $certificateLocation"
return
} else {
# Thumbprint is store in configuration
$CertificateThumbprint = $certificate.Thumbprint
Write-Verbose "Certificate has been found"
}
Write-Verbose "Writing SSL binding IIS:\SslBindings\$HostedIP!$SSLPort"
try {
$certificate | New-Item "IIS:\SslBindings\$HostedIP!$SSLPort"
} catch {
Write-KO "IIS SSL binding IIS:\SslBindings\$HostedIP!$SSLPort already exist"
}
Write-Verbose "SSL binding written"
if (!($NoSave)) {
$conf = @{
"Enable" = $true;
"Port" = $SSLPort;
"Store" = "$CertificateStore";
"Thumbprint" = "$CertificateThumbprint";
"IP" = "$HostedIP";
}
$jsonConf = ConvertTo-Json $conf
Store-WebConf $Tenant "SSL" $jsonConf
}
}
function EscapeQueryData($parameter) {
$escaped = [System.Uri]::EscapeDataString($parameter)
$escaped = $escaped.Replace(".", "%2E")
return $escaped
}
function FixUrl($url) {
# protocol for which to prevent unescaping. Change to HTTPS if necessary.
$protocol = "http"
# flag's value
$UnEscapeDotsAndSlashes = 0x2000000
# GetSyntax method, which is static internal, gets registered parsers for given protocol
$getSyntax = [System.UriParser].GetMethod("GetSyntax", 40)
# field m_Flags contains information about Uri parsing behaviour
$flags = [System.UriParser].GetField("m_Flags", 36)
$parser = $getSyntax.Invoke($null, $protocol)
# get the current Flag settings
$currentValue = $flags.GetValue($parser)
# check if un-escaping enabled
if (($currentValue -band $UnEscapeDotsAndSlashes) -eq $UnEscapeDotsAndSlashes) {
$newValue = $currentValue -bxor $UnEscapeDotsAndSlashes
# disable unescaping by removing UnEscapeDotsAndSlashes flag
$flags.SetValue($parser, $newValue)
}
$uri = new-object Uri($url)
return $uri
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/ApiKeyUtil.ps1
|
ApiKeyUtil.ps1
|
function Get-ApiPath {
return "$env:ProgramData\$TenantPrefix\API\"
}
function Get-ApiFile {
$baseDir = Get-ApiPath
return $baseDir + "key"
}
function Get-ApiKey {
$path = Get-ApiFile
if (!(Test-Path $path)) {
Write-Warning "No PlannerOne API key stored"
Write-Warning "Store one with Set-P1ApiKey"
Write-Warning "Contact PlannerOne team to get your private key"
return ""
}
return Get-Content $path
}
function Set-ApiKey($key) {
$baseDir = Get-ApiPath
if (!(Test-Path $baseDir)) {
mkdir $baseDir | Out-Null
}
$path = Get-ApiFile
$key | Out-File $path
}
function Get-FeedURL([string]$Source) {
if ($Source -ne "") {
Write-Verbose "Feed URL is $Source"
return $Source
} else {
$ApiKey = Get-ApiKey
if ($ApiKey -eq "") {
return ""
}
$feedUrl = [string]::Format($SourceURL,$ApiKey)
Write-Verbose "Feed URL is $feedUrl"
return $feedUrl
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/OutputUtil.ps1
|
OutputUtil.ps1
|
function Write-Section($Text) {
$baseColor = [Console]::ForegroundColor
[Console]::ForegroundColor = "Cyan"
Write-Output "$Text"
[Console]::ForegroundColor = $baseColor
}
function Write-OK($Text) {
$baseColor = [Console]::ForegroundColor
[Console]::ForegroundColor = "Green"
Write-Output "> $Text"
[Console]::ForegroundColor = $baseColor
}
function Write-Alert($Text) {
$baseColor = [Console]::ForegroundColor
[Console]::ForegroundColor = "Yellow"
Write-Output "> $Text"
[Console]::ForegroundColor = $baseColor
}
function Write-KO($Text) {
$baseColor = [Console]::ForegroundColor
[Console]::ForegroundColor = "Red"
Write-Output "> $Text"
[Console]::ForegroundColor = $baseColor
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/ReportsUtil.ps1
|
ReportsUtil.ps1
|
$global:NameDelimiter = " "
function Get-ConfigReportsFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\MigrationReports\"
}
function Get-GlobalReportPath() {
return "$env:ProgramData\$TenantPrefix\MigrationReports\"
}
function Get-GlobalReportList() {
$path = Get-GlobalReportPath
Get-ReportList $path
}
function Get-GlobalReport($Report) {
$storePath = Get-GlobalReportPath
Get-Report $storePath $Report
}
function Get-ConfigReportList($Tenant) {
$path = Get-ConfigReportsFromTenant $Tenant
Get-ReportList $path
}
function Get-ConfigReport($Tenant, $Report) {
$storePath = Get-ConfigReportsFromTenant $Tenant
Get-Report $storePath $Report
}
function Get-ReportList($path) {
Get-ChildItem $path -Filter *.json | format-table -property @{n="Report";e={$_.basename}}
}
function Get-Report($storePath, $Report) {
$path = $storePath + $Report + ".json"
Write-Verbose "Reading $path"
if ([System.IO.File]::Exists($path)) {
$json = [system.IO.File]::ReadAllText($path)
$info = $json | ConvertFrom-Json
Write-Output $info
} else {
Write-Output "$Report does not exist"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/AdapterUtil.ps1
|
AdapterUtil.ps1
|
function Set-AdapterParameter([string] $Name, [string] $Value, $Parameters, $ParametersCollection, $ParametersTypeCollection, $CollectionName) {
if (!($ParametersCollection.ContainsKey($Name))) {
Write-Warning "Property $Name is not a valid property. Operation canceled."
Write-ValidParameters $CollectionName $ParametersCollection
return
}
$propertyName = $ParametersCollection.Get_Item($Name)
if ($propertyName -eq $null) {
Write-Warning "Property name for $Name cannot be empty"
return
}
$propertyType = $ParametersTypeCollection.Get_Item($Name)
if ($propertyType -eq "") {
Write-Warning "Property type is missing in module. Continuing with type string."
$propertyType = "string"
}
$validType = Test-ParameterType $propertyType $Value
if (!$validType) {
Write-Warning "Type of value $Value for property $Name is not valid. Operation canceled."
return
}
$typedValue = Get-TypedValue $Value $propertyType
Write-Verbose "Adapter property corresponding to $Name is $propertyName"
Write-Verbose "Setting $propertyName to $Value..."
if (($Parameters | Get-Member -name $propertyName) -eq $null) {
$Parameters | Add-Member NoteProperty -Name $propertyName -Value $typedValue
} else {
$Parameters.$propertyName = $typedValue
}
}
function Get-AdapterParameters([string] $Tenant, $StorePath) {
if (Test-Path $StorePath) {
Write-Verbose "Reading configuration in $StorePath"
$json = Get-Content $StorePath
$configuration = $json | ConvertFrom-Json
return $configuration
} else {
Write-Verbose "No configuration in $storePath"
return $null
}
}
function Write-ValidParameters($CollectionName, $Collection) {
Write-Section "List of valid $CollectionName parameters"
$sorted = $Collection.GetEnumerator() | Sort-Object -Property Name
foreach($pair in $sorted) {
Write-Output $pair.Name
}
}
function Is-Numeric ($Value) {
return $Value -match "^[\d\.]+$"
}
function Test-ParameterType($PropertyType, $Value) {
if ($PropertyType -eq "int") {
$result = Is-Numeric $Value
if (!$result) {
Write-Warning "Value should be numeric"
}
return $result
}
if ($PropertyType -eq "bool") {
if ($Value -ne "true" -and $Value -ne "false") {
Write-Warning "Value should be boolean: true or false"
return $false
}
}
return $true
}
function Get-TypedValue($Value, $PropertyType) {
if ($PropertyType -eq "int") {
return [int]($Value)
}
if ($PropertyType -eq "bool") {
if ($Value -eq "false") {
return $false
} else {
return $true
}
}
return $Value
}
function Get-ConfigurationPath($Tenant, $File) {
$storePath = Get-AdapterConfigPathFromTenant $Tenant
if (!(Test-Path $storePath)) {
md $storePath | Out-Null
}
$storePath = $storePath + $File
return $storePath
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/DBUtil.ps1
|
DBUtil.ps1
|
function Get-LegacyDatabaseConfig($Role) {
$path = Get-LegacyDBConfigPath $Role
if (Test-Path $path) {
[xml]$dbConfigReader = Get-Content $path
$dbConfig = @{
Server = $dbConfigReader.DataConnectionConfig.serversList.Server.name;
Database = $dbConfigReader.DataConnectionConfig.serversList.Server.databasesList.Database.name;
}
Write-Verbose "Database configuration found and read"
return $dbConfig
} else {
Write-Warning "No database configuration $path"
return $null
}
}
function Get-ConnectionString(
$Server,
$Database,
$IntegratedSecurity,
$Login,
$Password) {
return "Server=$Server;Database=$Database;User ID=$Login;Password=$Password;Integrated Security=$IntegratedSecurity"
}
function Get-DatabaseData {
[CmdletBinding()]
param (
[string]$connectionString,
[string]$query,
[switch]$isSQLServer
)
if ($isSQLServer) {
Write-Verbose 'in SQL Server mode'
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
} else {
Write-Verbose 'in OleDB mode'
$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
}
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
if ($isSQLServer) {
$adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command
} else {
$adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $command
}
$dataset = New-Object -TypeName System.Data.DataSet
$adapter.Fill($dataset)
$dataset.Tables[0]
}
function Invoke-DatabaseQuery {
[CmdletBinding()]
param (
[string]$connectionString,
[string]$query,
[switch]$isSQLServer
)
if ($isSQLServer) {
Write-Verbose 'in SQL Server mode'
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
} else {
Write-Verbose 'in OleDB mode'
$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
}
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
$connection.Open()
$command.ExecuteNonQuery()
$connection.close()
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/MenuUtil.ps1
|
MenuUtil.ps1
|
function Show-Menu
{
param (
[Parameter(Mandatory=$true)] [string]$Title,
[Parameter(Mandatory=$true)] [string[]]$Choices
)
Write-Host ""
Write-Host "===== $Title ====="
Write-Host ""
$number = 0
foreach ($choice in $Choices) {
$number++
Write-Host "[$number] $choice"
}
Write-Host ""
do
{
$selection = Read-Host "Please make a selection"
}
until ($selection -match "^[\d]+$" -and $selection -ge 1 -and $selection -le $Choices.Count)
$selected = $Choices[$selection-1]
Write-Host "You've selected [$selection], $selected"
return $selection-1
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Private/TenantUtil.ps1
|
TenantUtil.ps1
|
$global:NameDelimiter = " "
function Get-ServiceNameFromTenant($Tenant) {
return $TenantPrefix + $Tenant
}
function Get-ServiceDisplayNameFromTenant($Tenant) {
return $TenantPrefix + $NameDelimiter + $Tenant
}
function Get-ServicePath {
return "$env:ProgramFiles\$TenantPrefix"
}
function Get-WebAppNameFromTenant($Tenant) {
return $TenantPrefix + $Tenant
}
function Get-SiteNameFromTenant($Tenant) {
return $TenantPrefix + $NameDelimiter + $Tenant + " Site"
}
function Get-PoolNameFromTenant($Tenant) {
return $TenantPrefix + $NameDelimiter + $Tenant + " Pool"
}
function Get-DatabaseNameFromTenant($Tenant) {
return $TenantPrefix + $Tenant
}
function Get-ServerPathFromTenant($Tenant) {
$servicePath = Get-ServicePath
return "$servicePath\$Tenant"
}
function Get-LegacyRolePath {
return "$env:ProgramData\$TenantPrefix\PlannerOneInstall.config"
}
function Get-LegacyDBConfigPath($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\database.config"
}
function Get-TenantsPath {
return "$env:ProgramData\$TenantPrefix\Tenants\"
}
function Get-AdapterConfigPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\Adapter\"
}
function Get-UIParamPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\GUI\"
}
function Get-CriteriaPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\Criteria\"
}
function Get-LocalStorePathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\"
}
function Get-EnvironmentsPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Environments\"
}
function Get-WebConfigPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\Web\"
}
function Get-ConfigPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Config\"
}
function Get-LogPathFromTenant($Tenant) {
return "$env:ProgramData\$TenantPrefix\$Tenant\Logs\"
}
function Register-Tenant($Tenant, $RemotingPort, $WebServicePort, $WebAppName, $SitePort, $Adapter, [string] $BinPath) {
if ($BinPath -eq "") {
$serverPath = ServerPathFromTenant $Tenant
} else {
$serverPath = $BinPath
}
$serviceName = Get-ServiceNameFromTenant $Tenant
if (!$WebAppName) {
$WebAppName = Get-WebAppNameFromTenant $Tenant
}
$tenantInfo = @{
Role = $Tenant;
Path = $serverPath;
WebApplicationName = $WebAppName;
SitePort = $SitePort;
RemotingPort = $RemotingPort;
WebServicePort = $WebServicePort;
WindowsServiceName = $serviceName;
WebHost = "localhost";
ServiceHost = "localhost";
Adapter = $Adapter;
}
Write-TenantInfo $Tenant $tenantInfo
}
function Write-TenantInfo($Tenant, $tenantInfo) {
$data = $tenantInfo | ConvertTo-Json
$storePath = Get-TenantsPath
if (!(Test-Path $storePath)) {
mkdir $storePath | Out-Null
}
$storePath = $storePath + $Tenant + ".json"
[System.IO.File]::WriteAllText($storePath, $data)
Write-Verbose "Tenant registered in $storePath"
}
function Remove-Tenant($Tenant, [switch]$RemoveData) {
$storePath = Get-TenantsPath
$storePath = $storePath + $Tenant + ".json"
Write-Verbose "Removing tenant configuration $storePath"
remove-item $storePath
$dataPath = Get-LocalStorePathFromTenant $Tenant
if ($RemoveData.IsPresent) {
Write-Verbose "Removing data stored in $dataPath ..."
Remove-Item $dataPath -Recurse -Force
} else {
Write-Verbose "Keeping data stored in $dataPath"
}
}
function Get-TenantList() {
$path = Get-TenantsPath
Get-ChildItem $path -Filter *.json | format-table -property @{n="Tenant";e={$_.basename}}
}
function Get-TenantInfo($Tenant) {
$storePath = Get-TenantsPath
$path = $storePath + $Tenant + ".json"
Write-Verbose "Reading $path"
if ([System.IO.File]::Exists($path)) {
$json = [system.IO.File]::ReadAllText($path)
$tenant = $json | ConvertFrom-Json
return $tenant
} else {
return "Tenant $Tenant does not exist"
}
}
function Test-Tenant($Tenant) {
$storePath = Get-TenantsPath
$path = $storePath + $Tenant + ".json"
return Test-Path $path
}
function Modify-TenantInfo([string] $Tenant, [int] $RemotingPort, [int] $WebServicePort, [int] $WebPort, [string] $WebAppName) {
$tenantInfo = Get-TenantInfo $Tenant
if ($RemotingPort -ne 0) {
$tenantInfo.RemotingPort = $RemotingPort
}
if ($WebServicePort -ne 0) {
$tenantInfo.WebServicePort = $WebServicePort
}
if ($WebPort -ne 0) {
$tenantInfo.SitePort = $WebPort
}
if ($WebAppName -ne "") {
$tenantInfo.WebApplicationName = $WebAppName
}
Write-TenantInfo $Tenant $tenantInfo
}
function Write-P1AdapterParametersList() {
Write-Section "Adapter parameter list"
foreach($parameter in $AdapterParameters) {
Write-Output $parameter
}
}
function Restart-Tenant($webApp, $tenantInfo) {
Stop-P1ServiceInternal $tenantInfo
$poolName = $webApp.applicationPool
Write-Verbose "Restarting web application $poolName"
Restart-WebAppPool "$poolName"
Start-P1ServiceInternal $tenantInfo
}
function Stop-P1ServiceInternal($tenantInfo) {
$serviceName = $tenantInfo.WindowsServiceName
Write-Verbose "Stopping $serviceName"
Stop-Service "$serviceName"
}
function Start-P1ServiceInternal($tenantInfo) {
$serviceName = $tenantInfo.WindowsServiceName
Write-Verbose "Starting $serviceName"
Start-Service "$serviceName"
}
function Stop-P1WebInternal($webApp) {
$poolName = $webApp.applicationPool
Write-Verbose "Stopping web application $poolName"
Stop-WebAppPool "$poolName"
}
function Start-P1WebInternal($webApp) {
$poolName = $webApp.applicationPool
Write-Verbose "Starting web application $poolName"
Start-WebAppPool "$poolName"
}
function Test-ERPName($ERP) {
[bool]$valid = $false
foreach($erpName in $ERPS) {
if ($ERP -eq $erpName) {
$valid = $true
break
}
}
return $valid
}
function Write-ERPNames() {
Write-Output "Valid ERP names:"
foreach($erpName in $ERPS) {
Write-Output $erpName
}
}
function Get-AdapterStatus($wsPort)
{
Write-Output "Production Scheduler adapter status:"
Get-ProductAdapterStatus $wsPort "adapter"
Write-Output "Resoure Planner adapter status:"
Get-ProductAdapterStatus $wsPort "adapterproject"
}
function Get-ProductAdapterStatus($wsPort, $service)
{
$url = "http://localhost:$wsPort/services/$service/nav/status"
write-verbose "url: $url"
$statusResp = Invoke-RestMethod -Method GET -Uri $url -UseDefaultCredentials
Write-AdapterStatus $statusResp
}
function Write-AdapterStatus($statusResp)
{
$global = $statusResp.Global
$status = $statusResp.Status
Write-Output "Global: $global"
foreach ($kvp in $statusResp.Environments)
{
$envName = $kvp.Key.Name
$envGroup = $kvp.Key.PlanningGroupContainer
$envStatus = $kvp.Value
Write-Output "$envName - $envGroup`: $envStatus"
}
if ($status -eq "Ready") {
Write-OK "Status: $status"
}
else {
Write-KO "Status: $status"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Restore-P1ConfigVal.ps1
|
Restore-P1ConfigVal.ps1
|
function Restore-P1ConfigVal {
<#
.Synopsis
Copy in local files the PlannerOne Config files.
.Description
After the backup command, this command copy the PlannerOne backup configuration files and reset the PlannerOne web security for the tenant(s).
.Parameter filesDir
Input files config directory.
.Parameter Tenant
The target tenant. If you have more than one tenant, use "," to seperate all name like -tenant "tenant1,tenant2,tenant3"
.Example
# Restoring PlannerOne Config File
Restore-P1ConfigVal -filesDir 'C:\tmp\PlannerOne_BackUp' -tenant Prod
# Restoring PlannerOne with multitenant configuration
Restore-P1ConfigVal -filesDir 'C:\tmp\PlannerOne-BackUp' -tenant 'Prod1,Debug,ValidTest2015,ValidTest2017'
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)] [string] $filesDir,
[Parameter(Mandatory=$true)] [string] $tenant
)
Process
{
Write-Section "Restore PlannerOne Configuration File from '$filesDir'"
if(($filesDir -eq "") -OR !(test-path $filesDir )){
Write-Error "Folder $filesDir not found"
return
}
$OutDir = $env:ProgramData + "\PlannerOne"
mkdir $OutDir -force
Copy-Item $filesDir $OutDir -Recurse -force
Write-Verbose "Copy '$filesDir' to '$OutDir'."
if($tenant.Contains(',')){
$tenants = $tenant.Split(',').Trim()
foreach($tnt in $tenants){
Write-Verbose "Restore WebSecurity for tenant : $tnt"
Restore-P1WebSecurity -tenant $tnt
}
}else{
Write-Verbose "Restore WebSecurity for tenant : $tenant"
Restore-P1WebSecurity -tenant $tenant
}
Write-OK "Restore ended"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Backup-P1ConfigValue.ps1
|
Backup-P1ConfigValue.ps1
|
function Backup-P1ConfigValue {
<#
.Synopsis
Export PlannerOne configuration file to file.
.Description
Copy at destination path the PlannerOne configuration files to creat a backup folder.
.Parameter OutDir
The root directory path to use for export. .\p1EnvExport by default.
.Example
#Copy the cofiguration files to c:\tmp
Backup-P1ConfigValue C:\tmp\Plannerone-Backup
#>
[cmdletbinding()]
param(
[string] $OutDir = ""
)
Process {
Write-Section "Backup PlannerOne config file..."
if ($OutDir -eq "") {
$OutDir = ".\p1P1ConfigBackup"
}
if (!(Test-Path $OutDir)) {
mkdir $OutDir | Out-Null
}
$sourcePath = $env:ProgramData + "\PlannerOne"
write-verbose "Copy '$sourcePath' to '$OutDir'."
Copy-Item $sourcePath $OutDir -Recurse -force
Write-Section "Backup finished"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Get-P1LogLevel.ps1
|
Get-P1LogLevel.ps1
|
function Get-P1LogLevel {
<#
.Synopsis
Get the PlannerOne log level for tenant.
.Description
Get the PlannerOne log level for tenant.
.Parameter Tenant
The tenant name.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant
)
Process
{
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return
}
$level = Read-LogLevel $Tenant
Write-Output $level
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Set-P1Tenant.ps1
|
Set-P1Tenant.ps1
|
function Set-P1Tenant {
<#
.Synopsis
Modify a tenant configuration.
.Description
Modify the configuration of an existing PlannerOne tenant.
.Parameter Tenant
The tenant name.
.Parameter WebServicePort
The port to be used by AppServer for REST API.
.Parameter RemotingPort
The port to be used by AppServer for Remoting API.
.Parameter WebPort
The customized port to be used by WebServer site.
.Parameter WebAppName
The customized name to use for web application.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant,
[int] $RemotingPort,
[int] $WebServicePort,
[int] $WebPort,
[string] $WebAppName
)
Process
{
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return
}
$tenantInfo = Get-TenantInfo $Tenant
if ($tenantInfo -eq $null) {
Write-Warning "No tenant information available"
Write-Warning "Configuration cancel"
return
}
Modify-TenantInfo $Tenant $RemotingPort $WebServicePort $WebPort $WebAppName
$serviceName = Get-ServiceNameFromTenant $Tenant
Write-Output "Restarting PlannerOne service $serviceName..."
Stop-Service -Name $ServiceName -Force
Write-Output "Waiting 5 seconds for service to really stop."
Start-Sleep -seconds 5
Start-Service -Name $serviceName
Write-OK "Configuration done"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Restore-P1WebSecurity.ps1
|
Restore-P1WebSecurity.ps1
|
function Restore-P1WebSecurity {
<#
.Synopsis
Restore Web Application IIS configration based on security configuration (Authentication and SSL)
.Description
Configure IIS and register PlannerOne Web Application REST services with correct security configuration based on Authentication and SSL.
Run Set-P1WebAuthentication and Set-P1WebSSL to change this parameters.
.Parameter Tenant
The target tenant.
.Example
# Restoring security
Restore-P1WebSecurity -Tenant Prod
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant
)
Process
{
Write-Section "Restoring IIS and REST Web services for current security"
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return;
}
$ssl = Get-SSLConf $Tenant
if ($ssl.Enable) {
Write-Alert "Enabling SSL"
} else {
Write-Alert "Disabling SSL"
}
$disable = !($ssl.Enable)
Set-WebSSLInternal -Tenant $Tenant -Enable:$ssl.Enable -Disable:$disable -SSLPort $ssl.Port -CertificateStore $ssl.Store -CertificateThumbprint $ssl.Thumbprint -HostedIP $ssl.IP -NoSave
$authentication = Get-AuthenticationConf $Tenant
Write-Alert "Applying authentication security: $authentication"
$windows = $true
$formular = $false
if ($authentication -ne "Windows") {
$windows = $false
$formular = $true
}
Set-WebAuthenticationInternal -Tenant $Tenant -Windows:$windows -Formular:$formular -NoSave
Register-P1WebServices $Tenant
Write-OK "Web security configuration restored for $Tenant"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Copy-P1Environment.ps1
|
Copy-P1Environment.ps1
|
function Copy-P1Environment {
<#
.Synopsis
Copy environments between two tenants
.Description
Copy all environments from one tenant to another.
.Parameter InTenant
The tenant name to copy from.
.Parameter OutTenant
The tenant name to copy to.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $InTenant,
[Parameter(Mandatory=$true)]
[string] $OutTenant
)
Process {
if (!(Test-Tenant $InTenant)) {
Write-Warning "Tenant $InTenant does not exist."
return
}
if (!(Test-Tenant $OutTenant)) {
Write-Warning "Tenant $OutTenant does not exist."
return
}
Write-Section "Copying environments..."
$sourceDir = Get-EnvironmentsPathFromTenant $InTenant
$sourcePath = $sourceDir + "*"
$targetPath = Get-EnvironmentsPathFromTenant $OutTenant
if (!(Test-Path $targetPath)) {
mkdir $targetPath | Out-Null
}
Write-Verbose "Copying from $sourcePath to $targetPath"
Copy-Item -Recurse $sourcePath $targetPath -Force
Write-Section "Copy finished"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Start-P1WebManager.ps1
|
Start-P1WebManager.ps1
|
function Start-P1WebManager {
<#
.Synopsis
Start PlannerOne web manager.
.Description
Start PlannerOne web manager in the default web browser.
.Parameter Tenant
The target tenant.
.Example
# Start PlannerOne web manager for tenant named Prod.
Start-P1WebManager -Tenant Prod
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant
)
Process
{
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return;
}
$info = Get-P1Tenant $Tenant
$host = $info.WebHost
$port = $info.SitePort
$app = $info.WebApplicationName
$url = "http://" + $host + ":" + $port + "/" + $app + "/configure"
Write-Verbose "Opening $url"
[Diagnostics.Process]::Start($url) | Out-Null
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Switch-P1Version.ps1
|
Switch-P1Version.ps1
|
function Switch-P1Version {
<#
.Synopsis
Switch to another version an existing PlannerOne tenant (service + web app).
.Description
Switch an existing PlannerOne tenant to another version.
Warning: PlannerOne service will be restarted during the process.
.Parameter Tenant
The tenant name.
.Parameter Version
The version to switch to.
.Example
# Switch a PlannerOne tenant named P1Prod to V6.0.1624.73941.
Switch-P1Tenant -Tenant P1Prod -Version 6.0.1624.73941
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant,
[string] $Version,
[string] $WebAppName,
[string] $LegacySite
)
Process
{
if ($Version -eq "") {
$VersionStr = "LAST"
} else {
$VersionStr = $Version
}
Write-Section "Switch tenant $Tenant to version $VersionStr"
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Type Get-P1Tenant for a list of tenants."
return
}
$TenantInfo = Get-P1Tenant $Tenant
$Adapter = $TenantInfo.Adapter
# Retro compatibility with legacy NAV tooling
if ($Adapter -eq "") {
$Adapter = "NAV"
}
$erp = $AdapterToERP.Get_Item($Adapter)
$packageSrvName = Get-PackageName $P1SrvPackage $erp
if ($Version -eq "") {
$package = Get-Package $packageSrvName
} else {
$package = Get-Package -Name $packageSrvName -RequiredVersion $Version
}
if ($package -eq $null) {
Write-Warning "Package $packageSrvName does not exist for version: $VersionStr."
Write-Warning "Call 'Get-Package $packageSrvName -AllVersion' to get a list of available package versions."
Write-Warning "Call Install-P1Package $packageSrvName to get last package version."
return
}
$packageWebName = Get-PackageName $P1WebPackage $erp
if ($Version -eq "") {
$package = Get-Package $packageWebName
} else {
$package = Get-Package -Name $packageWebName -RequiredVersion $Version
}
if ($package -eq $null) {
Write-Warning "Package $packageWebName does not exist for version: $VersionStr."
Write-Warning "Call 'Get-Package $packageWebName -AllVersion' to get a list of available package versions."
Write-Warning "Call Install-P1Package $packageWebName to get last package version."
return
}
$serviceName = Get-ServiceNameFromTenant $Tenant
$service = Get-Service -Name $serviceName
if ($service -eq $null) {
Write-Warning "Service $serviceName does not exist"
Write-Warning "Switch operation canceled"
return
}
if ($Version -eq "") {
$srvBinPath = Get-PackageFolder $packageSrvName
} else {
$srvBinPath = Get-PackageFolderForVersion $packageSrvName $Version
}
Write-Verbose "Server package folder is $srvBinPath"
$srvBinFolder = "AppServer"
#Test if service already exists
# Link folder to repository
$serverPath = $TenantInfo.Path
Write-Verbose "Server path is $serverPath"
if (!(Test-Path $serverPath)) {
Write-Warning "$serverPath does not exist."
Write-Warning "Switch operation canceled."
return
}
if ($LegacySite -eq "") {
$siteName = Get-SiteNameFromTenant $Tenant
} else {
Write-Verbose "Site name forced to $LegacySite"
$siteName = $LegacySite
}
if (!$WebAppName) {
$WebAppName = Get-WebAppNameFromTenant $Tenant
}
$sitePath = "$IISRootPath\$siteName"
$webAppPath = "$sitePath\$WebAppName"
Write-Verbose "Web app path is $webAppPath"
if ($Version -eq "") {
$webBinPath = Get-PackageFolder $packageWebName
} else {
$WebBinPath = Get-PackageFolderForVersion $packageWebName $Version
}
Write-Verbose "Web package folder is $webBinPath"
if (!(Test-Path $webAppPath)) {
Write-Warning "$webAppPath does not exist."
Write-Warning "Switch operation canceled."
return
}
$webApp = Get-P1WebApplication $Tenant
$poolName = $webApp.applicationPool
Write-Output "Stopping web application $poolName"
Stop-WebAppPool "$poolName"
Write-Output "Stopping service $serviceName"
Stop-ServiceAndProcess $serviceName
Write-Output "Switching server..."
Remove-Symlink $serverPath
New-Symlink $serverPath "$srvBinPath\$srvBinFolder"
Write-Output "Switching web application..."
Remove-Symlink $webAppPath
New-Symlink $webAppPath "$webBinPath\WebServer"
Restore-P1WebSecurity $Tenant
$logLevel = Get-P1LogLevel $Tenant
Write-Output "Reapplying log level configuration"
Set-P1LogLevel -Tenant $Tenant -Level $logLevel -NoPersist
Write-Output "Starting service..."
Start-Service $serviceName
Write-Output "Starting web application $poolName"
Start-WebAppPool "$poolName"
Write-OK "Tenant '$Tenant' switched"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Select-NAVInstance.ps1
|
Select-NAVInstance.ps1
|
function Select-NAVInstance {
<#
.Synopsis
Detect existing NAV instances and allow to select the target.
.Description
Will look for all NAV instances and propose to the user to select the good one for PlannerOne integration.
If there is only one instance, it will be selected automaticaly.
#>
[cmdletbinding()]
param (
)
Process
{
Initialize-NAVVersion
if ((Get-Command Get-NAVServerInstance -ErrorAction SilentlyContinue) -eq $null) {
Import-Module $DynamicsNavManagementModule | Out-Null
}
$NAVInstances = Get-NAVServerInstance
if ($NAVInstances.GetType().IsArray) {
$UsableInstances = Convert-NAVInstancesToArray $NAVInstances
[string[]] $instanceNames = @()
foreach ($instance in $UsableInstances) {
$instanceNames += $instance.InstanceName
}
$targetInstanceNumber = Show-Menu "Please choose the NAV instance in the following list" $instanceNames
$NAVInstance = $NAVInstances[$targetInstanceNumber]
$targetInstance = $UsableInstances[$targetInstanceNumber]
} else {
$NAVInstance = $NAVInstances
$xmlConfig = $NAVInstance | Get-NAVServerConfiguration -AsXml
$values = $xmlConfig.configuration.appSettings.add
$NAVServerInstance = ($values | Where-Object key -eq 'ServerInstance').value
$targetInstance = Get-NAVParametersFromConfig $NAVServerInstance $global:NAVVersionCode
}
while ($targetInstance.SOAPServicesEnabled -ne $true -or $targetInstance.ServicesDefaultTimeZone -ne "Server Time Zone") {
Write-Host $targetInstance.InstanceName
Write-Host $targetInstance.SOAPServicesEnabled
Write-Host $targetInstance.ServicesDefaultTimeZone
Write-Warning "Modify the instance settings so that:"
Write-Warning "- SOAP Services are enabled"
Write-Warning "- Services Default Time Zone is set to Server Time Zone"
Read-Host "Press enter when done"
$targetInstance = Get-NAVParametersFromConfig $targetInstance.InstanceName $global:NAVVersionCode
}
Write-Host "This instance is ready for PlannerOne!"
$global:NavInstance = $targetInstance.InstanceName
Write-Context
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Initialize-NAVVersion.ps1
|
Initialize-NAVVersion.ps1
|
function Initialize-NAVVersion {
<#
.Synopsis
Detect and initialize NAV Version on the local machine.
.Description
Will look for a NAV installation and will set some common variables in the session context.
#>
[cmdletbinding()]
param (
)
Process
{
$DynamicsNavParentFolder = "$env:ProgramFiles\Microsoft Dynamics NAV"
$DynamicsNavParentFolder86 = "${env:ProgramFiles(x86)}\Microsoft Dynamics NAV"
$DynamicsNavDataFolder = "$env:ProgramData\Microsoft\Microsoft Dynamics NAV"
if (Test-Path $DynamicsNavParentFolder) {
# read sub folders to find NavVersionCodes
$NavVersionCodes = Get-ChildItem $DynamicsNavParentFolder
if ($NavVersionCodes.Length -eq 1) {
[int]$global:NavVersionCode = [int] $NavVersionCodes[0].Name
Write-Output "Version code found: $NavVersionCode"
} elseif ($NavVersionCodes.Length -gt 1) {
Write-Warning "Multiple versions of Dynamics NAV detected ($NavVersionCodes)."
$maxVer = [int] $NavVersionCodes[0].Name
foreach ($ver in $NavVersionCodes) {
$newVer = [int] $ver.Name
if ($newVer -gt $maxVer) {
$maxVer = $newVer
}
}
$global:NavVersionCode = $maxVer
Write-Warning "The higher one ($maxVer) has been selected."
} else {
Write-Warning "Dynamics NAV is not installed on this host!"
}
} else {
Write-Warning "Dynamics NAV is not installed on this host!"
}
switch ($NavVersionCode) {
71 {
$global:NavVersion="2013R2"
$global:NavDefaultDatabase = 'Demo Database NAV (7-1)'
}
80 {
$global:NavVersion="2015"
$global:NavDefaultDatabase = 'Demo Database NAV (8-0)'
}
90 {
$global:NavVersion="2016"
$global:NavDefaultDatabase = 'Demo Database NAV (9-0)'
}
100 {
$global:NavVersion="2017"
$global:NavDefaultDatabase = 'Demo Database NAV (10-0)'
}
Default {
Write-Warning "This version is not supported: $NavVersionCode"
return
}
}
$global:NavDefaultInstance = "DynamicsNAV$NavVersionCode"
$global:NavDefaultCompanyName = 'CRONUS International Ltd.'
$global:NavDefaultLicencePath = "$DynamicsNavDataFolder\$NavVersionCode\Database\Cronus.flf"
Write-Output "The version $NavVersion of Microsoft Dynamics NAV has been detected."
if ($NavVersionCode -eq 71) {
$global:DynamicsNavManagementModule = "$DynamicsNavParentFolder\$NavVersionCode\Service\NavAdminTool.ps1"
} else {
$global:DynamicsNavManagementModule = "$DynamicsNavParentFolder\$NavVersionCode\Service\Microsoft.Dynamics.Nav.Management.psm1"
$global:DynamicsNavToolsModule = "$DynamicsNavParentFolder86\$NavVersionCode\RoleTailored Client\Microsoft.Dynamics.Nav.Model.Tools.psd1"
#Import-Module $DynamicsNavToolsModule
. "$DynamicsNavParentFolder86\$NAVVersionCode\RoleTailored Client\NavModelTools.ps1" -NavIde "$DynamicsNavParentFolder86\$NAVVersioncode\RoleTailored Client\finsql.exe" | Out-Null
Write-Output "The Microsoft Dynamics NAV Tools module has been imported."
}
Import-Module $DynamicsNavManagementModule
Write-Output "The Microsoft Dynamics NAV Management module has been imported."
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Import-P1Environment.ps1
|
Import-P1Environment.ps1
|
function Import-P1Environment {
<#
.Synopsis
Import PlannerOne environment from file.
.Description
Import an existing and initialized environment saved in file system.
Each environments found for Production Scheduler and ResourcePlanner will be imported.
.Parameter Tenant
The tenant name to import to.
.Parameter InDir
The root directory path to use for import. Default current.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant,
[string] $InDir
)
Process {
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
return
}
Write-Section "Importing environments..."
if ($InDir -eq "") {
$InDir = ".\"
}
if (!(Test-Path $InDir)) {
Write-Warning "Source directory does not exist"
return
}
$targetPath = Get-EnvironmentsPathFromTenant $Tenant
if (!(Test-Path $targetPath)) {
mkdir $targetPath | Out-Null
}
$sourcePath = $InDir + "\*"
Copy-Item -Recurse $sourcePath $targetPath -Force
Write-Section "Import finished"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/New-P1ServerInstance.ps1
|
New-P1ServerInstance.ps1
|
function New-P1ServerInstance {
<#
.Synopsis
Install a new PlannerOne service.
.Description
Install a new PlannerOne service with the given parameters.
.Parameter Tenant
The tenant name of this service.
.Parameter ERP
The adapter to use (NAV, AP, SAGE)
.Example
# Install a PlannerOne service for the tenant Prod.
New-P1ServerInstance -Tenant Prod -Login PlanAdm -Password MyPassword
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant,
[Parameter(Mandatory=$true)]
[string] $ERP
)
Process
{
Write-Section "Creating new server instance..."
$serviceName = Get-ServiceNameFromTenant $Tenant
$displayName = Get-ServiceDisplayNameFromTenant $Tenant
$servicePath = Get-ServicePath
$erpValid = Test-ERPName $ERP
if (!$erpValid) {
Write-Warning "$ERP is not a valid value"
Write-ERPNames
Write-Warning "Operation canceled"
return
}
$packageName = Get-PackageName $P1SrvPackage $ERP
$srvBinPath = Get-PackageFolder($packageName)
Write-Verbose "Server package folder is $srvBinPath"
$srvBinFolder = "AppServer"
#Test if service already exists
if (Test-ServiceExists($serviceName)) {
Write-Warning "Service $serviceName already exists!"
} else {
# Create folder for the service
if (!(Test-Path $servicePath)) {
mkdir $servicePath | Out-Null
}
# Link folder to repository
$serverPath = Get-ServerPathFromTenant $Tenant
New-Symlink $serverPath "$srvBinPath\$srvBinFolder"
Write-Verbose "Creating new PlannerOne service for Tenant $Tenant"
New-Service -Name $serviceName -BinaryPathName "$servicePath\$Tenant\$P1SrvExe" -DisplayName $displayName -StartupType Automatic | Out-Null
Start-Service -Name $serviceName
}
Write-OK "Server created"
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Set-P1AdapterParameter.ps1
|
Set-P1AdapterParameter.ps1
|
function Set-P1AdapterParameter {
<#
.Synopsis
Set one parameter for the adapter.
.Description
Set an adapter parameter by name.
Call Set-P1AdapterParameter with only the tenant name to get available parameters for it
Some names are specific to some adapters.
.Parameter Tenant
The target tenant.
.Parameter Name
The parameter name.
.Parameter Value
The parameter value.
.Example
# Set the SynchroniztionTick parameter to 5 seconds
Set-P1AdapterParameter -Tenant Prod -Name SynchronizationTick -Value 5
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant,
[string] $Name,
[string] $Value
)
Process
{
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return
}
$tenantInfo = Get-TenantInfo $Tenant
if ($tenantInfo -eq $null) {
Write-Warning "No tenant information available"
Write-Warning "Configuration canceled"
return
}
$adapterType = $tenantInfo.Adapter
if ($adapterType -eq "") {
Write-Warning "No adapter define for tenant $Tenant"
return
}
Write-Verbose "Adapter type is $adapterType"
if ($adapterType -ne "NAV" -and $adapterType -ne "REST" -and $adapterType -ne "AP") {
Write-Warning "Adapter type $adapterType is undefined or unrecognized"
return
}
if ($Name -eq "" -and $Value -eq "") {
if ($adapterType -eq "NAV") {
Write-NAVValidParameters
}
if ($adapterType -eq "REST") {
Write-RESTValidParameters
}
if ($adapterType -eq "AP") {
Write-APValidParameters
}
return
}
Write-Section "Set adapter parameter for tenant $Tenant, parameter $Name to value $Value"
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return;
}
if ($Name -eq "") {
Write-Warning "Parameter name must be set"
return;
}
if ($Value -eq "") {
Write-Warning "Parameter value must be set. Value must be true or false for boolean values."
return;
}
if ($adapterType -eq "NAV") {
Set-NAVAdapterParameter $Tenant $Name $Value
}
if ($adapterType -eq "REST") {
Set-RESTAdapterParameter $Tenant $Name $Value
}
if ($adapterType -eq "AP") {
Set-APAdapterParameter $Tenant $Name $Value
}
Write-Warning "You must restart the server to enable the new parameter."
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Import-P1NavTool.ps1
|
Import-P1NavTool.ps1
|
function Import-P1NavTool{
<#
.Synopsis
Import in local environnement the powershell module PlannerOne.NavTool.
.Description
Get the module from local package.
.Parameter Version
Dynamics NAV version.
#><#
param(
[Parameter(Mandatory=$True)] [string] $Version
)
$ModuleName = Get-Version $P1NavToolPackage $Version
$path = Get-PackageFolder $ModuleName
$modRepo = "$env:SystemDrive\Program Files\WindowsPowerShell\Modules"
Copy-item "$path\PlannerOne.NavTool\" "$modRepo" -recurse -Force
Write-host "copy $path in $modRepo"
Import-module "PlannerOne.NavTool" -force
Write-OK "Import Module PlannerOne.NavTool done.."
Dynamics NAV version.
#>
param(
[Parameter(Mandatory=$True)] [string] $Version
)
$ModuleName = Get-Version $P1NavToolPackage $Version
$path = Get-PackageFolder $ModuleName
$getVal = $false
foreach($modRepo in $ENV:PSModulePath.split(";"))
{
if($modRepo.Contains($HOME)){
$getVal = $true
break
}
}
if(! $getVal){
Write-Verbose "No PSModule folder for this user. "
$modRepo = $ENV:PSModulePath.split(";")[0]
}
Copy-item "$path\PlannerOne.NavTool\" "$modRepo" -recurse -force
Write-host "copy $path in $modRepo"
Import-module "PlannerOne.NavTool" -force
Write-OK "Import Module PlannerOne.NavTool done.."
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Export-P1LegacyEnvironment.ps1
|
Export-P1LegacyEnvironment.ps1
|
function Export-P1LegacyEnvironment {
<#
.Synopsis
Export legacy PlannerOne environment to file.
.Description
Export an existing and initialized legacy environment stored in a database and save it to file system.
Each environments found for Production Scheduler and ResourcePlanner will be exported in its own file in -OutDir directory.
.Parameter SQLServer
The SQL Server host name and instance.
.Parameter Database
The SQL Server database name.
.Parameter OutDir
The root directory path to use for export. .\p1EnvExport by default.
.Parameter ForceDatatableName
Force datatable name to export. By default script will export sequentially dbo.EnvironmentProductionDao and dbo.EnvironmentProjectDao.
.Parameter Product
Select product to export environment from.
Valid values are: Production, Projects, All.
Default value is All.
All option cannot be used with ForceDatatableName.
.Parameter UseUIdAsName
Do not try to retrieve Planning name and Planning Group Container to create directories.
Use environment UId.
Use this option if environments names are not valid for directory names.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $SQLServer,
[Parameter(Mandatory=$true)]
[string] $Database,
[string] $OutDir,
[string] $ForceDatatableName,
[string] $Product,
[switch] $UseUIdAsName
)
Process {
if ($Product -eq "") {
$Product = "All"
}
if ($Product -ne "Production" -and $Product -ne "Project" -and $Product -ne "All") {
Write-Warning "Valid values for -Product are: Production, Project, All"
Write-Warning "Operation canceled."
return
}
$currentDir = (Get-Item -Path ".\").FullName
if ($OutDir -eq "") {
$OutDir = $currentDir + "\p1EnvExport"
} else {
$rooted = [System.IO.Path]::IsPathRooted($OutDir)
if ($rooted -eq $false) {
$OutDir = $currentDir + "\" + $OutDir
}
}
Write-Verbose "OutDir is $OutDir"
$connectionString = Get-ConnectionString -Server $SQLServer -Database $Database -IntegratedSecurity "true"
if ($ForceDatatableName -eq "") {
if ($Product -eq "Production" -or $Product -eq "All") {
$PSDir = $OutDir + "\Production"
Write-Section "Production Scheduler environments"
Export-DBEnvironments -connectionString $connectionString -dataTable "dbo.EnvironmentProductionDao" -OutDir $PSDir -useUId:$UseUIdAsName
}
if ($Product -eq "Project" -or $Product -eq "All") {
$RPDir = $OutDir + "\Project"
Write-Section "Resource Planner environments"
Export-DBEnvironments -connectionString $connectionString -dataTable "dbo.EnvironmentProjectDao" -OutDir $RPDir -useUId:$UseUIdAsName
}
} else {
if ($Product -eq "All") {
Write-Warning "Product cannot be All with ForceDatatableName option"
Write-Warning "Operation canceled."
return;
}
Write-Verbose "Reading $ForceDatatableName environments..."
Export-DBEnvironments -connectionString $connectionString -dataTable $ForceDatatableName -OutDir $OutDir -useUId:$UseUIdAsName
}
}
}
|
PowerShellCorpus/PowerShellGallery/PlannerOne.Deployment/1.0.151/Public/Get-P1WebSecurity.ps1
|
Get-P1WebSecurity.ps1
|
function Get-P1WebSecurity {
<#
.Synopsis
Get the PlannerOne web security for tenant.
.Description
Get the PlannerOne web security for tenant.
.Parameter Tenant
The tenant name.
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Tenant
)
Process
{
if (!(Test-Tenant $Tenant)) {
Write-Warning "Tenant $Tenant does not exist."
Write-Warning "Operation canceled."
return
}
$ssl = Get-SSLConf $Tenant
if ($ssl -eq $null) {
$ssl = "false"
}
Write-Output "SSL: $ssl"
$authentication = Get-AuthenticationConf $Tenant
if ($authentication -eq $null) {
$authentication = "Windows"
}
Write-Output "Authentication: $authentication"
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.