full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/RBAC.ps1
|
RBAC.ps1
|
using namespace Microsoft.Azure.Commands.Resources.Models.Authorization
using namespace System.Management.Automation
Set-StrictMode -Version Latest
# Class to implement Subscription RBAC controls
class RBAC: CommandBase
{
hidden [SubscriptionRBAC] $Policy = $null;
hidden [PSRoleAssignment[]] $RoleAssignments = $null;
hidden [ActiveRBACAccount[]] $ApplicableActiveAccounts = $null;
hidden [ActiveRBACAccount[]] $MissingActiveAccounts = $null;
hidden [RBACAccountRoleMapping[]] $MatchedActiveAccounts = $null;
hidden [RBACAccountRoleMapping[]] $MatchedDeprecatedAccounts = $null;
RBAC([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags):
Base($subscriptionId, $invocationContext)
{
$this.Policy = [SubscriptionRBAC] $this.LoadServerConfigFile("Subscription.RBAC.json");
$this.FilterTags = $this.ConvertToStringArray($tags) | Select-Object -Unique;
}
hidden [PSRoleAssignment[]] GetRoleAssignments()
{
if(-not $this.RoleAssignments)
{
$this.RoleAssignments = [RoleAssignmentHelper]::GetAzSDKRoleAssignment($true, $true);
}
return $this.RoleAssignments;
}
hidden [ActiveRBACAccount[]] GetApplicableActiveAccounts()
{
if($null -eq $this.ApplicableActiveAccounts)
{
$this.ApplicableActiveAccounts = @();
$subscriptionId = $this.SubscriptionContext.SubscriptionId;
if(($this.FilterTags | Measure-Object).Count -ne 0)
{
$this.Policy.ValidActiveAccounts |
ForEach-Object {
$currentItem = $_;
if(($currentItem.Tags | Where-Object { $this.FilterTags.Contains($_) } | Measure-Object).Count -ne 0)
{
# Resolve the value of SubscriptionId
$currentItem.Scope = $global:ExecutionContext.InvokeCommand.ExpandString($currentItem.Scope);
if([string]::IsNullOrWhiteSpace($currentItem.Scope))
{
$currentItem.Scope = "/subscriptions/$subscriptionId"
}
$this.ApplicableActiveAccounts += $currentItem;
}
}
}
}
return $this.ApplicableActiveAccounts;
}
hidden [void] LoadActiveAccountStatus()
{
$this.MissingActiveAccounts = @();
$this.MatchedActiveAccounts = @();
$this.GetApplicableActiveAccounts() | Where-Object { $_.Enabled } |
ForEach-Object {
$currentItem = $_;
$matchedAccount = $this.GetRoleAssignments() |
Where-Object {
($_.ObjectId -eq $currentItem.ObjectId) -and
($_.Scope -eq $currentItem.Scope) -and
($_.RoleDefinitionName -eq $currentItem.RoleDefinitionName)
} | Select-Object -First 1
if($matchedAccount)
{
$this.MatchedActiveAccounts += [RBACAccountRoleMapping]@{
RoleAssignment = $matchedAccount;
RBACAccount = $currentItem;
};
}
else
{
$this.MissingActiveAccounts += $currentItem;
}
};
}
hidden [void] LoadDeprecatedAccountStatus()
{
$this.MatchedDeprecatedAccounts = @();
$this.Policy.DeprecatedAccounts | Where-Object { $_.Enabled } |
ForEach-Object {
$currentItem = $_;
$matchedAccounts = $this.GetRoleAssignments() |
Where-Object { ($_.ObjectId -eq $currentItem.ObjectId) };
if(($matchedAccounts | Measure-Object).Count -ne 0)
{
$matchedAccounts | ForEach-Object {
$this.MatchedDeprecatedAccounts += [RBACAccountRoleMapping]@{
RoleAssignment = $_;
RBACAccount = $currentItem;
};
};
}
};
}
[MessageData[]] SetRBACAccounts()
{
[MessageData[]] $messages = @();
# Set Active accounts
$nonConfiguredActiveAccounts = $this.GetNonConfiguredActiveAccounts(([ref]$messages));
if($nonConfiguredActiveAccounts.Count -ne 0)
{
$provisionAccounts = @();
$provisionAccounts += $nonConfiguredActiveAccounts | Where-Object { $_.Type -eq [RBACAccountType]::Provision };
if($provisionAccounts.Count -ne 0)
{
# Adding Central Accounts
$messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following active accounts to the subscription. Total accounts: $($provisionAccounts.Count)", $provisionAccounts);
$errorCount = 0;
$currentCount = 0;
$provisionAccounts | ForEach-Object {
$accountName = $_.Name;
$currentCount += 1;
# Add account
try
{
$this.PublishCustomMessage("Adding account [$accountName] to the subscription");
New-AzureRmRoleAssignment -ObjectId $_.ObjectId -Scope $_.Scope -RoleDefinitionName $_.RoleDefinitionName -ErrorAction Stop | Out-Null
}
catch
{
$messages += [MessageData]::new("Error while adding account [$accountName] to the subscription", $_, [MessageType]::Error);
$errorCount += 1;
}
$this.CommandProgress($provisionAccounts.Count, $currentCount, 5);
};
[MessageData[]] $resultMessages = @();
if($errorCount -eq 0)
{
$resultMessages += [MessageData]::new("All required active accounts have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
}
elseif($errorCount -eq $provisionAccounts.Count)
{
$resultMessages += [MessageData]::new("No accounts have been added to the subscription due to error occured. Please add the accounts manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
}
else
{
$resultMessages += [MessageData]::new("[$errorCount] required active accounts have not been added to the subscription. Please add the accounts manually.", [MessageType]::Error);
$resultMessages += [MessageData]::new("[$($provisionAccounts.Count - $errorCount)] required active accounts have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
}
$messages += $resultMessages;
$this.PublishCustomMessage($resultMessages);
}
$nonProvisionAccounts = @();
$nonProvisionAccounts += $nonConfiguredActiveAccounts | Where-Object { $_.Type -ne [RBACAccountType]::Provision };
if($nonProvisionAccounts.Count -ne 0)
{
$messageText = "Some accounts are not added to the subscription, since the account type is not set to 'Provision' in RBAC policy file. Total accounts: $($nonProvisionAccounts.Count)";
$messages += [MessageData]::new($messageText, $nonProvisionAccounts);
$this.PublishCustomMessage($messageText);
}
}
else
{
}
# Remove deprecated accounts
$depAccounts = $this.GetMatchedDeprecatedAccounts(([ref]$messages));
$messages += $this.RemoveRoleAssignments($depAccounts);
return $messages;
}
[ActiveRBACAccount[]] GetNonConfiguredActiveAccounts([ref]$messages)
{
if($this.Policy.ValidActiveAccounts.Count -ne 0)
{
if($this.GetApplicableActiveAccounts().Count -ne 0)
{
$startMessage = [MessageData]::new("Processing RBAC rules for adding central accounts. Tags:[$([string]::Join(",", $this.FilterTags))]. Total accounts: $($this.GetApplicableActiveAccounts().Count)");
$messages.Value += $startMessage;
$this.PublishCustomMessage($startMessage);
$disabledAccounts = $this.GetApplicableActiveAccounts() | Where-Object { -not $_.Enabled };
if(($disabledAccounts | Measure-Object).Count -ne 0)
{
$disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
$messages.Value += [MessageData]::new($disabledMessage, $disabledAccounts);
$this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
}
# Load all properties
$this.LoadActiveAccountStatus();
if($this.MatchedActiveAccounts.Count -ne 0)
{
$messages.Value += [MessageData]::new("Following accounts have correct RBAC configured. Total accounts: $($this.MatchedActiveAccounts.Count)", ($this.MatchedActiveAccounts | Select-Object -Property RoleAssignment));
}
if($this.MissingActiveAccounts.Count -ne 0)
{
$missingAccountsMessage = "Following accounts does not have correct RBAC configured. Total accounts: $($this.MissingActiveAccounts.Count)";
$messages.Value += [MessageData]::new($missingAccountsMessage, $this.MissingActiveAccounts);
$this.PublishCustomMessage($missingAccountsMessage);
}
else
{
$successMessage = [MessageData]::new("All required accounts are correctly configured");
$messages.Value += $successMessage;
$this.PublishCustomMessage($successMessage);
}
return $this.MissingActiveAccounts;
}
else
{
$this.PublishCustomMessage("No active accounts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
}
}
else
{
$this.PublishCustomMessage("No active accounts found in the RBAC policy file", [MessageType]::Warning);
}
return @();
}
[RBACAccountRoleMapping[]] GetMatchedDeprecatedAccounts([ref]$messages)
{
if($this.Policy.DeprecatedAccounts -and $this.Policy.DeprecatedAccounts.Count -ne 0)
{
$this.PublishCustomMessage("Found deprecated accounts in the RBAC policy file");
$startMessage = [MessageData]::new("Processing RBAC rules for removing deprecated central accounts. Total accounts: $($this.Policy.DeprecatedAccounts.Count)");
$messages.Value += $startMessage;
$this.PublishCustomMessage($startMessage);
$disabledAccounts = $this.Policy.DeprecatedAccounts | Where-Object { -not $_.Enabled };
if(($disabledAccounts | Measure-Object).Count -ne 0)
{
$disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
$messages.Value += [MessageData]::new($disabledMessage, $disabledAccounts);
$this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
}
# Load all properties
$this.LoadDeprecatedAccountStatus();
if($this.MatchedDeprecatedAccounts.Count -ne 0)
{
$messages.Value += [MessageData]::new("Following deprecated accounts must be removed from the subscription. Total accounts: $($this.MatchedDeprecatedAccounts.Count)", ($this.MatchedDeprecatedAccounts | Select-Object -Property RoleAssignment));
}
else
{
$resultMessage = [MessageData]::new("No deprecated accounts found on the subscription");
$messages.Value += $resultMessage;
$this.PublishCustomMessage($resultMessage);
}
return $this.MatchedDeprecatedAccounts;
}
else
{
$this.PublishCustomMessage("No deprecated accounts found in the RBAC policy file");
}
return @();
}
[MessageData[]] RemoveRBACAccounts()
{
[MessageData[]] $messages = @();
if($this.Policy.ValidActiveAccounts.Count -ne 0)
{
if($this.GetApplicableActiveAccounts().Count -ne 0)
{
$startMessage += [MessageData]::new("Processing RBAC rules for removing central accounts. Tags:[$([string]::Join(",", $this.FilterTags))]. Total accounts: $($this.GetApplicableActiveAccounts().Count)");
$messages += $startMessage;
$this.PublishCustomMessage($startMessage);
$disabledAccounts = $this.GetApplicableActiveAccounts() | Where-Object { -not $_.Enabled };
if(($disabledAccounts | Measure-Object).Count -ne 0)
{
$disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
$messages += [MessageData]::new($disabledMessage, $disabledAccounts);
$this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
}
# Load all properties
$this.LoadActiveAccountStatus();
$messages += $this.RemoveRoleAssignments($this.MatchedActiveAccounts);
}
else
{
$this.PublishCustomMessage("No active accounts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
}
}
else
{
$this.PublishCustomMessage("No active accounts found in the RBAC policy file", [MessageType]::Warning);
}
return $messages;
}
hidden [MessageData[]] RemoveRoleAssignments([RBACAccountRoleMapping[]] $rbacRoleMapping)
{
[MessageData[]] $messages = @();
if($rbacRoleMapping.Count -ne 0)
{
$messages += [MessageData]::new("Total matching accounts found in the subscription: $($rbacRoleMapping.Count)");
$provisionAccounts = @();
$provisionAccounts += $rbacRoleMapping | Where-Object { $_.RBACAccount.Type -eq [RBACAccountType]::Provision };
if($provisionAccounts.Count -ne 0)
{
# Removing Central Accounts
$messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following accounts from the subscription. Total accounts: $($provisionAccounts.Count)", ($provisionAccounts | Select-Object -Property RoleAssignment));
$errorCount = 0;
$currentCount = 0;
$provisionAccounts | ForEach-Object {
$accountName = $_.RoleAssignment.DisplayName;
$currentCount += 1;
if(-not [string]::IsNullOrWhiteSpace($_.RoleAssignment.SignInName))
{
$accountName += " ($($_.RoleAssignment.SignInName))";
}
# Remove account
try
{
$this.PublishCustomMessage("Removing account [$accountName] from the subscription");
Remove-AzureRmRoleAssignment -ObjectId $_.RoleAssignment.ObjectId -Scope $_.RoleAssignment.Scope -RoleDefinitionId $_.RoleAssignment.RoleDefinitionId -ErrorAction Stop | Out-Null
}
catch
{
$messages += [MessageData]::new("Error while removing account [$accountName] from the subscription", $_, [MessageType]::Error);
$errorCount += 1;
}
$this.CommandProgress($provisionAccounts.Count, $currentCount, 5);
};
[MessageData[]] $resultMessages = @();
if($errorCount -eq 0)
{
$resultMessages += [MessageData]::new("All matched accounts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
}
elseif($errorCount -eq $provisionAccounts.Count)
{
$resultMessages += [MessageData]::new("No accounts have been removed from the subscription due to error occured. Please remove the accounts manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
}
else
{
$resultMessages += [MessageData]::new("[$errorCount] matched accounts have not been removed from the subscription. Please remove the accounts manually.", [MessageType]::Error);
$resultMessages += [MessageData]::new("[$($provisionAccounts.Count - $errorCount)] matched accounts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
}
$messages += $resultMessages;
$this.PublishCustomMessage($resultMessages);
}
$nonProvisionAccounts = @();
$nonProvisionAccounts += $rbacRoleMapping | Where-Object { $_.RBACAccount.Type -ne [RBACAccountType]::Provision };
if($nonProvisionAccounts.Count -ne 0)
{
$messageText = "Some accounts are not removed from the subscription, since the account type is not set to 'Provision' in RBAC policy file. Total accounts: $($nonProvisionAccounts.Count)";
$messages += [MessageData]::new($messageText, ($nonProvisionAccounts | Select-Object -Property RoleAssignment));
$this.PublishCustomMessage($messageText);
}
}
return $messages;
}
}
class RBACAccountRoleMapping
{
hidden [PSRoleAssignment] $RoleAssignment = $null;
hidden [RBACAccount] $RBACAccount = $null;
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/SecurityCenter.ps1
|
SecurityCenter.ps1
|
using namespace System.Management.Automation
Set-StrictMode -Version Latest
class SecurityCenter: AzSdkRoot
{
[PSObject] $Policy = $null;
[string] $Off = "Off";
[string] $On = "On";
SecurityCenter([string] $subscriptionId):
Base($subscriptionId)
{
$this.Policy = $this.LoadServerConfigFile("SecurityCenter.json");
}
[PSObject[]] GetMisconfiguredPolicies()
{
$misConfiguredPolicies = @();
$allPolicies = @();
$allPolicies += [SecurityCenterHelper]::InvokeGetSecurityCenterRequest($this.SubscriptionContext.SubscriptionId, [SecurityCenterHelper]::PoliciesApi)
if($allPolicies.Count -ne 0)
{
#Query to select only subscription level polices and other polices which are modified explicitly
$uniquePolicies = @();
$uniquePolicies += $allPolicies | Where-Object {
$_.properties.policyLevel -eq "Subscription" -or
$_.properties.unique -eq $this.On
};
if($uniquePolicies.Count -ne 0)
{
#If recommendations object is kept blank in Policy json, consider to check all properties to be 'On'
#Check with get-member here
if(($this.Policy.properties.recommendations | Get-Member -MemberType Properties | Measure-Object).Count -eq 0)
{
#Pick first object and add all recommendation property to policy json object
$samplePolicy = $allPolicies | Select-Object -First 1
if([Helpers]::CheckMember($samplePolicy, "properties.recommendations"))
{
$samplePolicy.properties.recommendations | Get-Member -MemberType Properties |
ForEach-Object {
Add-Member -InputObject $this.Policy.properties.recommendations -MemberType NoteProperty -Name $_.Name -Value $this.On
}
}
}
$uniquePolicies | ForEach-Object {
$isMisconfigured = $true;
if([Helpers]::CompareObject($this.Policy.properties, $_.properties))
{
# Check for email address and phone nnumber props
if([Helpers]::CheckMember($_, "properties.securityContactConfiguration.securityContactEmails") -and
-not [string]::IsNullOrEmpty($_.properties.securityContactConfiguration.securityContactEmails) -and
[Helpers]::CheckMember($_, "properties.securityContactConfiguration.securityContactPhone") -and
-not [string]::IsNullOrEmpty($_.properties.securityContactConfiguration.securityContactPhone))
{
$isMisconfigured = $false
}
}
if($isMisconfigured)
{
$misConfiguredPolicies += $_;
}
};
$misConfiguredPolicies += $uniquePolicies | Where-Object { -not [Helpers]::CompareObject($this.Policy.properties, $_.properties) };
}
else
{
#no relevant policies found message here
$this.PublishCustomMessage("No Subsciption level or uniquely configured policies found in the Security Center", [MessageType]::Warning);
}
}
else
{
#Error message here
$this.PublishCustomMessage("Not able to get the Security Center policies", [MessageType]::Error);
}
return $misConfiguredPolicies;
}
[MessageData[]] SetPolicies([string] $securityContactEmails, [string] $securityPhoneNumber)
{
[MessageData[]] $messages = @();
$misConfiguredPolicies = $this.GetMisconfiguredPolicies();
if($misConfiguredPolicies.Count -ne 0)
{
$messageText = "Found Security Center policies which are not correctly configured. Updating the policies. Total: $($misConfiguredPolicies.Count)";
$messages += [MessageData]::new("Security center policies must be configured with settings mentioned below:", $this.Policy.properties);
$messages += [MessageData]::new($messageText, $misConfiguredPolicies);
$this.PublishCustomMessage($messageText);
#Keeping a copy of policy email addresses. The original policy object is going to update while merging email addresses
$policyEmails = @();
if([Helpers]::CheckMember($this.Policy, "properties.securityContactConfiguration.securityContactEmails"))
{
$policyEmails += $this.Policy.properties.securityContactConfiguration.securityContactEmails;
}
$updateObject = $this.Policy | Select-Object -Property properties
$misConfiguredPolicies | Where-Object { $_.properties.policyLevel -eq "Subscription" } | ForEach-Object {
#Merge email addresses
$allEmails = @();
# User provided email addresses
$allEmails += $this.ConvertToStringArray($securityContactEmails);
# Ignore existing email addresses if user has provided any email addresses
if($allEmails.Count -eq 0 -and $_.properties.securityContactConfiguration.securityContactEmails.Count -ne 0)
{
$allEmails += $_.properties.securityContactConfiguration.securityContactEmails | Where-Object { -not [string]::IsNullOrWhiteSpace($_) };
}
# Add email addresses from policy files
$allEmails += $policyEmails;
$updateObject.properties.securityContactConfiguration.securityContactEmails = [array] ($allEmails | Select-Object -Unique)
$policyName = "";
if([Helpers]::CheckMember($_, "name"))
{
$policyName = "[$($_.name)]";
}
$exceptionMessage = "";
# Check if securityContactEmails is still null, then set it to blank array
if(-not $updateObject.properties.securityContactConfiguration.securityContactEmails)
{
$exceptionMessage += "Please provide 'SecurityContactEmails' parameter in the command to set up security center policy $policyName`r`n";
$updateObject.properties.securityContactConfiguration.securityContactEmails = @("");
}
$isPhoneRequired = $true;
if([Helpers]::CheckMember($_, "properties.securityContactConfiguration.securityContactPhone"))
{
if(-not [string]::IsNullOrEmpty($_.properties.securityContactConfiguration.securityContactPhone))
{
$isPhoneRequired = $false;
}
}
if($isPhoneRequired -and [string]::IsNullOrWhiteSpace($securityPhoneNumber))
{
$exceptionMessage += "Please provide 'SecurityPhoneNumber' parameter in the command to set up security center policy $policyName`r`n";
}
if(-not [string]::IsNullOrWhiteSpace($exceptionMessage))
{
throw $exceptionMessage;
}
# Set phone number
if(-not [string]::IsNullOrWhiteSpace($securityPhoneNumber))
{
Add-Member -InputObject $updateObject.properties.securityContactConfiguration -MemberType NoteProperty -Name "securityContactPhone" -Value $securityPhoneNumber
}
$messages += [MessageData]::new("Updating [$($_.properties.policyLevel)] level security center policy $policyName");
$response = [SecurityCenterHelper]::InvokePutSecurityCenterRequest($_.id, $updateObject);
[MessageData] $resultMessage = $null
if(($response | Measure-Object).Count -ne 0)
{
$resultMessage = [MessageData]::new("Successfully updated [$($_.properties.policyLevel)] level security center policy $policyName", [MessageType]::Update);
}
else
{
$resultMessage = [MessageData]::new("Not able to update [$($_.properties.policyLevel)] level security center policy $policyName", [MessageType]::Error);
}
$messages += $resultMessage;
$this.PublishCustomMessage($resultMessage);
}
#Setting up the original values
$this.Policy.properties.securityContactConfiguration.securityContactEmails = $policyEmails;
$nonDefaultPolicies = $misConfiguredPolicies | Where-Object { $_.properties.unique -eq $this.On } | Select-Object -Property id, name
if(($nonDefaultPolicies | Measure-Object).Count -ne 0)
{
$messageText = "Found policies at resource group level in overridden state. These policies have to be manually setup correctly. Total: $($nonDefaultPolicies.Count)";
$messages += [MessageData]::new($messageText + "`r`nBelow are the policies that have to be manually corrected: ",
$nonDefaultPolicies);
$this.PublishCustomMessage($messageText);
}
}
else
{
$this.PublishCustomMessage("All security center policies are correctly configured. No changes are required.");
}
return $messages;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Configurations/ContinuousAssurance/Continuous_Assurance_Runbook.ps1
|
Continuous_Assurance_Runbook.ps1
|
function Set-Modules
{
param(
[System.Collections.IDictionary] $ModuleList,
[string[]] $SyncModuleList
)
$ModuleList.Keys | ForEach-Object{
$ModuleName = $_
$ModuleVersion = $ModuleList.Item($_)
$Module = Get-AzureRmAutomationModule `
-ResourceGroupName $AutomationAccountRG `
-AutomationAccountName $AutomationAccountName `
-Name $ModuleName -ErrorAction SilentlyContinue
if(($Module | Measure-Object).Count -eq 0)
{
#Download module if it is not available
DownloadModule -ModuleName $ModuleName -ModuleVersion $ModuleVersion -Sync ($SyncModuleList.Contains($ModuleName))
}
else
{
#module is in extraction state
if($Module.ProvisioningState -ne "Failed" -and $Module.ProvisioningState -ne "Succeeded" -and $Module.ProvisioningState -ne "Created")
{
"Current provisioning state for module $ModuleName is $($Module.ProvisioningState)"
}
#Check if module with specified version already exists
elseif(CheckModuleVersion -ModuleName $ModuleName -ModuleVersion $ModuleVersion)
{
$ModuleName + " is updated in assets"
return
}
else
{
#Download required version
DownloadModule -ModuleName $ModuleName -ModuleVersion $ModuleVersion -Sync ($SyncModuleList.Contains($ModuleName))
}
}
}
}
function DownloadModule
{
param(
[string]$ModuleName,
[string]$ModuleVersion,
[bool] $Sync
)
$SearchResult = SearchModule -ModuleName $ModuleName -ModuleVersion $ModuleVersion
if($SearchResult)
{
$ModuleName = $SearchResult.title.'#text' # get correct casing for the Module name
$PackageDetails = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $SearchResult.id
$ModuleVersion = $PackageDetails.entry.properties.version
#Build the content url for the nuget package
$ModuleContentUrl = "$PowershellGalleryUrl/api/v2/package/$ModuleName/$ModuleVersion"
# Find the actual blob storage location of the Module
do {
$ActualUrl = $ModuleContentUrl
$ModuleContentUrl = (Invoke-WebRequest -Uri $ModuleContentUrl -MaximumRedirection 0 -UseBasicParsing -ErrorAction Ignore).Headers.Location
} while($null -ne $ModuleContentUrl)
$AutomationModule = New-AzureRmAutomationModule `
-ResourceGroupName $AutomationAccountRG `
-AutomationAccountName $AutomationAccountName `
-Name $ModuleName `
-ContentLink $ActualUrl
"Downloading "+ $ModuleName + " , version:-" + $ModuleVersion
if($Sync)
{
while(
$AutomationModule.ProvisioningState -ne "Created" -and
$AutomationModule.ProvisioningState -ne "Succeeded" -and
$AutomationModule.ProvisioningState -ne "Failed"
)
{
#Module is in extracting state
Start-Sleep -Seconds 120
$AutomationModule = $AutomationModule | Get-AzureRmAutomationModule
}
if($AutomationModule.ProvisioningState -eq "Failed")
{
Write-Error "Importing $AutomationModule Module to Automation failed."
}
}
}
}
function CheckModuleVersion
{
param(
[string] $ModuleName,
[string] $ModuleVersion
)
$SearchResult = SearchModule -ModuleName $ModuleName -ModuleVersion $ModuleVersion
$Module = Get-AzureRmAutomationModule `
-ResourceGroupName $AutomationAccountRG `
-AutomationAccountName $AutomationAccountName `
-Name $ModuleName -ErrorAction SilentlyContinue
if(($Module | Measure-Object).Count -eq 0)
{
#Module is not available
return $false
}
else
{
#added condition to return false if module is not succcessfully extracted
return ((($Module.ProvisioningState -eq "Succeeded") -or ($Module.ProvisioningState -eq "Created")) -and ($SearchResult.properties.Version -eq $Module.Version))
}
}
function SearchModule
{
param(
[string] $ModuleName,
[string] $ModuleVersion
)
$url =""
if([string]::IsNullOrWhiteSpace($ModuleVersion))
{
$queryString = "`$filter=IsLatestVersion&searchTerm=%27$ModuleName%27&includePrerelease=false&`$skip=0&`$top=40"
$url = "$PowershellGalleryUrl/api/v2/Search()?$queryString"
}
else
{
$queryString = "id=%27$ModuleName%27&`$skip=0&`$top=40"
$url = "$PowershellGalleryUrl/api/v2/FindPackagesById()?$queryString"
}
$SearchResult = Invoke-RestMethod -Method Get -Uri $url -UseBasicParsing
if(!$SearchResult)
{
Write-Error "Could not find Module '$ModuleName'"
return $null
}
else
{
$SearchResult = $SearchResult | Where-Object -FilterScript {
return $_.title.'#text' -eq $ModuleName
}
#filter for module version
if(![string]::IsNullOrWhiteSpace($ModuleVersion)) {
$SearchResult = $SearchResult | Where-Object -FilterScript {
return $_.properties.version -eq $ModuleVersion
}
}
return $SearchResult
}
}
function AddDependentModules
{
param(
$InputModuleList
)
$InputModuleList.Keys | ForEach-Object{
$moduleName = $_
$moduleVersion = $InputModuleList.Item($_)
$searchResult = SearchModule -ModuleName $moduleName -ModuleVersion $moduleVersion
if($searchResult)
{
$packageDetails = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $searchResult.id
$dependencies = $packageDetails.entry.properties.dependencies
if($dependencies)
{
$dependencies = $dependencies.Split("|")
# parse depencencies, which are in the format: Module1name:[Module1version]:|Module2name:[Module2version]
for($index=$dependencies.count-1;($index -ge 0) -and (![string]::IsNullOrWhiteSpace($dependencies[$index]));$index--)
{
$dependencyModuleDetail = $dependencies[$index].Split(":")
$dependencyModuleName = $dependencyModuleDetail[0]
$dependencyModuleVersion = $dependencyModuleDetail[1].Replace('[','').Replace(']','')
#Add dependent module to the result list
if(!$ResultModuleList.Contains($dependencyModuleName))
{
$tempList = [ordered]@{$dependencyModuleName=$dependencyModuleVersion}
$tempList+= $ResultModuleList
$ResultModuleList.Clear()
$tempList.Keys|ForEach-Object{$ResultModuleList.Add($_,$tempList.Item($_))}
AddDependentModules -InputModuleList @{$dependencyModuleName=$dependencyModuleVersion} | Out-Null
}
}
}
if(!$ResultModuleList.Contains($moduleName))
{
if([string]::IsNullOrWhiteSpace($moduleVersion))
{
$moduleVersion = $searchResult.properties.Version
}
$ResultModuleList.Add($moduleName,$moduleVersion)
}
}
}
return $ResultModuleList
}
function ReLinkAllSchedules()
{
$allRunbookSchedules = @();
$allRunbookSchedules += Get-AzureRmAutomationScheduledRunbook -AutomationAccountName $AutomationAccountName -ResourceGroupName $AutomationAccountRG -RunbookName $RunbookName -ErrorAction SilentlyContinue
if($allRunbookSchedules.Count -ne 0)
{
# Filter schedules of AzSDK runbook
$allRunbookSchedules | Where-Object { $_.ScheduleName -ne $NextRunScheduleName -and $_.RunbookName -eq $RunbookName} |
ForEach-Object {
Unregister-AzureRmAutomationScheduledRunbook -RunbookName $_.RunbookName -ScheduleName $_.ScheduleName `
-ResourceGroupName $_.ResourceGroupName `
-AutomationAccountName $_.AutomationAccountName -ErrorAction Stop -Force | Out-Null
Register-AzureRmAutomationScheduledRunbook -RunbookName $_.RunbookName -ScheduleName $_.ScheduleName `
-ResourceGroupName $_.ResourceGroupName `
-AutomationAccountName $_.AutomationAccountName -ErrorAction Stop| Out-Null
};
"Relinked runbook"
}
else
{
# Create new Next run schedule
CreateNextRunSchedule
}
}
function CreateNextRunSchedule()
{
#create next run schedule
Get-AzureRmAutomationSchedule -AutomationAccountName $AutomationAccountName `
-ResourceGroupName $AutomationAccountRG -Name $NextRunScheduleName -ErrorAction SilentlyContinue | Remove-AzureRmAutomationSchedule -Force
New-AzureRmAutomationSchedule -AutomationAccountName $AutomationAccountName -Name $NextRunScheduleName `
-ResourceGroupName $AutomationAccountRG -StartTime $(get-date).AddMinutes(10) `
-OneTime -ErrorAction Stop | Out-Null
Register-AzureRmAutomationScheduledRunbook -RunbookName $RunbookName -ScheduleName $NextRunScheduleName `
-ResourceGroupName $AutomationAccountRG `
-AutomationAccountName $AutomationAccountName -ErrorAction Stop | Out-Null
"Scheduled next run"
}
function ConvertStringToBoolean($strToConvert)
{
switch($strToConvert)
{
"true" {return $true}
"false" {return $false}
}
return $false #adding this to prevent error all path doesn't return value"
}
function GetCCStatus()
{
Set-AzSDKOMSSettings -OMSWorkspaceID $OMSWorkspaceId -OMSSharedKey $OMSWorkspaceSharedKey -Source "CC"
#set values in azsdksettings json
$UseOnlinePolicyStore = ConvertStringToBoolean($UseOnlinePolicyStore)
$EnableAADAuthForOnlinePolicyStore = ConvertStringToBoolean($EnableAADAuthForOnlinePolicyStore)
if($UseOnlinePolicyStore)
{
if($EnableAADAuthForOnlinePolicyStore)
{
Set-AzSDKPolicySettings -OnlinePolicyStoreUrl $OnlinePolicyStoreUrl -EnableAADAuthForOnlinePolicyStore
}
else
{
Set-AzSDKPolicySettings -OnlinePolicyStoreUrl $OnlinePolicyStoreUrl
}
}
else
{
Set-AzSDKPolicySettings -DisableOnlinePolicy
}
"Running command 'Get-AzSDKAzureServicesSecurityStatus'"
$SVTResultPath = Get-AzSDKAzureServicesSecurityStatus -SubscriptionId $SubscriptionID -ResourceGroupNames $ResourceGroupNames -ExcludeTags "OwnerAccess"
"Running command 'Get-AzSDKSubscriptionSecurityStatus'"
$SubCoreResultPath = Get-AzSDKSubscriptionSecurityStatus -SubscriptionId $SubscriptionID -ExcludeTags "OwnerAccess"
$ReportFolderPath = (Get-Item $SVTResultPath).parent.FullName
"commands execution completed"
#Check if storage account exists
try
{
Get-AzureRmStorageAccount -ResourceGroupName $StorageAccountRG -Name $StorageAccountName -ErrorAction stop | Out-Null
}
catch
{
Write-Error -Message $_.Exception
throw $_.Exception
}
#Create output files in storage
$containerName = "azsdkexecutionlogs"
$archiveFilePath = "$ReportFolderPath\AutomationLogs_" + $(Get-Date -format "yyyyMMdd_HHmmss") + ".zip"
$keys = Get-AzureRmStorageAccountKey -ResourceGroupName $StorageAccountRG -Name $StorageAccountName
$currentContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $keys[0].Value -Protocol Https
try
{
Get-AzureStorageContainer -Name $containerName -Context $currentContext -ErrorAction Stop | Out-Null
}
Catch
{
New-AzureStorageContainer -Name $containerName -Context $currentContext | Out-Null
}
Compress-Archive -Path $ReportFolderPath -CompressionLevel Optimal -DestinationPath $archiveFilePath
Set-AzureStorageBlobContent -File $archiveFilePath -Container $containerName -Context $currentContext | Out-Null
"Exported reports to storage"
#cleanup
Remove-Item -Path $ReportFolderPath -Recurse
}
#config start
$ResourceGroupNames = Get-AutomationVariable -Name "AppResourceGroupNames"
$OMSWorkspaceId = Get-AutomationVariable -Name "OMSWorkspaceId"
$OMSWorkspaceSharedKey = Get-AutomationVariable -Name "OMSSharedKey"
$StorageAccountName = Get-AutomationVariable -Name "ReportsStorageAccountName"
$StorageAccountRG = "[#AutomationAccountRG#]"
$AutomationAccountRG = "[#AutomationAccountRG#]"
$AutomationAccountName="[#AutomationAccountName#]"
$RunbookName = "[#RunbookName#]"
$NextRunScheduleName = "Next_Run_Schedule"
$UseOnlinePolicyStore = "[#UseOnlinePolicyStore#]"
$OnlinePolicyStoreUrl = "[#OnlinePolicyStoreUrl#]"
$EnableAADAuthForOnlinePolicyStore = "[#EnableAADAuthForOnlinePolicyStore#]"
#config end
#global variables
$PowershellGalleryUrl = "https://www.powershellgallery.com"
$AzSDKModuleName = "[#ModuleName#]"
$ResultModuleList = [ordered]@{}
#Login
try {
$RunAsConnection = Get-AutomationConnection -Name "AzureRunAsConnection"
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $RunAsConnection.TenantId `
-ApplicationId $RunAsConnection.ApplicationId `
-CertificateThumbprint $RunAsConnection.CertificateThumbprint | Out-Null
Set-AzureRmContext -SubscriptionId $RunAsConnection.SubscriptionID | Out-Null
}
catch {
if(!$RunAsConnection) {
throw "Connection AzureRunAsConnection not found. Please create one"
}
else {
throw $_.Exception
}
}
#Set subscription id
$SubscriptionID = $RunAsConnection.SubscriptionID
#check if AzureRM is available (for scenario where AzSDK is available but AzureRM extraction might have failed)
$azureRMmodule = Get-AzureRmAutomationModule -ResourceGroupName $AutomationAccountRG `
-AutomationAccountName $AutomationAccountName `
-Name AzureRM -ErrorAction SilentlyContinue
$isAzureRMAvailable = $null -ne $azureRMmodule -and `
($azureRMmodule.ProvisioningState -eq "Succeeded" -or $azureRMmodule.ProvisioningState -eq "Created")
#check if AzSDK module is latest and AzureRM is available
if(!(CheckModuleVersion -ModuleName $AzSDKModuleName) -or !$isAzureRMAvailable)
{
#Update all modules
#Module list is in hashtable format : key = modulename , value = version (This is useful to fetch version of specific module by name)
$finalModuleList = [ordered]@{}
#Get dependencies of azsdk module
AddDependentModules -InputModuleList @{$AzSDKModuleName=""} | Out-Null
#Azure modules to be downloaded first should be added first in finalModuleList
$baseModuleList = [ordered]@{}
$baseModuleList.Add("AzureRM.Profile",$ResultModuleList.Item("AzureRM.Profile"))
$baseModuleList.Add("AzureRM.Automation",$ResultModuleList.Item("AzureRM.Automation"))
$ResultModuleList.Remove("AzureRM.Profile")
$ResultModuleList.Remove("AzureRM.Automation")
$finalModuleList += $baseModuleList
$finalModuleList += $ResultModuleList
$syncModules = @("AzureRM.Profile", "AzureRM.Automation");
Set-Modules -ModuleList $finalModuleList -SyncModuleList $syncModules
#Create next run
CreateNextRunSchedule
}
#check if AzSDK command is accessible
elseif((Get-Command -Name "Get-AzSDKAzureServicesSecurityStatus" -ErrorAction SilentlyContinue|Measure-Object).Count -eq 0)
{
CreateNextRunSchedule
}
else
{
GetCCStatus
}
#relink all schedules to use latest modules
ReLinkAllSchedules
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Managers/ControlStateExtension.ps1
|
ControlStateExtension.ps1
|
Set-StrictMode -Version Latest
class ControlStateExtension
{
hidden [PSObject] $AzSDKResourceGroup = $null;
hidden [PSObject] $AzSDKStorageAccount = $null;
hidden [PSObject] $AzSDKStorageContainer = $null;
hidden [PSObject] $ControlStateIndexer = $null;
hidden [int] $HasControlStateReadPermissions = -1;
hidden [int] $HasControlStateWritePermissions = -1;
hidden [string] $IndexerBlobName ="Resource.index.json"
ControlStateExtension()
{
}
hidden [void] Initialize()
{
try
{
$this.GetAzSDKControlStateContainer()
$this.HasControlStateReadPermissions = 1
#If there are no write permissions and with just read permissions, we cant get the container object.
if($null -ne $this.AzSDKResourceGroup -and $null -ne $this.AzSDKStorageAccount -and $null -ne $this.AzSDKStorageContainer)
{
$this.HasControlStateWritePermissions = 1
}
}
catch
{
$this.HasControlStateReadPermissions = 0
}
}
hidden [PSObject] GetAzSDKRG()
{
$azSDKConfigData = [ConfigurationManager]::GetAzSdkConfigData()
$resourceGroup = Get-AzureRmResourceGroup -Name $azSDKConfigData.AzSDKRGName -ErrorAction SilentlyContinue
if($null -eq $resourceGroup -or ($resourceGroup | Measure-Object).Count -eq 0)
{
if([Helpers]::NewAzSDKResourceGroup($azSDKConfigData.AzSDKRGName, [Constants]::AzSDKRGLocation, ""))
{
$resourceGroup = Get-AzureRmResourceGroup -Name $azSDKConfigData.AzSDKRGName -ErrorAction SilentlyContinue
}
}
$this.AzSDKResourceGroup = $resourceGroup
return $resourceGroup;
}
hidden [PSObject] GetAzSDKStorageAccount()
{
if($null -eq $this.AzSDKResourceGroup)
{
$this.GetAzSDKRG();
}
$StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $this.AzSDKResourceGroup.ResourceGroupName | Where-Object {$_.StorageAccountName -like 'azsdk*'} -ErrorAction SilentlyContinue
#if no storage account found then it assumes that there is no control state feature is not used and if there are more than one storage account found it assumes the same
if($null -eq $StorageAccount -or ($StorageAccount | Measure-Object).Count -eq 0)
{
$storageAccountName = ("azsdk" + (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss"));
$storageObject = [Helpers]::NewAzsdkCompliantStorage($storageAccountName, $this.AzSDKResourceGroup.ResourceGroupName, [Constants]::AzSDKRGLocation)
if($null -ne $storageObject -and ($storageObject | Measure-Object).Count -gt 0)
{
$StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $this.AzSDKResourceGroup.ResourceGroupName | Where-Object {$_.StorageAccountName -like 'azsdk*'} -ErrorAction SilentlyContinue
}
}
$this.AzSDKStorageAccount = $StorageAccount;
return $StorageAccount;
}
hidden [PSObject] GetAzSDKControlStateContainer()
{
if($null -eq $this.AzSDKStorageAccount)
{
$this.GetAzSDKStorageAccount();
}
$ContainerName = "azsdk-controls-state"
$containerObject = Get-AzureStorageContainer -Context $this.AzSDKStorageAccount.Context -Name $ContainerName -ErrorAction SilentlyContinue
if($null -eq $containerObject)
{
New-AzureStorageContainer -Context $this.AzSDKStorageAccount.Context -Name $ContainerName -ErrorAction SilentlyContinue
$containerObject = $containerObject = Get-AzureStorageContainer -Context $this.AzSDKStorageAccount.Context -Name $ContainerName -ErrorAction SilentlyContinue
}
$this.AzSDKStorageContainer = $containerObject;
return $containerObject;
}
hidden [bool] ComputeControlStateIndexer()
{
#check for permission validaiton
if($this.HasControlStateReadPermissions -le 0)
{
return $false;
}
$StorageAccount = $this.AzSDKStorageAccount;
$containerObject = $this.AzSDKStorageContainer;
$ContainerName = $this.AzSDKStorageContainer.Name
$indexerBlob = Get-AzureStorageBlob -Container $ContainerName -Blob $this.IndexerBlobName -Context $StorageAccount.Context -ErrorAction SilentlyContinue
[ControlStateIndexer[]] $indexerObjects = @();
$this.ControlStateIndexer = $indexerObjects
if($null -eq $indexerBlob)
{
return $true;
}
$AzSDKTemp = [Constants]::AzSdkAppFolderPath + "\Temp\ServerControlState";
if(-not (Test-Path -Path $AzSDKTemp))
{
mkdir -Path $AzSDKTemp -Force
}
Get-AzureStorageBlobContent -CloudBlob $indexerBlob.ICloudBlob -Context $StorageAccount.Context -Destination $AzSDKTemp -Force
$indexerObject = Get-ChildItem -Path "$AzSDKTemp\$($this.IndexerBlobName)" -Force | Get-Content | ConvertFrom-Json
$this.ControlStateIndexer += $indexerObject;
return $true;
}
hidden [PSObject] GetControlState([string] $id)
{
try
{
[ControlState[]] $controlStates = @();
$retVal = $this.ComputeControlStateIndexer();
if($null -ne $this.ControlStateIndexer -and $retVal)
{
$indexes = @();
$indexes += $this.ControlStateIndexer
$selectedIndex = $indexes | Where-Object { $_.ResourceId -eq $id}
if(($selectedIndex | Measure-Object).Count -gt 0)
{
$controlStateBlobName = $selectedIndex.HashId + ".json"
$azSDKConfigData = [ConfigurationManager]::GetAzSdkConfigData()
#$azSDKConfigData.$AzSDKRGName
#Look of is there is a AzSDK RG and AzSDK Storage account
$StorageAccount = $this.AzSDKStorageAccount;
$containerObject = $this.AzSDKStorageContainer
$ContainerName = $this.AzSDKStorageContainer.Name
$controlStateBlob = Get-AzureStorageBlob -Container $ContainerName -Blob $controlStateBlobName -Context $StorageAccount.Context -ErrorAction SilentlyContinue
if($null -eq $controlStateBlob)
{
return $controlStates;
}
$AzSDKTemp = [Constants]::AzSdkAppFolderPath + "\Temp\ServerControlState";
if(-not (Test-Path -Path $AzSDKTemp))
{
mkdir -Path $AzSDKTemp -Force
}
Get-AzureStorageBlobContent -CloudBlob $controlStateBlob.ICloudBlob -Context $StorageAccount.Context -Destination $AzSDKTemp -Force
$ControlStatesJson = Get-ChildItem -Path "$AzSDKTemp\$controlStateBlobName" -Force | Get-Content | ConvertFrom-Json
if($null -ne $ControlStatesJson)
{
$ControlStatesJson | ForEach-Object {
$controlStates += [ControlState] $_;
}
}
}
}
return $controlStates;
}
finally{
$this.CleanTempFolder();
}
}
hidden [void] SetControlState([string] $id, [ControlState[]] $controlStates, [bool] $Override)
{
$AzSDKTemp = [Constants]::AzSdkAppFolderPath + "\Temp\ServerControlState";
if(-not (Test-Path "$AzSDKTemp\ControlState"))
{
mkdir -Path "$AzSDKTemp\ControlState" -ErrorAction Stop | Out-Null
}
$hash = [Helpers]::ComputeHash($id);
$indexerPath = "$AzSDKTemp\ControlState\$($this.IndexerBlobName)"
$fileName = "$AzSDKTemp\ControlState\$hash.json"
$StorageAccount = $this.AzSDKStorageAccount;
$containerObject = $this.AzSDKStorageContainer
$ContainerName = $this.AzSDKStorageContainer.Name
$finalControlStates = $controlStates;
if($Override)
{
# in the case of override, just persist what is evaluated in the current context. No merging with older data
$this.UpdateControlIndexer($id, $controlStates);
$finalControlStates = $controlStates | Where-Object { $_.State};
}
else
{
#merge with the exiting if found
$persistedControlStates = $this.GetPersistedControlStates("$hash.json");
$finalControlStates = $this.MergeControlStates($persistedControlStates, $controlStates);
$this.UpdateControlIndexer($id, $finalControlStates);
}
[Helpers]::ConvertToJsonCustom($finalControlStates) | Out-File $fileName -Force
if($null -ne $this.ControlStateIndexer)
{
[Helpers]::ConvertToJsonCustom($this.ControlStateIndexer) | Out-File $indexerPath -Force
$controlStateArray = Get-ChildItem -Path "$AzSDKTemp\ControlState"
$controlStateArray | ForEach-Object { Set-AzureStorageBlobContent -File $_.FullName -Container $ContainerName -BlobType Block -Context $StorageAccount.Context -Force }
}
else
{
#clean up the container as there is no indexer
Get-AzureStorageBlob -Container $ContainerName -Context $StorageAccount.Context | Remove-AzureStorageBlob
}
}
hidden [ControlState[]] GetPersistedControlStates([string] $controlStateBlobName)
{
$AzSDKTemp = [Constants]::AzSdkAppFolderPath + "\Temp\ServerControlState";
if(-not (Test-Path "$AzSDKTemp\ExistingControlStates"))
{
mkdir -Path "$AzSDKTemp\ExistingControlStates" -ErrorAction Stop | Out-Null
}
$StorageAccount = $this.AzSDKStorageAccount;
$containerObject = $this.AzSDKStorageContainer
$ContainerName = $this.AzSDKStorageContainer.Name
[ControlState[]] $ControlStatesJson = @()
try
{
$controlStateBlob = Get-AzureStorageBlob -Container $ContainerName -Blob $controlStateBlobName -Context $StorageAccount.Context -ErrorAction SilentlyContinue
Get-AzureStorageBlobContent -CloudBlob $controlStateBlob.ICloudBlob -Context $StorageAccount.Context -Destination "$AzSDKTemp\ExistingControlStates" -Force
$ControlStatesJson = Get-ChildItem -Path "$AzSDKTemp\ExistingControlStates\$controlStateBlobName" -Force | Get-Content | ConvertFrom-Json
}
catch
{
$ControlStatesJson = @()
}
return $ControlStatesJson
}
hidden [ControlState[]] MergeControlStates([ControlState[]] $persistedControlStates,[ControlState[]] $controlStates)
{
[ControlState[]] $computedControlStates = $controlStates;
if(($computedControlStates | Measure-Object).Count -le 0)
{
$computedControlStates = @();
}
if(($persistedControlStates | Measure-Object).Count -gt 0)
{
$persistedControlStates | ForEach-Object {
$controlState = $_;
if(($computedControlStates | Where-Object { $_.InternalId -eq $controlState.InternalId} | Measure-Object).Count -le 0)
{
$computedControlStates += $controlState;
}
}
}
#remove the control states with null state which would be in the case of clear attestation.
$computedControlStates = $computedControlStates | Where-Object { $_.State}
return $computedControlStates;
}
hidden [void] UpdateControlIndexer([string] $id, [ControlState[]] $controlStates)
{
$this.ControlStateIndexer = $null;
$retVal = $this.ComputeControlStateIndexer();
$StorageAccount = $this.AzSDKStorageAccount;
$containerObject = $this.AzSDKStorageContainer
$ContainerName = $this.AzSDKStorageContainer.Name
if($retVal)
{
$tempHash = [Helpers]::ComputeHash($id);
$filteredIndexerObject = $this.ControlStateIndexer | Where-Object { $_.HashId -eq $tempHash}
if($null -ne $filteredIndexerObject)
{
if(($controlStates | Measure-Object).Count -le 0)
{
$this.ControlStateIndexer = $this.ControlStateIndexer | Where-Object { $_.HashId -ne $tempHash}
}
else
{
$filteredIndexerObject.ExpiryTime = [DateTime]::UtcNow.AddMonths(3);
$filteredIndexerObject.AttestedBy = [Helpers]::GetCurrentSessionUser();
$filteredIndexerObject.AttestedDate = [DateTime]::UtcNow;
$filteredIndexerObject.Version = "1.0";
}
}
else
{
$currentIndexObject = [ControlStateIndexer]::new();
$currentIndexObject.ResourceId = $id
$currentIndexObject.HashId = $tempHash;
$currentIndexObject.ExpiryTime = [DateTime]::UtcNow.AddMonths(3);
$currentIndexObject.AttestedBy = [Helpers]::GetCurrentSessionUser();
$currentIndexObject.AttestedDate = [DateTime]::UtcNow;
$currentIndexObject.Version = "1.0";
$this.ControlStateIndexer += $currentIndexObject;
}
}
}
[bool] HasControlStateReadAccessPermissions()
{
if($this.HasControlStateReadPermissions -le 0)
{
return $false;
}
else
{
return $true;
}
}
[bool] HasControlStateWriteAccessPermissions()
{
if($this.HasControlStateWritePermissions -le 0)
{
return $false;
}
else
{
return $true;
}
}
hidden [void] CleanTempFolder()
{
$AzSDKTemp = [Constants]::AzSdkAppFolderPath + "\Temp";
if(Test-Path "$AzSDKTemp")
{
rmdir -Path $AzSDKTemp -Recurse -Force -ErrorAction Stop | Out-Null
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Managers/ConfigurationManager.ps1
|
ConfigurationManager.ps1
|
Set-StrictMode -Version Latest
#
# ConfigManager.ps1
#
class ConfigurationManager
{
hidden static [AzSdkConfig] GetAzSdkConfigData()
{
return [AzSdkConfig]::GetInstance([ConfigurationManager]::GetAzSdkSettings().UseOnlinePolicyStore, [ConfigurationManager]::GetAzSdkSettings().OnlinePolicyStoreUrl, [ConfigurationManager]::GetAzSdkSettings().EnableAADAuthForOnlinePolicyStore)
}
hidden static [AzSdkSettings] GetAzSdkSettings()
{
return [AzSdkSettings]::GetInstance()
}
hidden static [SVTConfig] GetSVTConfig([string] $fileName)
{
return [SVTConfig]::LoadServerConfigFile($fileName, [ConfigurationManager]::GetAzSdkSettings().UseOnlinePolicyStore, [ConfigurationManager]::GetAzSdkSettings().OnlinePolicyStoreUrl, [ConfigurationManager]::GetAzSdkSettings().EnableAADAuthForOnlinePolicyStore);
}
hidden static [PSObject] LoadServerConfigFile([string] $fileName)
{
return [ConfigurationHelper]::LoadServerConfigFile($fileName, [ConfigurationManager]::GetAzSdkSettings().UseOnlinePolicyStore, [ConfigurationManager]::GetAzSdkSettings().OnlinePolicyStoreUrl, [ConfigurationManager]::GetAzSdkSettings().EnableAADAuthForOnlinePolicyStore);
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/ListenerHelper.ps1
|
ListenerHelper.ps1
|
Set-StrictMode -Version Latest
#Class to register appropriate listeners based on environment
class ListenerHelper
{
static ListenerHelper()
{
}
static [void] RegisterListeners()
{
[WriteFolderPath]::GetInstance().RegisterEvents();
[WriteDetailedLog]::GetInstance().RegisterEvents();
[WriteSummaryFile]::GetInstance().RegisterEvents();
[WritePsConsole]::GetInstance().RegisterEvents();
[WriteDataFile]::GetInstance().RegisterEvents();
[OMSOutput]::GetInstance().RegisterEvents();
[ControlTelemetry]::GetInstance().RegisterEvents();
[UsageTelemetry]::GetInstance().RegisterEvents();
[VulnDataPublisher]::GetInstance().RegisterEvents();
}
static [void] UnregisterListeners()
{
[WriteFolderPath]::GetInstance().UnregisterEvents();
[WriteDetailedLog]::GetInstance().UnregisterEvents();
[WriteSummaryFile]::GetInstance().UnregisterEvents();
[WritePsConsole]::GetInstance().UnregisterEvents();
[WriteDataFile]::GetInstance().UnregisterEvents();
[OMSOutput]::GetInstance().UnregisterEvents();
[ControlTelemetry]::GetInstance().UnregisterEvents();
[UsageTelemetry]::GetInstance().UnregisterEvents();
[VulnDataPublisher]::GetInstance().UnregisterEvents();
}
}
#[ListenerHelper]::RegisterListeners();
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/RemoteReports/RemoteReportHelper.ps1
|
RemoteReportHelper.ps1
|
Set-StrictMode -Version Latest
class RemoteReportHelper
{
hidden static [string[]] $IgnoreScanParamList = "DoNotOpenOutputFolder";
hidden static [string[]] $AllowedServiceScanParamList = "SubscriptionId", "ResourceGroupNames";
hidden static [string[]] $AllowedSubscriptionScanParamList = "SubscriptionId";
hidden static [int] $MaxServiceParamCount = [RemoteReportHelper]::IgnoreScanParamList.Count + [RemoteReportHelper]::AllowedServiceScanParamList.Count;
hidden static [int] $MaxSubscriptionParamCount = [RemoteReportHelper]::IgnoreScanParamList.Count + [RemoteReportHelper]::AllowedSubscriptionScanParamList.Count;
static [FeatureGroup] GetFeatureGroup([string] $command)
{
$command = $command.ToLower()
if ($command.Contains("subscriptionsecurity"))
{
return [FeatureGroup]::Subscription
}
if ($command.Contains("azureservicessecurity"))
{
return [FeatureGroup]::Service
}
return [FeatureGroup]::Unknown
}
static [ServiceScanKind] GetServiceScanKind([string] $command, [hashtable] $parameters)
{
$parameterNames = [array] $parameters.Keys
if($parameterNames.Count -gt [RemoteReportHelper]::MaxServiceParamCount)
{
return [ServiceScanKind]::Partial;
}
$validParamCounter = 0;
foreach($parameterName in $parameterNames)
{
if ([RemoteReportHelper]::AllowedServiceScanParamList.Contains($parameterName))
{
$validParamCounter += 1
}
elseif ([RemoteReportHelper]::IgnoreScanParamList.Contains($parameterName))
{
# Ignoring
}
else
{
return [ServiceScanKind]::Partial;
}
}
if ($validParamCounter -eq 1)
{
return [ServiceScanKind]::Subscription;
}
elseif ($validParamCounter -eq 2)
{
return [ServiceScanKind]::ResourceGroup;
}
else
{
return [ServiceScanKind]::Partial;
}
}
static [SubscriptionScanKind] GetSubscriptionScanKind([string] $command, [hashtable] $parameters)
{
$parameterNames = [array] $parameters.Keys
if($parameterNames.Count -gt [RemoteReportHelper]::MaxSubscriptionParamCount)
{
return [SubscriptionScanKind]::Partial;
}
$validParamCounter = 0;
foreach($parameterName in $parameterNames)
{
if ([RemoteReportHelper]::AllowedSubscriptionScanParamList.Contains($parameterName))
{
$validParamCounter += 1
}
elseif ([RemoteReportHelper]::IgnoreScanParamList.Contains($parameterName))
{
# Ignoring
}
else
{
return [SubscriptionScanKind]::Partial;
}
}
if ($validParamCounter -eq 1)
{
return [SubscriptionScanKind]::Complete;
}
else
{
return [SubscriptionScanKind]::Partial;
}
}
static [SubscriptionControlResult] BuildSubscriptionControlResult([ControlResult] $controlResult, [ControlItem] $control)
{
$result = [SubscriptionControlResult]::new()
$result.ControlId = $control.ControlId
$result.ControlSeverity = $control.ControlSeverity
$result.ActualVerificationResult = $controlResult.ActualVerificationResult
$result.AttestationStatus = $controlResult.AttestationStatus
$result.VerificationResult = $controlResult.VerificationResult
return $result;
}
static [ServiceControlResult] BuildServiceControlResult([ControlResult] $controlResult, [bool] $isNestedResource, [ControlItem] $control)
{
$result = [ServiceControlResult]::new()
$result.IsNestedResource = $isNestedResource
if ($isNestedResource)
{
$result.NestedResourceName = $controlResult.ChildResourceName
}
else
{
$result.NestedResourceName = $null
}
$result.ControlId = $control.ControlID
$result.ControlSeverity = $control.ControlSeverity
$result.ActualVerificationResult = $controlResult.ActualVerificationResult
$result.AttestationStatus = $controlResult.AttestationStatus
$result.VerificationResult = $controlResult.VerificationResult
return $result;
}
static [ScanSource] GetScanSource()
{
# TODO: From framework
$settings = [ConfigurationManager]::GetAzSdkSettings();
[string] $omsSource = $settings.OMSSource;
if([string]::IsNullOrWhiteSpace($omsSource)){
return [ScanSource]::SpotCheck
}
if($omsSource.Equals("CICD", [System.StringComparison]::OrdinalIgnoreCase)){
return [ScanSource]::VSO
}
if($omsSource.Equals("CC", [System.StringComparison]::OrdinalIgnoreCase)){
return [ScanSource]::Runbook
}
return [ScanSource]::SpotCheck
}
static [string] GetControlTelemetryKey()
{
$settings = [ConfigurationManager]::GetAzSdkConfigData();
$telemetryKey = $settings.ControlTelemetryKey
[guid]$key = [guid]::NewGuid()
if([guid]::TryParse($telemetryKey, [ref] $key) -and ![guid]::Empty.Equals($key))
{
return $telemetryKey;
}
return [ConfigurationManager]::GetAzSdkSettings().LocalControlTelemetryKey;
}
static [bool] IsControlTelemetryEnabled()
{
$settings = [ConfigurationManager]::GetAzSdkConfigData();
$telemetryKey = $settings.ControlTelemetryKey
[guid]$key = [guid]::NewGuid()
if([guid]::TryParse($telemetryKey, [ref] $key) -and ![guid]::Empty.Equals($key))
{
return $settings.EnableControlTelemetry;
}
return [ConfigurationManager]::GetAzSdkSettings().LocalEnableControlTelemetry;
}
static [string] Mask([psobject] $toMask)
{
$sha384 = [System.Security.Cryptography.SHA384Managed]::new()
$maskBytes = [System.Text.Encoding]::UTF8.GetBytes($toMask.ToString())
$maskBytes = $sha384.ComputeHash($maskBytes)
$sha384.Dispose()
$take = 16
$sb = [System.Text.StringBuilder]::new($take)
for($i = 0; $i -lt ($take/2); $i++){
$x = $sb.Append($maskBytes[$i].ToString("x2"))
}
return $sb.ToString();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/RemoteReports/VulnDataPublisher.ps1
|
VulnDataPublisher.ps1
|
Set-StrictMode -Version Latest
class VulnDataPublisher: ListenerBase {
hidden VulnDataPublisher() {
}
hidden static [VulnDataPublisher] $Instance = $null;
static [VulnDataPublisher] GetInstance() {
if ( $null -eq [VulnDataPublisher]::Instance ) {
[VulnDataPublisher]::Instance = [VulnDataPublisher]::new();
}
return [VulnDataPublisher]::Instance
}
[void] RegisterEvents() {
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [VulnDataPublisher]::GetInstance();
try
{
$runIdentifier = [AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1)
$currentInstance.SetRunIdentifier($runIdentifier);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
$currentInstance = [VulnDataPublisher]::GetInstance();
try
{
$settings = [ConfigurationManager]::GetAzSdkConfigData();
if(!$settings.PublishVulnDataToApi) {return;}
$invocationContext = [System.Management.Automation.InvocationInfo] $currentInstance.InvocationContext
$featureGroup = [RemoteReportHelper]::GetFeatureGroup($invocationContext.MyCommand.Name)
$SVTEventContexts = [SVTEventContext[]] $Event.SourceArgs
if($featureGroup -eq [FeatureGroup]::Subscription){
[VulnDataPublisher]::ReportSubscriptionScan($currentInstance, $invocationContext, $SVTEventContexts)
}elseif($featureGroup -eq [FeatureGroup]::Service){
[VulnDataPublisher]::ReportServiceScan($currentInstance, $invocationContext, $SVTEventContexts)
}else{
}
}
catch
{
$currentInstance.PublishException($_);
}
});
}
static [void] ReportSubscriptionScan(
[VulnDataPublisher] $publisher, `
[System.Management.Automation.InvocationInfo] $invocationContext, `
[SVTEventContext[]] $SVTEventContexts)
{
$SVTEventContext = $SVTEventContexts[0]
$scanResult = [SubscriptionScanInfo]::new()
$scanResult.ScanKind = [RemoteReportHelper]::GetSubscriptionScanKind($invocationContext.MyCommand.Name, $invocationContext.BoundParameters)
$scanResult.SubscriptionId = $SVTEventContext.SubscriptionContext.SubscriptionId
$scanResult.SubscriptionName = $SVTEventContext.SubscriptionContext.SubscriptionName
$scanResult.Source = [RemoteReportHelper]::GetScanSource()
$scanResult.ScannerVersion = $publisher.GetCurrentModuleVersion()
# TODO: Figure out, temp using module version
$scanResult.ControlVersion = $publisher.GetCurrentModuleVersion()
$results = [System.Collections.ArrayList]::new()
$SVTEventContexts | ForEach-Object {
$context = $_
if ($context.ControlItem.Enabled) {
$result = [RemoteReportHelper]::BuildSubscriptionControlResult($context.ControlResults[0], $context.ControlItem)
$results.Add($result)
}
else {
$result = [SubscriptionControlResult]::new()
$result.ControlId = $context.ControlItem.ControlID
$result.ActualVerificationResult = [VerificationResult]::Disabled
$result.AttestationStatus = [AttestationStatus]::None
$result.VerificationResult = [VerificationResult]::Disabled
$results.Add($result)
}
}
$scanResult.ControlResults = [SubscriptionControlResult[]] $results
[RemoteApiHelper]::PostSubscriptionScanResult($scanResult)
}
static [void] ReportServiceScan(
[VulnDataPublisher] $publisher, `
[System.Management.Automation.InvocationInfo] $invocationContext, `
[SVTEventContext[]] $SVTEventContexts)
{
$SVTEventContextFirst = $SVTEventContexts[0]
$scanResult = [ServiceScanInfo]::new()
$scanResult.ScanKind = [RemoteReportHelper]::GetServiceScanKind($invocationContext.MyCommand.Name, $invocationContext.BoundParameters)
$scanResult.SubscriptionId = $SVTEventContextFirst.SubscriptionContext.SubscriptionId
$scanResult.SubscriptionName = $SVTEventContextFirst.SubscriptionContext.SubscriptionName
$scanResult.Source = [RemoteReportHelper]::GetScanSource()
$scanResult.ScannerVersion = $publisher.GetCurrentModuleVersion()
# TODO: Figure out, temp using module version
$scanResult.ControlVersion = $publisher.GetCurrentModuleVersion()
$scanResult.Feature = $SVTEventContextFirst.FeatureName
$scanResult.ResourceGroup = $SVTEventContextFirst.ResourceContext.ResourceGroupName
$scanResult.ResourceName = $SVTEventContextFirst.ResourceContext.ResourceName
$scanResult.ResourceId = $SVTEventContextFirst.ResourceContext.ResourceId
$results = [System.Collections.ArrayList]::new()
$SVTEventContexts | ForEach-Object {
$SVTEventContext = $_
if (!$SVTEventContext.ControlItem.Enabled) {
$result = [ServiceControlResult]::new()
$result.ControlId = $SVTEventContext.ControlItem.ControlID
$result.ControlSeverity = $SVTEventContext.ControlItem.ControlSeverity
$result.ActualVerificationResult = [VerificationResult]::Disabled
$result.AttestationStatus = [AttestationStatus]::None
$result.VerificationResult = [VerificationResult]::Disabled
$results.Add($result)
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
($scanResult.ResourceName -eq $SVTEventContext.ControlResults[0].ChildResourceName -or `
[string]::IsNullOrWhiteSpace($SVTEventContext.ControlResults[0].ChildResourceName)))
{
$result = [RemoteReportHelper]::BuildServiceControlResult($SVTEventContext.ControlResults[0], `
$false, $SVTEventContext.ControlItem)
$results.Add($result)
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
$scanResult.ResourceName -ne $SVTEventContext.ControlResults[0].ChildResourceName)
{
$result = [RemoteReportHelper]::BuildServiceControlResult($SVTEventContext.ControlResults[0], `
$true, $SVTEventContext.ControlItem)
$results.Add($result)
}
elseif ($SVTEventContext.ControlResults.Count -gt 1)
{
$SVTEventContext.ControlResults | Foreach-Object {
$result = [RemoteReportHelper]::BuildServiceControlResult($_ , `
$true, $SVTEventContext.ControlItem)
$results.Add($result)
}
}
}
$scanResult.ControlResults = [ServiceControlResult[]] $results
[RemoteApiHelper]::PostServiceScanResult($scanResult)
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/RemoteReports/TelemetryStrings.ps1
|
TelemetryStrings.ps1
|
Set-StrictMode -Version Latest
class TelemetryKeys {
static [string] $SubscriptionId = "SubscriptionId";
static [string] $SubscriptionName = "SubscriptionName";
static [string] $FeatureGroup = "FeatureGroup";
static [string] $Feature = "Feature";
static [string] $ResourceName = "ResourceName";
static [string] $ResourceGroup = "ResourceGroup";
static [string] $IsInterrupted = "IsInterrupted";
static [string] $InterruptedReason = "InterruptedReason";
static [string] $InterruptedReasonException = "InterruptedReasonException";
static [string] $TimeTakenInMs = "TimeTakenInMs";
static [string] $ControlId = "ControlId";
static [string] $ControlStatus = "ControlStatus";
static [string] $ControlFailedReason = "ControlFailedReason";
static [string] $NestedComplaintCount = "NestedComplaintCount";
static [string] $NestedNonComplaintCount = "NestedNonComplaintCount";
static [string] $NestedTotalCount = "NestedTotalCount";
static [string] $NestedResourceName = "NestedResourceName";
static [string] $IsNestedResourceCheck = "IsNestedResourceCheck";
}
class TelemetryEvents {
static [string] $OperationInterrupted = "Operation Interrupted";
static [string] $OperationCompleted = "Operation Completed";
static [string] $ControlScanned = "Control Scanned";
static [string] $NestedResourceControlScanned = "Nested Resource Control Scanned";
static [string] $AutoHealAttempted = "Auto Heal Attempted";
}
class TelemetryMessages {
static [string] $Yes = "Yes";
static [string] $InterruptedReasonException = "Exception";
static [string] $InterruptedReasonControlJSONNotFound = "ControlJSONNotFound";
static [string] $ControlPassed = "Passed";
static [string] $ControlFailed = "Failed";
static [string] $ControlManual = "Manual";
static [string] $ControlVerify = "Verify";
static [string] $ControlDisabled = "Disabled";
static [string] $ControlNotApplicable = "N/A";
}
enum TraceLevel {
Verbose
Information
Warning
Error
Fatal
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/RemoteReports/UsageTelemetry.ps1
|
UsageTelemetry.ps1
|
Set-StrictMode -Version Latest
class UsageTelemetry: ListenerBase {
[Microsoft.ApplicationInsights.TelemetryClient] $TelemetryClient;
hidden UsageTelemetry() {
$this.TelemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new()
$this.TelemetryClient.InstrumentationKey = [Constants]::UsageTelemetryKey
}
hidden static [UsageTelemetry] $Instance = $null;
static [UsageTelemetry] GetInstance() {
if ( $null -eq [UsageTelemetry]::Instance -or $null -eq [UsageTelemetry]::Instance.TelemetryClient) {
[UsageTelemetry]::Instance = [UsageTelemetry]::new();
}
return [UsageTelemetry]::Instance
}
[void] RegisterEvents() {
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
$runIdentifier = [AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1)
$currentInstance.SetRunIdentifier($runIdentifier);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
$azsdkSettings = [ConfigurationManager]::GetAzSdkSettings();
if($azsdkSettings.UsageTelemetryLevel -ne "Anonymous") { return; }
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
$invocationContext = [System.Management.Automation.InvocationInfo] $currentInstance.InvocationContext
$featureGroup = [RemoteReportHelper]::GetFeatureGroup($invocationContext.MyCommand.Name)
$SVTEventContexts = [SVTEventContext[]] $Event.SourceArgs
if($featureGroup -eq [FeatureGroup]::Subscription){
[UsageTelemetry]::PushSubscriptionScanResults($currentInstance, $SVTEventContexts)
}elseif($featureGroup -eq [FeatureGroup]::Service){
[UsageTelemetry]::PushServiceScanResults($currentInstance, $SVTEventContexts)
}else{
}
}
catch
{
$currentInstance.PublishException($_);
}
$currentInstance.TelemetryClient.Flush()
});
$this.RegisterEvent([AzSdkGenericEvent]::Exception, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
[System.Management.Automation.ErrorRecord] $er = ($Event.SourceArgs | Select-Object -First 1)
[UsageTelemetry]::PushException($currentInstance, @{}, @{}, $er);
}
catch
{
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandError, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
[System.Management.Automation.ErrorRecord] $er = $Event.SourceArgs.ExceptionMessage
[UsageTelemetry]::PushException($currentInstance, @{}, @{}, $er);
}
catch
{
}
});
$this.RegisterEvent([SVTEvent]::CommandError, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
[System.Management.Automation.ErrorRecord] $er = $Event.SourceArgs.ExceptionMessage
[UsageTelemetry]::PushException($currentInstance, @{}, @{}, $er);
}
catch
{
}
});
$this.RegisterEvent([SVTEvent]::EvaluationError, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
[System.Management.Automation.ErrorRecord] $er = $Event.SourceArgs.ExceptionMessage
[UsageTelemetry]::PushException($currentInstance, @{}, @{}, $er);
}
catch
{
}
});
$this.RegisterEvent([SVTEvent]::ControlError, {
$currentInstance = [UsageTelemetry]::GetInstance();
try
{
[System.Management.Automation.ErrorRecord] $er = $Event.SourceArgs.ExceptionMessage
[UsageTelemetry]::PushException($currentInstance, @{}, @{}, $er);
}
catch
{
}
});
}
static [void] PushSubscriptionScanResults(
[UsageTelemetry] $Publisher, `
[SVTEventContext[]] $SVTEventContexts)
{
$eventData = @{
[TelemetryKeys]::FeatureGroup = [FeatureGroup]::Subscription;
"ScanKind" = [RemoteReportHelper]::GetSubscriptionScanKind(
$Publisher.InvocationContext.MyCommand.Name,
$Publisher.InvocationContext.BoundParameters);
}
$SVTEventContexts | ForEach-Object {
$context = $_
[hashtable] $eventDataClone = $eventData.Clone();
$eventDataClone.Add("ControlIntId", $context.ControlItem.Id);
$eventDataClone.Add("ControlId", $context.ControlItem.ControlID);
$eventDataClone.Add("ControlSeverity", $context.ControlItem.ControlSeverity);
if ($context.ControlItem.Enabled) {
$eventDataClone.Add("ActualVerificationResult", $context.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $context.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $context.ControlResults[0].VerificationResult)
}
else {
$eventDataClone.Add("ActualVerificationResult", [VerificationResult]::Disabled)
$eventDataClone.Add("AttestationStatus", [AttestationStatus]::None)
$eventDataClone.Add("VerificationResult", [VerificationResult]::Disabled)
}
[UsageTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
}
static [void] PushServiceScanResults(
[UsageTelemetry] $Publisher, `
[SVTEventContext[]] $SVTEventContexts)
{
$NA = "NA"
$SVTEventContextFirst = $SVTEventContexts[0]
$eventData = @{
[TelemetryKeys]::FeatureGroup = [FeatureGroup]::Service;
"ScanKind" = [RemoteReportHelper]::GetServiceScanKind(
$Publisher.InvocationContext.MyCommand.Name,
$Publisher.InvocationContext.BoundParameters);
"Feature" = $SVTEventContextFirst.FeatureName;
"ResourceGroup" = [RemoteReportHelper]::Mask($SVTEventContextFirst.ResourceContext.ResourceGroupName);
"ResourceName" = [RemoteReportHelper]::Mask($SVTEventContextFirst.ResourceContext.ResourceName);
"ResourceId" = [RemoteReportHelper]::Mask($SVTEventContextFirst.ResourceContext.ResourceId);
}
$SVTEventContexts | ForEach-Object {
$SVTEventContext = $_
[hashtable] $eventDataClone = $eventData.Clone()
$eventDataClone.Add("ControlIntId", $SVTEventContext.ControlItem.Id);
$eventDataClone.Add("ControlId", $SVTEventContext.ControlItem.ControlID);
$eventDataClone.Add("ControlSeverity", $SVTEventContext.ControlItem.ControlSeverity);
if (!$SVTEventContext.ControlItem.Enabled) {
$eventDataClone.Add("ActualVerificationResult", [VerificationResult]::Disabled)
$eventDataClone.Add("AttestationStatus", [AttestationStatus]::None)
$eventDataClone.Add("VerificationResult", [VerificationResult]::Disabled)
[UsageTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
($SVTEventContextFirst.ResourceContext.ResourceName -eq $SVTEventContext.ControlResults[0].ChildResourceName -or `
[string]::IsNullOrWhiteSpace($SVTEventContext.ControlResults[0].ChildResourceName)))
{
$eventDataClone.Add("ActualVerificationResult", $SVTEventContext.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $SVTEventContext.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $SVTEventContext.ControlResults[0].VerificationResult)
$eventDataClone.Add("IsNestedResource", 'No')
$eventDataClone.Add("NestedResourceName", $NA)
[UsageTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
$SVTEventContextFirst.ResourceContext.ResourceName -ne $SVTEventContext.ControlResults[0].ChildResourceName)
{
$eventDataClone.Add("ActualVerificationResult", $SVTEventContext.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $SVTEventContext.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $SVTEventContext.ControlResults[0].VerificationResult)
$eventDataClone.Add("IsNestedResource", 'Yes')
$eventDataClone.Add("NestedResourceName", [RemoteReportHelper]::Mask($SVTEventContext.ControlResults[0].ChildResourceName))
[UsageTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -gt 1)
{
$eventDataClone.Add("IsNestedResource", 'Yes')
$SVTEventContext.ControlResults | Foreach-Object {
[hashtable] $eventDataCloneL2 = $eventDataClone.Clone()
$eventDataCloneL2.Add("ActualVerificationResult", $_.ActualVerificationResult)
$eventDataCloneL2.Add("AttestationStatus", $_.AttestationStatus)
$eventDataCloneL2.Add("VerificationResult", $_.VerificationResult)
$eventDataCloneL2.Add("NestedResourceName", [RemoteReportHelper]::Mask($_.ChildResourceName))
[UsageTelemetry]::PushEvent($Publisher, $eventDataCloneL2, @{})
}
}
}
}
static [void] PushEvent([UsageTelemetry] $Publisher, `
[hashtable] $Properties, [hashtable] $Metrics)
{
try{
[UsageTelemetry]::SetCommonProperties($Publisher, $Properties);
$event = [Microsoft.ApplicationInsights.DataContracts.EventTelemetry]::new()
$event.Name = "Control Scanned"
$Properties.Keys | ForEach-Object {
try{
$event.Properties.Add($_, $Properties[$_].ToString());
}
catch{
}
}
$Metrics.Keys | ForEach-Object {
try{
$event.Metrics.Add($_, $Metrics[$_]);
}
catch{
}
}
$Publisher.TelemetryClient.TrackEvent($event);
}
catch{
}
}
static [void] PushException([UsageTelemetry] $Publisher, `
[hashtable] $Properties, [hashtable] $Metrics, `
[System.Management.Automation.ErrorRecord] $ErrorRecord)
{
try{
[UsageTelemetry]::SetCommonProperties($Publisher, $Properties);
$ex = [Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry]::new()
$ex.Exception = $ErrorRecord.Exception
try{
$ex.Properties.Add("ScriptStackTrace", [UsageTelemetry]::AnonScriptStackTrace($ErrorRecord.ScriptStackTrace))
}catch{}
$Properties.Keys | ForEach-Object {
try{
$ex.Properties.Add($_, $Properties[$_].ToString());
}
catch{
}
}
$Metrics.Keys | ForEach-Object {
try{
$ex.Metrics.Add($_, $Metrics[$_]);
}
catch{
}
}
$Publisher.TelemetryClient.TrackException($ex)
$Publisher.TelemetryClient.Flush()
}
catch{
}
}
hidden static [void] SetCommonProperties([UsageTelemetry] $Publisher, [hashtable] $Properties)
{
try{
$NA = "NA";
$Properties.Add("InfoVersion", "V1");
try{
$Properties.Add("ScanSource", [RemoteReportHelper]::GetScanSource());
}catch{}
try{
$Properties.Add("ScannerVersion", $Publisher.GetCurrentModuleVersion());
}catch{}
try{
$Properties.Add("ControlVersion", $Publisher.GetCurrentModuleVersion());
}catch{}
try{
$azureContext = Get-AzureRmContext
try{
$Properties.Add([TelemetryKeys]::SubscriptionId, [RemoteReportHelper]::Mask($azureContext.Subscription.SubscriptionId))
}catch{}
try{
$Properties.Add([TelemetryKeys]::SubscriptionName, [RemoteReportHelper]::Mask($azureContext.Subscription.SubscriptionName))
}catch{}
try{
$Properties.Add("AzureEnv", $azureContext.Environment.Name)
}catch{}
try{
$Properties.Add("TenantId", [RemoteReportHelper]::Mask($azureContext.Tenant.TenantId))
}catch{}
try{
$Properties.Add("AccountId", [RemoteReportHelper]::Mask($azureContext.Account.Id))
}catch{}
try{
$Properties.Add("RunIdentifier", [RemoteReportHelper]::Mask($azureContext.Account.Id + '##' + $Publisher.RunIdentifier));
}catch{
$Properties.Add("RunIdentifier", $Publisher.RunIdentifier);
}
try{
$Properties.Add("AccountType", $azureContext.Account.AccountType)
}catch{}
}catch{
}
}
catch{
}
}
hidden static [string] AnonScriptStackTrace([string] $ScriptStackTrace)
{
try{
$ScriptStackTrace = $ScriptStackTrace.Replace($env:USERNAME, "USERNAME")
$lines = $ScriptStackTrace.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries)
$newLines = $lines | ForEach-Object {
$line = $_
$lineSplit = $line.Split(@(", "), [System.StringSplitOptions]::RemoveEmptyEntries);
if($lineSplit.Count -eq 2){
$filePath = $lineSplit[1];
$startMarker = $filePath.IndexOf("AzSDK")
if($startMarker -gt 0){
$anonFilePath = $filePath.Substring($startMarker, $filePath.Length - $startMarker)
$newLine = $lineSplit[0] + ", " + $anonFilePath
$newLine
}
else{
$line
}
}
else{
$line
}
}
return ($newLines | Out-String)
}
catch{
return $ScriptStackTrace
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/RemoteReports/ControlTelemetry.ps1
|
ControlTelemetry.ps1
|
Set-StrictMode -Version Latest
class ControlTelemetry: ListenerBase {
[Microsoft.ApplicationInsights.TelemetryClient] $TelemetryClient;
hidden ControlTelemetry() {
$this.TelemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new()
}
hidden static [ControlTelemetry] $Instance = $null;
static [ControlTelemetry] GetInstance() {
if ( $null -eq [ControlTelemetry]::Instance -or $null -eq [ControlTelemetry]::Instance.TelemetryClient) {
[ControlTelemetry]::Instance = [ControlTelemetry]::new();
}
return [ControlTelemetry]::Instance
}
[void] RegisterEvents() {
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [ControlTelemetry]::GetInstance();
try
{
$runIdentifier = [AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1)
$currentInstance.SetRunIdentifier($runIdentifier);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
if(![RemoteReportHelper]::IsControlTelemetryEnabled()){ return; };
$currentInstance = [ControlTelemetry]::GetInstance();
$currentInstance.TelemetryClient.InstrumentationKey = [RemoteReportHelper]::GetControlTelemetryKey();
try
{
$invocationContext = [System.Management.Automation.InvocationInfo] $currentInstance.InvocationContext
$featureGroup = [RemoteReportHelper]::GetFeatureGroup($invocationContext.MyCommand.Name)
$SVTEventContexts = [SVTEventContext[]] $Event.SourceArgs
if($featureGroup -eq [FeatureGroup]::Subscription){
[ControlTelemetry]::PushSubscriptionScanResults($currentInstance, $SVTEventContexts)
}elseif($featureGroup -eq [FeatureGroup]::Service){
[ControlTelemetry]::PushServiceScanResults($currentInstance, $SVTEventContexts)
}else{
}
}
catch
{
$currentInstance.PublishException($_);
}
$currentInstance.TelemetryClient.Flush()
});
}
static [void] PushSubscriptionScanResults(
[ControlTelemetry] $Publisher, `
[SVTEventContext[]] $SVTEventContexts)
{
$eventData = @{
[TelemetryKeys]::FeatureGroup = [FeatureGroup]::Subscription;
"ScanKind" = [RemoteReportHelper]::GetSubscriptionScanKind(
$Publisher.InvocationContext.MyCommand.Name,
$Publisher.InvocationContext.BoundParameters);
}
$SVTEventContexts | ForEach-Object {
$context = $_
[hashtable] $eventDataClone = $eventData.Clone();
$eventDataClone.Add("ControlIntId", $context.ControlItem.Id);
$eventDataClone.Add("ControlId", $context.ControlItem.ControlID);
$eventDataClone.Add("ControlSeverity", $context.ControlItem.ControlSeverity);
if ($context.ControlItem.Enabled) {
$eventDataClone.Add("ActualVerificationResult", $context.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $context.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $context.ControlResults[0].VerificationResult)
}
else {
$eventDataClone.Add("ActualVerificationResult", [VerificationResult]::Disabled)
$eventDataClone.Add("AttestationStatus", [AttestationStatus]::None)
$eventDataClone.Add("VerificationResult", [VerificationResult]::Disabled)
}
[ControlTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
}
static [void] PushServiceScanResults(
[ControlTelemetry] $Publisher, `
[SVTEventContext[]] $SVTEventContexts)
{
$NA = "NA"
$SVTEventContextFirst = $SVTEventContexts[0]
$eventData = @{
[TelemetryKeys]::FeatureGroup = [FeatureGroup]::Service;
"ScanKind" = [RemoteReportHelper]::GetServiceScanKind(
$Publisher.InvocationContext.MyCommand.Name,
$Publisher.InvocationContext.BoundParameters);
"Feature" = $SVTEventContextFirst.FeatureName;
"ResourceGroup" = $SVTEventContextFirst.ResourceContext.ResourceGroupName;
"ResourceName" = $SVTEventContextFirst.ResourceContext.ResourceName;
"ResourceId" = $SVTEventContextFirst.ResourceContext.ResourceId;
}
$SVTEventContexts | ForEach-Object {
$SVTEventContext = $_
[hashtable] $eventDataClone = $eventData.Clone()
$eventDataClone.Add("ControlIntId", $SVTEventContext.ControlItem.Id);
$eventDataClone.Add("ControlId", $SVTEventContext.ControlItem.ControlID);
$eventDataClone.Add("ControlSeverity", $SVTEventContext.ControlItem.ControlSeverity);
if (!$SVTEventContext.ControlItem.Enabled) {
$eventDataClone.Add("VerificationResult", [VerificationResult]::Disabled)
$eventDataClone.Add("AttestationStatus", [AttestationStatus]::None)
$eventDataClone.Add("VerificationResult", [VerificationResult]::Disabled)
[ControlTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
($SVTEventContextFirst.ResourceContext.ResourceName -eq $SVTEventContext.ControlResults[0].ChildResourceName -or `
[string]::IsNullOrWhiteSpace($SVTEventContext.ControlResults[0].ChildResourceName)))
{
$eventDataClone.Add("ActualVerificationResult", $SVTEventContext.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $SVTEventContext.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $SVTEventContext.ControlResults[0].VerificationResult)
$eventDataClone.Add("IsNestedResource", 'No')
$eventDataClone.Add("NestedResourceName", $NA)
[ControlTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -eq 1 -and `
$SVTEventContextFirst.ResourceContext.ResourceName -ne $SVTEventContext.ControlResults[0].ChildResourceName)
{
$eventDataClone.Add("ActualVerificationResult", $SVTEventContext.ControlResults[0].ActualVerificationResult)
$eventDataClone.Add("AttestationStatus", $SVTEventContext.ControlResults[0].AttestationStatus)
$eventDataClone.Add("VerificationResult", $SVTEventContext.ControlResults[0].VerificationResult)
$eventDataClone.Add("IsNestedResource", 'Yes')
$eventDataClone.Add("NestedResourceName", $SVTEventContext.ControlResults[0].ChildResourceName)
[ControlTelemetry]::PushEvent($Publisher, $eventDataClone, @{})
}
elseif ($SVTEventContext.ControlResults.Count -gt 1)
{
$eventDataClone.Add("IsNestedResource", 'Yes')
$SVTEventContext.ControlResults | Foreach-Object {
[hashtable] $eventDataCloneL2 = $eventDataClone.Clone()
$eventDataCloneL2.Add("ActualVerificationResult", $_.ActualVerificationResult)
$eventDataCloneL2.Add("AttestationStatus", $_.AttestationStatus)
$eventDataCloneL2.Add("VerificationResult", $_.VerificationResult)
$eventDataCloneL2.Add("NestedResourceName", $_.ChildResourceName)
[ControlTelemetry]::PushEvent($Publisher, $eventDataCloneL2, @{})
}
}
}
}
static [void] PushEvent([ControlTelemetry] $Publisher, `
[hashtable] $Properties, [hashtable] $Metrics)
{
try{
[ControlTelemetry]::SetCommonProperties($Publisher, $Properties);
$event = [Microsoft.ApplicationInsights.DataContracts.EventTelemetry]::new()
$event.Name = "Control Scanned"
$Properties.Keys | ForEach-Object {
try{
$event.Properties.Add($_, $Properties[$_].ToString());
}
catch{
}
}
$Metrics.Keys | ForEach-Object {
try{
$event.Metrics.Add($_, $Metrics[$_]);
}
catch{
}
}
$Publisher.TelemetryClient.TrackEvent($event);
}
catch{
}
}
hidden static [void] SetCommonProperties([ControlTelemetry] $Publisher, [hashtable] $Properties)
{
try{
$NA = "NA";
$Properties.Add("InfoVersion", "V1");
try{
$Properties.Add("ScanSource", [RemoteReportHelper]::GetScanSource());
}catch{}
try{
$Properties.Add("ScannerVersion", $Publisher.GetCurrentModuleVersion());
}catch{}
try{
$Properties.Add("ControlVersion", $Publisher.GetCurrentModuleVersion());
}catch{}
try{
$azureContext = Get-AzureRmContext
try{
$Properties.Add([TelemetryKeys]::SubscriptionId, $azureContext.Subscription.SubscriptionId)
}catch{}
try{
$Properties.Add([TelemetryKeys]::SubscriptionName, $azureContext.Subscription.SubscriptionName)
}catch{}
try{
$Properties.Add("AzureEnv", $azureContext.Environment.Name)
}catch{}
try{
$Properties.Add("TenantId", $azureContext.Tenant.TenantId)
}catch{}
try{
$Properties.Add("AccountId", $azureContext.Account.Id)
}catch{}
try{
$Properties.Add("RunIdentifier", [RemoteReportHelper]::Mask($azureContext.Account.Id + '##' + $Publisher.RunIdentifier));
}catch{
$Properties.Add("RunIdentifier", $Publisher.RunIdentifier);
}
try{
$Properties.Add("AccountType", $azureContext.Account.AccountType)
}catch{}
}catch{
}
}
catch{
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/UserReports/WriteDataFile.ps1
|
WriteDataFile.ps1
|
Set-StrictMode -Version Latest
class WriteDataFile: FileOutputBase
{
hidden static [WriteDataFile] $Instance = $null;
hidden [int] $JsonDepth = 10;
static [WriteDataFile] GetInstance()
{
if ( $null -eq [WriteDataFile]::Instance)
{
[WriteDataFile]::Instance = [WriteDataFile]::new();
}
return [WriteDataFile]::Instance
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [WriteDataFile]::GetInstance();
try
{
$currentInstance.SetRunIdentifier([AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandStarted, {
$currentInstance = [WriteDataFile]::GetInstance();
try
{
$currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, [FileOutputBase]::ETCFolderPath, ("SecurityEvaluationData-" + $currentInstance.RunIdentifier + ".json"));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandCompleted, {
$currentInstance = [WriteDataFile]::GetInstance();
try
{
$currentInstance.WriteToJson($Event.SourceArgs);
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
}
[void] WriteToJson([SVTEventContext[]] $arguments)
{
if ([string]::IsNullOrEmpty($this.FilePath)) {
return;
}
if($arguments)
{
if (($arguments | Measure-Object).Count -gt 0)
{
#[SVTEventResult[]] $result = @();
#$arguments | ForEach-Object {
# $result += [SVTEventResult]::new($_);
#}
#if ($result.Count -gt 0) {
# #$result | ConvertTo-Json -Depth $this.JsonDepth | Out-File $this.FilePath
# #[Helpers]::ConvertToJsonCustom($result) | Out-File $($this.FilePath.Replace(".json", ".custom.json"))
# [Helpers]::ConvertToJsonCustom($result) | Out-File $this.FilePath
# [Helpers]::ConvertToPson($result) | Out-File $($this.FilePath.Replace(".json", ".pson"))
#}
[Helpers]::ConvertToJsonCustom($arguments) | Out-File $this.FilePath
[Helpers]::ConvertToPson($arguments) | Out-File $($this.FilePath.Replace(".json", ".pson"))
}
}
}
}
class SVTEventResult
{
[ResourceContext] $ResourceContext
[ControlItem] $ControlItem
[ControlResultData[]] $ControlResults = @()
[string] $ExceptionMessage
SVTEventResult ([SVTEventContext] $context)
{
$this.ResourceContext = $context.ResourceContext;
$this.ControlItem = $context.ControlItem;
if($context.ExceptionMessage)
{
$this.ExceptionMessage = $context.ExceptionMessage.ToString();
}
if($context.ControlResults)
{
$context.ControlResults |
ForEach-Object {
$this.ControlResults += [ControlResultData]::new($_);
}
}
}
}
class ControlResultData
{
[string] $ChildResourceName = ""
[string] $VerificationResult = ""
[MessageDataObject[]] $Messages = @();
ControlResultData([ControlResult] $result)
{
$this.ChildResourceName = $result.ChildResourceName;
$this.VerificationResult = $result.VerificationResult.ToString();
if($result.Messages)
{
$result.Messages |
ForEach-Object {
$this.Messages += [MessageDataObject]::new($_);
}
}
}
}
class MessageDataObject
{
[string] $MessageType = "";
[string] $Message = "";
#[bool] $MaintainState = $false;
[PSObject] $DataObject;
#[string] $DataObjectType;
MessageDataObject([MessageData] $message)
{
$this.MessageType = $message.MessageType.ToString();
$this.Message = $message.Message;
if($message.DataObject)
{
<#if ($message.DataObject.GetType().FullName -eq "System.Management.Automation.ErrorRecord")
{
if([string]::IsNullOrEmpty($message.Message))
{
$this.Message = $message.DataObject.ToString();
}
else
{
$this.DataObject = $message.DataObject.ToString();
}
}
else
{#>
try
{
[Helpers]::ConvertToJsonCustom($message.DataObject);
$this.DataObject = $message.DataObject;
}
catch
{
$this.DataObject = $message.DataObject | Out-String;
}
#}
}
#$this.MaintainState = $message.MaintainState;
#$this.DataObjectType = $message.DataObjectType;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/UserReports/WriteFolderPath.ps1
|
WriteFolderPath.ps1
|
Set-StrictMode -Version Latest
class WriteFolderPath: FileOutputBase
{
hidden static [WriteFolderPath] $Instance = $null;
static [WriteFolderPath] GetInstance()
{
if ($null -eq [WriteFolderPath]::Instance)
{
[WriteFolderPath]::Instance = [WriteFolderPath]::new();
}
return [WriteFolderPath]::Instance
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [WriteFolderPath]::GetInstance();
try
{
$currentInstance.SetRunIdentifier([AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandStarted, {
$currentInstance = [WriteFolderPath]::GetInstance();
try
{
$currentInstance.CommandStartedAction($Event.SourceArgs.SubscriptionContext);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandStarted, {
$currentInstance = [WriteFolderPath]::GetInstance();
try
{
$currentInstance.CommandStartedAction($Event.SourceArgs.SubscriptionContext);
}
catch
{
$currentInstance.PublishException($_);
}
});
}
[void] CommandStartedAction([SubscriptionContext] $context)
{
$this.SetFolderPath($context);
Copy-Item $PSScriptRoot\Readme.txt $this.FolderPath
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/UserReports/WriteDetailedLog.ps1
|
WriteDetailedLog.ps1
|
Set-StrictMode -Version Latest
class WriteDetailedLog: FileOutputBase
{
hidden static [WriteDetailedLog] $Instance = $null;
static [WriteDetailedLog] GetInstance()
{
if ( $null -eq [WriteDetailedLog]::Instance)
{
[WriteDetailedLog]::Instance = [WriteDetailedLog]::new();
}
return [WriteDetailedLog]::Instance
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
$currentInstance.SetRunIdentifier([AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationStarted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
if($Event.SourceArgs.IsResource())
{
$currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, $Event.SourceArgs.ResourceContext.ResourceGroupName, ($Event.SourceArgs.FeatureName + ".log"));
$startHeading = ([Constants]::ModuleStartHeading -f $Event.SourceArgs.FeatureName, $Event.SourceArgs.ResourceContext.ResourceGroupName, $Event.SourceArgs.ResourceContext.ResourceName);
}
else
{
$currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, $Event.SourceArgs.SubscriptionContext.SubscriptionName, ($Event.SourceArgs.FeatureName + ".log"));
$startHeading = ([Constants]::ModuleStartHeadingSub -f $Event.SourceArgs.FeatureName, $Event.SourceArgs.SubscriptionContext.SubscriptionName, $Event.SourceArgs.SubscriptionContext.SubscriptionId);
}
$currentInstance.AddOutputLog($startHeading);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
$props = $Event.SourceArgs[0];
if($props.IsResource())
{
$currentInstance.AddOutputLog(([Constants]::CompletedAnalysis -f $props.FeatureName, $props.ResourceContext.ResourceGroupName, $props.ResourceContext.ResourceName));
}
else
{
$currentInstance.AddOutputLog(([Constants]::CompletedAnalysisSub -f $props.FeatureName, $props.SubscriptionContext.SubscriptionName, $props.SubscriptionContext.SubscriptionId));
}
$currentInstance.AddOutputLog([Constants]::HashLine);
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::ControlStarted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
$currentInstance.AddOutputLog([Constants]::DoubleDashLine);
$currentInstance.AddOutputLog("[$($Event.SourceArgs.ControlItem.ControlID)]: $($Event.SourceArgs.ControlItem.Description)");
$currentInstance.AddOutputLog([Constants]::SingleDashLine);
if($Event.SourceArgs.IsResource())
{
$currentInstance.AddOutputLog(("Info: Checking: [{0}]-[$($Event.SourceArgs.ControlItem.Description)] for resource [{1}]" -f
$Event.SourceArgs.FeatureName,
$Event.SourceArgs.ResourceContext.ResourceName),
$true);
}
else
{
$currentInstance.AddOutputLog(("Info: Checking: [{0}]-[$($Event.SourceArgs.ControlItem.Description)] for subscription [{1}]" -f
$Event.SourceArgs.FeatureName,
$Event.SourceArgs.SubscriptionContext.SubscriptionName),
$true);
}
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::ControlCompleted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
$currentInstance.WriteControlResult([SVTEventContext] ($Event.SourceArgs | Select-Object -First 1 ));
$currentInstance.AddOutputLog(([Constants]::DoubleDashLine + " `r`n`r`n "));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandStarted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
$currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, $Event.SourceArgs.SubscriptionContext.SubscriptionName, "Detailed.log");
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandProcessing, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
if($Event.SourceArgs.Messages)
{
$Event.SourceArgs.Messages | ForEach-Object {
$currentInstance.AddOutputLog($_);
}
}
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandCompleted, {
$currentInstance = [WriteDetailedLog]::GetInstance();
try
{
if($Event.SourceArgs.Messages)
{
$Event.SourceArgs.Messages | ForEach-Object {
$currentInstance.AddOutputLog($_);
}
}
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
}
hidden [void] AddOutputLog([string] $message, [bool] $includeTimeStamp)
{
if([string]::IsNullOrEmpty($message) -or [string]::IsNullOrEmpty($this.FilePath))
{
return;
}
if($includeTimeStamp)
{
$message = (Get-Date -format "MM\/dd\/yyyy HH:mm:ss") + "-" + $message
}
Add-Content -Value $message -Path $this.FilePath
}
hidden [void] AddOutputLog([string] $message)
{
$this.AddOutputLog($message, $false);
}
hidden [void] AddOutputLog([MessageData] $messageData)
{
if($messageData)
{
if (-not [string]::IsNullOrEmpty($messageData.Message))
{
$this.AddOutputLog("`r`n`r`n" + $messageData.Message);
}
if ($messageData.DataObject) {
if (-not [string]::IsNullOrEmpty($messageData.Message))
{
$this.AddOutputLog("`r`n");
}
$this.AddOutputLog([Helpers]::ConvertObjectToString($messageData.DataObject, $false));
}
}
}
hidden [void] WriteControlResult([SVTEventContext] $eventContext)
{
if($eventContext.ControlResults -and $eventContext.ControlResults.Count -ne 0)
{
$controlDesc = $eventContext.ControlItem.Description;
$eventContext.ControlResults | Foreach-Object {
if(-not [string]::IsNullOrWhiteSpace($_.ChildResourceName))
{
$this.AddOutputLog("`r`n"+([Constants]::SingleDashLine));
$this.AddOutputLog(("Info: Checking: [{0}]-[$controlDesc] for resource [{1}]" -f
$eventContext.FeatureName,
$_.ChildResourceName),
$true);
}
$_.Messages | ForEach-Object {
$this.AddOutputLog($_);
}
# Add attestation data to log
if($_.StateManagement -and $_.StateManagement.AttestedStateData)
{
$this.AddOutputLog([Constants]::SingleDashLine);
$this.AddOutputLog("Attestation Data");
$stateObject = $_.StateManagement.AttestedStateData;
$this.AddOutputLog("Justification: $($stateObject.Justification)");
$this.AddOutputLog("Attested by: [$($stateObject.AttestedBy)] on [$($stateObject.AttestedDate)]");
if([string]::IsNullOrWhiteSpace($stateObject.Message))
{
$this.AddOutputLog($stateObject.Message);
}
if ($stateObject.DataObject)
{
if (-not [string]::IsNullOrEmpty($stateObject.Message))
{
$this.AddOutputLog("`r`n");
}
$this.AddOutputLog([Helpers]::ConvertObjectToString($stateObject.DataObject, $false));
}
}
$this.AddOutputLog("`r`n");
$this.AddOutputLog([Constants]::SingleDashLine);
if($eventContext.IsResource())
{
$resourceName = $eventContext.ResourceContext.ResourceName;
if(-not [string]::IsNullOrWhiteSpace($_.ChildResourceName))
{
$resourceName = $_.ChildResourceName;
}
$this.AddOutputLog(("**{3}**: [{0}]-[{2}] for resource: [{1}]" -f
$eventContext.FeatureName,
$resourceName,
$eventContext.ControlItem.Description,
$_.VerificationResult.ToString()));
}
else
{
$this.AddOutputLog(("**{3}**: [{0}]-[{2}] for subscription: [{1}]" -f
$eventContext.FeatureName,
$eventContext.SubscriptionContext.SubscriptionName,
$eventContext.ControlItem.Description,
$_.VerificationResult.ToString()));
}
}
}
else
{
$this.AddOutputLog("`r`n");
$this.AddOutputLog([Constants]::SingleDashLine);
$this.AddOutputLog(("**Disabled**: [{0}]-[{1}]" -f
$eventContext.FeatureName,
$eventContext.ControlItem.Description));
}
$this.AddOutputLog([Constants]::SingleDashLine);
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/UserReports/WritePsConsole.ps1
|
WritePsConsole.ps1
|
Set-StrictMode -Version Latest
class WritePsConsole: FileOutputBase
{
hidden static [WritePsConsole] $Instance = $null;
static [WritePsConsole] GetInstance()
{
if ($null -eq [WritePsConsole]::Instance)
{
[WritePsConsole]::Instance = [WritePsConsole]::new();
}
return [WritePsConsole]::Instance
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
# Mandatory: Generate Run Identifier Event
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.SetRunIdentifier([AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkGenericEvent]::CustomMessage, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
if($Event.SourceArgs)
{
$messages = @();
$messages += $Event.SourceArgs;
$messages | ForEach-Object {
$currentInstance.WriteMessageData($_);
}
}
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkGenericEvent]::Exception, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage(($Event.SourceArgs | Select-Object -First 1), [MessageType]::Error);
}
catch
{
#Consuming the exception intentionally to prevent infinite loop of errors
#$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CustomMessage, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
if($Event.SourceArgs -and $Event.SourceArgs.Messages)
{
$Event.SourceArgs.Messages | ForEach-Object {
$currentInstance.WriteMessageData($_);
}
}
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandStarted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.CommandStartedAction($Event);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandError, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage($Event.SourceArgs.ExceptionMessage, [MessageType]::Error);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::CommandCompleted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage([Constants]::DoubleDashLine, [MessageType]::Info)
$currentInstance.WriteMessage("Info: Logs has been exported to path - $([WriteFolderPath]::GetInstance().FolderPath)", [MessageType]::Info)
$currentInstance.WriteMessage([Constants]::DoubleDashLine, [MessageType]::Info)
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
# SVT events
$this.RegisterEvent([SVTEvent]::CommandStarted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.CommandStartedAction($Event);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandError, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage($Event.SourceArgs.ExceptionMessage, [MessageType]::Error);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandCompleted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage([Constants]::DoubleDashLine, [MessageType]::Info)
if(($Event.SourceArgs | Measure-Object).Count -gt 0)
{
$currentInstance.WriteMessage([Constants]::RemediationMsg, [MessageType]::Info)
$currentInstance.WriteMessage([Constants]::SingleDashLine, [MessageType]::Info)
}
$currentInstance.WriteMessage("Info: Status and detailed logs has been exported to path - $([WriteFolderPath]::GetInstance().FolderPath)", [MessageType]::Info)
$currentInstance.WriteMessage([Constants]::DoubleDashLine, [MessageType]::Info)
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationStarted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
if($Event.SourceArgs.IsResource())
{
$startHeading = ([Constants]::ModuleStartHeading -f $Event.SourceArgs.FeatureName, $Event.SourceArgs.ResourceContext.ResourceGroupName, $Event.SourceArgs.ResourceContext.ResourceName);
}
else
{
$startHeading = ([Constants]::ModuleStartHeadingSub -f $Event.SourceArgs.FeatureName, $Event.SourceArgs.SubscriptionContext.SubscriptionName, $Event.SourceArgs.SubscriptionContext.SubscriptionId);
}
$currentInstance.WriteMessage($startHeading, [MessageType]::Info);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$props = $Event.SourceArgs[0];
if($props.IsResource())
{
$currentInstance.WriteMessage(([Constants]::CompletedAnalysis -f $props.FeatureName, $props.ResourceContext.ResourceGroupName, $props.ResourceContext.ResourceName), [MessageType]::Update);
}
else
{
$currentInstance.WriteMessage(([Constants]::CompletedAnalysisSub -f $props.FeatureName, $props.SubscriptionContext.SubscriptionName, $props.SubscriptionContext.SubscriptionId), [MessageType]::Update);
}
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::EvaluationError, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage($Event.SourceArgs.ExceptionMessage, [MessageType]::Error);
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::ControlStarted, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
if($Event.SourceArgs.IsResource())
{
$AnalysingControlHeadingMsg =([Constants]::AnalysingControlHeading -f $Event.SourceArgs.FeatureName,$Event.SourceArgs.ControlItem.Description,$Event.SourceArgs.ResourceContext.ResourceName)
}
else
{
$AnalysingControlHeadingMsg =([Constants]::AnalysingControlHeadingSub -f $Event.SourceArgs.FeatureName,$Event.SourceArgs.ControlItem.Description,$Event.SourceArgs.SubscriptionContext.SubscriptionName)
}
$currentInstance.WriteMessage($AnalysingControlHeadingMsg, [MessageType]::Info)
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::ControlDisabled, {
$currentInstance = [WritePsConsole]::GetInstance();
try
{
$currentInstance.WriteMessage(("**Disabled**: [{0}]-[{1}]" -f
$Event.SourceArgs.FeatureName,
$Event.SourceArgs.ControlItem.Description), [MessageType]::Warning);
}
catch
{
$currentInstance.PublishException($_);
}
});
}
#Write message on powershell console with appropriate color
[void] WriteMessage([PSObject] $message, [MessageType] $messageType)
{
if(-not $message)
{
return;
}
$colorCode = [System.ConsoleColor]::White
switch($messageType)
{
([MessageType]::Critical) {
$colorCode = [System.ConsoleColor]::Red
}
([MessageType]::Error) {
$colorCode = [System.ConsoleColor]::Red
}
([MessageType]::Warning) {
$colorCode = [System.ConsoleColor]::Yellow
}
([MessageType]::Info) {
$colorCode = [System.ConsoleColor]::Cyan
}
([MessageType]::Update) {
$colorCode = [System.ConsoleColor]::Green
}
([MessageType]::Deprecated) {
$colorCode = [System.ConsoleColor]::DarkYellow
}
}
# FilePath check ensures to print detailed error objects on PS host
$formattedMessage = [Helpers]::ConvertObjectToString($message, (-not [string]::IsNullOrEmpty($this.FilePath)));
Write-Host $formattedMessage -ForegroundColor $colorCode
#if($message.GetType().FullName -eq "System.Management.Automation.ErrorRecord")
#{
$this.AddOutputLog([Helpers]::ConvertObjectToString($message, $false));
#}
#else
#{
# $this.AddOutputLog($message);
#}
}
hidden [void] WriteMessage([PSObject] $message)
{
$this.WriteMessage($message, [MessageType]::Info);
}
hidden [void] WriteMessageData([MessageData] $messageData)
{
if($messageData)
{
$this.WriteMessage(("`r`n" + $messageData.Message), $messageData.MessageType);
if($messageData.DataObject)
{
if (-not [string]::IsNullOrEmpty($messageData.Message))
{
$this.WriteMessage("`r`n");
}
$this.WriteMessage($messageData.DataObject, $messageData.MessageType);
}
}
}
hidden [void] AddOutputLog([string] $message, [bool] $includeTimeStamp)
{
if([string]::IsNullOrEmpty($message) -or [string]::IsNullOrEmpty($this.FilePath))
{
return;
}
if($includeTimeStamp)
{
$message = (Get-Date -format "MM\/dd\/yyyy HH:mm:ss") + "-" + $message
}
Add-Content -Value $message -Path $this.FilePath
}
hidden [void] AddOutputLog([string] $message)
{
$this.AddOutputLog($message, $false);
}
hidden [void] CommandStartedAction($event)
{
$arg = $event.SourceArgs | Select-Object -First 1;
$this.SetFilePath($arg.SubscriptionContext, [FileOutputBase]::ETCFolderPath, "PowerShellOutput.log");
$currentVersion = $this.GetCurrentModuleVersion();
$moduleName = $this.GetModuleName();
$this.WriteMessage([Constants]::DoubleDashLine + "`r`n$moduleName Version: $currentVersion `r`n" + [Constants]::DoubleDashLine , [MessageType]::Info);
# Version check message
if($arg.Messages)
{
$arg.Messages | ForEach-Object {
$this.WriteMessageData($_);
}
}
$this.WriteMessage("Method Name: $($this.InvocationContext.MyCommand.Name) `r`nInput Parameters: $(($this.InvocationContext.BoundParameters | Out-String).TrimEnd()) `r`n" + [Constants]::DoubleDashLine , [MessageType]::Info);
$this.WriteMessage([ConfigurationManager]::GetAzSdkConfigData().PolicyMessage,[MessageType]::Warning)
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/UserReports/WriteSummaryFile.ps1
|
WriteSummaryFile.ps1
|
Set-StrictMode -Version Latest
class WriteSummaryFile: FileOutputBase
{
hidden static [WriteSummaryFile] $Instance = $null;
static [WriteSummaryFile] GetInstance()
{
if ( $null -eq [WriteSummaryFile]::Instance)
{
[WriteSummaryFile]::Instance = [WriteSummaryFile]::new();
}
return [WriteSummaryFile]::Instance
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
$this.RegisterEvent([AzSdkRootEvent]::GenerateRunIdentifier, {
$currentInstance = [WriteSummaryFile]::GetInstance();
try
{
$currentInstance.SetRunIdentifier([AzSdkRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandStarted, {
$currentInstance = [WriteSummaryFile]::GetInstance();
try
{
$currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, ("SecurityReport-" + $currentInstance.RunIdentifier + ".csv"));
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([SVTEvent]::CommandCompleted, {
$currentInstance = [WriteSummaryFile]::GetInstance();
try
{
$currentInstance.WriteToCSV($Event.SourceArgs);
$currentInstance.FilePath = "";
}
catch
{
$currentInstance.PublishException($_);
}
});
$this.RegisterEvent([AzSdkRootEvent]::UnsupportedResources, {
$currentInstance = [WriteSummaryFile]::GetInstance();
try
{
$message = $Event.SourceArgs.Messages | Select-Object -First 1
if($message -and $message.DataObject)
{
$filePath = $currentInstance.CalculateFilePath($Event.SourceArgs.SubscriptionContext, [FileOutputBase]::ETCFolderPath, ("UnsupportedResources-" + $currentInstance.RunIdentifier + ".csv.log"));
$message.DataObject | Export-Csv $filePath -NoTypeInformation
}
}
catch
{
$currentInstance.PublishException($_);
}
});
}
[void] WriteToCSV([SVTEventContext[]] $arguments)
{
if ([string]::IsNullOrEmpty($this.FilePath)) {
return;
}
[CsvOutputItem[]] $csvItems = @();
$arguments | ForEach-Object {
$item = $_
if ($item -and $item.ControlResults) {
$item.ControlResults | ForEach-Object{
$csvItem = [CsvOutputItem]@{
ControlID = $item.ControlItem.ControlID;
ControlSeverity = $item.ControlItem.ControlSeverity;
Description = $item.ControlItem.Description;
FeatureName = $item.FeatureName;
ChildResourceName = $_.ChildResourceName;
Status = $_.ActualVerificationResult.ToString();
Recommendation = $item.ControlItem.Recommendation;
};
if($item.IsResource())
{
$csvItem.ResourceName = $item.ResourceContext.ResourceName;
$csvItem.ResourceGroupName = $item.ResourceContext.ResourceGroupName;
}
if($_.AttestationStatus -ne [AttestationStatus]::None)
{
$csvItem.AttestedSubStatus = $_.AttestationStatus.ToString();
$csvItem.AttestedStatus = $_.VerificationResult.ToString();
}
if($null -ne $_.StateManagement -and $null -ne $_.StateManagement.AttestedStateData)
{
$csvItem.AttesterJustification = $_.StateManagement.AttestedStateData.Justification
$csvItem.AttestedBy = $_.StateManagement.AttestedStateData.AttestedBy
}
$csvItems += $csvItem;
}
}
}
if ($csvItems.Count -gt 0) {
# Remove Null properties
$nonNullProps = @();
[CsvOutputItem].GetMembers() | Where-Object { $_.MemberType -eq [System.Reflection.MemberTypes]::Property } | ForEach-Object {
$propName = $_.Name;
if(($csvItems | Where-object { -not [string]::IsNullOrWhiteSpace($_.$propName) } | Measure-object).Count -ne 0)
{
$nonNullProps += $propName;
}
};
$csvItems | Select-Object -Property $nonNullProps | Export-Csv $this.FilePath -NoTypeInformation
}
}
}
class CsvOutputItem
{
#Fields from JSON
[string] $ControlID = ""
[string] $Status = ""
[string] $AttestedSubStatus = ""
[string] $AttestedStatus = ""
[string] $FeatureName = ""
[string] $ResourceGroupName = ""
[string] $ResourceName = ""
[string] $ChildResourceName = ""
[string] $ControlSeverity = ""
[string] $Description = ""
[string] $AttestedBy = ""
[string] $AttesterJustification = ""
[string] $Recommendation = ""
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Listeners/OMS/OMSOutput.ps1
|
OMSOutput.ps1
|
Set-StrictMode -Version Latest
class OMSOutput: ListenerBase
{
hidden static [OMSOutput] $Instance = $null;
#Default source is kept as SDL / PowerShell.
#This value must be set in respective environment i.e. CICD,CC
[string] $OMSSource;
OMSOutput()
{
}
static [OMSOutput] GetInstance()
{
if($null -eq [OMSOutput]::Instance)
{
[OMSOutput]::Instance = [OMSOutput]::new();
}
return [OMSOutput]::Instance;
}
[void] RegisterEvents()
{
$this.UnregisterEvents();
$this.RegisterEvent([SVTEvent]::ControlCompleted, {
$currentInstance = [OMSOutput]::GetInstance();
try
{
$currentInstance.WriteControlResult([SVTEventContext] ($Event.SourceArgs | Select-Object -First 1));
}
catch
{
$currentInstance.PublishException($_);
}
});
}
hidden [void] WriteControlResult([SVTEventContext] $eventContext)
{
try
{
$settings = [ConfigurationManager]::GetAzSdkSettings()
if(-not [string]::IsNullOrWhiteSpace($settings.OMSSource))
{
$this.OMSSource = $settings.OMSSource
}
if(-not [string]::IsNullOrWhiteSpace($settings.OMSWorkspaceId))
{
$tempBodyObjects = $this.GetOMSBodyObjects($this.OMSSource,$eventContext) #need to prioritze this
$tempBodyObjects | ForEach-Object{
Set-Variable -Name tempBody -Value $_ -Scope Local
$body = $tempBody | ConvertTo-Json
$this.PostOMSData($settings.OMSWorkspaceId, $settings.OMSSharedKey, ([System.Text.Encoding]::UTF8.GetBytes($body)),$settings.OMSType)
}
}
}
catch
{
[Exception] $ex = [Exception]::new(("Invalid OMS Settings: " + $_.Exception.ToString()), $_.Exception)
throw $ex
}
}
hidden [PSObject[]] GetOMSBodyObjects([string] $Source,[SVTEventContext] $eventContext)
{
[PSObject[]] $output = @();
[array] $eventContext.ControlResults | ForEach-Object{
Set-Variable -Name ControlResult -Value $_ -Scope Local
$out = "" | Select-Object ResourceType, ResourceGroup, Reference, ResourceName, ChildResourceName, ControlStatus, ActualVerificationResult, ControlId, SubscriptionName, SubscriptionId, FeatureName, Source, Recommendation, ControlSeverity, TimeTakenInMs, AttestationStatus, AttestedBy, Justification
if($eventContext.IsResource())
{
$out.ResourceType=$eventContext.ResourceContext.ResourceType
$out.ResourceGroup=$eventContext.ResourceContext.ResourceGroupName
$out.ResourceName=$eventContext.ResourceContext.ResourceName
$out.ChildResourceName=$ControlResult.ChildResourceName
}
$out.Reference=$eventContext.Metadata.Reference
$out.ControlStatus=$ControlResult.VerificationResult.ToString()
$out.ActualVerificationResult=$ControlResult.ActualVerificationResult.ToString()
$out.ControlId=$eventContext.ControlItem.ControlID
$out.SubscriptionName=$eventContext.SubscriptionContext.SubscriptionName
$out.SubscriptionId=$eventContext.SubscriptionContext.SubscriptionId
$out.FeatureName=$eventContext.FeatureName
$out.Recommendation=$eventContext.ControlItem.Recommendation
$out.ControlSeverity=$eventContext.ControlItem.ControlSeverity.ToString()
$out.Source=$Source
#mapping the attestation properties
if($null -ne $ControlResult -and $null -ne $ControlResult.StateManagement -and $null -ne $ControlResult.StateManagement.AttestedStateData)
{
$attestedData = $ControlResult.StateManagement.AttestedStateData;
$out.AttestationStatus = $ControlResult.AttestationStatus.ToString();
$out.AttestedBy = $attestedData.AttestedBy;
$out.Justification = $attestedData.Justification;
}
#$out.TimeTakenInMs=[int] $Metrics["TimeTakenInMs"]
$output += $out
}
return $output
}
hidden [string] GetOMSSignature ($OMSWorkspaceID, $SharedKey, $Date, $ContentLength, $Method, $ContentType, $Resource)
{
[string] $xHeaders = "x-ms-date:" + $Date
[string] $stringToHash = $Method + "`n" + $ContentLength + "`n" + $ContentType + "`n" + $xHeaders + "`n" + $Resource
[byte[]]$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
[byte[]]$keyBytes = [Convert]::FromBase64String($SharedKey)
[System.Security.Cryptography.HMACSHA256] $sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
[byte[]]$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $OMSWorkspaceID,$encodedHash
return $authorization
}
# Create the function to create and post the request
hidden [string] PostOMSData([string] $OMSWorkspaceID, [string] $SharedKey, $Body, $LogType)
{
[string] $method = "POST"
[string] $contentType = "application/json"
[string] $resource = "/api/logs"
$rfc1123date = [System.DateTime]::UtcNow.ToString("r")
[int] $contentLength = $Body.Length
[string] $signature = $this.GetOMSSignature($OMSWorkspaceID , $SharedKey , $rfc1123date ,$contentLength ,$method ,$contentType ,$resource)
[string] $uri = "https://" + $OMSWorkspaceID + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
[DateTime] $TimeStampField = [System.DateTime]::UtcNow
$headers = @{
"Authorization" = $signature;
"Log-Type" = $LogType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
}
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $Body -UseBasicParsing
return $response.StatusCode
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/EventBase.ps1
|
EventBase.ps1
|
using namespace System.Management.Automation
Set-StrictMode -Version Latest
# Class for providing capability to fire events
# Also includes support to fire AzSdkGenericEvent and holds InvocationContext
class EventBase
{
[string] $RunIdentifier = "default";
[InvocationInfo] $InvocationContext;
[string] GenerateRunIdentifier()
{
return $(Get-Date -format "yyyyMMdd_HHmmss");
}
hidden [void] PublishEvent([string] $eventType, [PSObject] $eventArgument)
{
New-Event -SourceIdentifier $eventType `
-Sender $this `
-EventArguments $eventArgument | Out-Null
}
[void] PublishException([ErrorRecord] $eventArgument)
{
$this.PublishEvent([AzSdkGenericEvent]::Exception, $eventArgument);
}
[void] PublishCustomMessage([MessageData[]] $messageData)
{
if($messageData)
{
$this.PublishEvent([AzSdkGenericEvent]::CustomMessage, $messageData);
}
}
[void] PublishCustomMessage([string] $message, [MessageType] $messageType)
{
$this.PublishCustomMessage([MessageData]::new($message, $messageType));
}
[void] PublishCustomMessage([string] $message, [PSObject] $dataObject)
{
$this.PublishCustomMessage([MessageData]::new($message, $dataObject));
}
[void] PublishCustomMessage([string] $message)
{
$this.PublishCustomMessage($message, [MessageType]::Info);
}
[string] GetModuleName()
{
if($this.InvocationContext)
{
return $this.InvocationContext.MyCommand.ModuleName;
}
throw [System.ArgumentException] "The parameter 'InvocationContext' is not set"
}
[System.Version] GetCurrentModuleVersion()
{
if($this.InvocationContext)
{
return [System.Version] ($this.InvocationContext.MyCommand.Version);
}
# Return default version which is 0.0.
return [System.Version]::new();
}
# Static Methods
static [void] PublishGenericException([ErrorRecord] $eventArgument)
{
[EventBase]::new().PublishException($eventArgument);
}
static [void] PublishGenericCustomMessage([string] $message)
{
[EventBase]::PublishGenericCustomMessage($message, [MessageType]::Info);
}
static [void] PublishGenericCustomMessage([string] $message, [MessageType] $messageType)
{
[EventBase]::new().PublishCustomMessage($message, $messageType);
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/SVTCommandBase.ps1
|
SVTCommandBase.ps1
|
using namespace System.Management.Automation
Set-StrictMode -Version Latest
# Base class for SVT classes being called from PS commands
# Provides functionality to fire important events at command call
class SVTCommandBase: CommandBase
{
[string[]] $ExcludeTags = @();
[string[]] $ControlIds = @();
[AttestControls] $AttestControls = [AttestControls]::None;
hidden [ControlStateExtension] $ControlStateExt;
hidden [bool] $UserHasStateAccess = $false;
SVTCommandBase([string] $subscriptionId, [InvocationInfo] $invocationContext):
Base($subscriptionId, $invocationContext)
{
[Helpers]::AbstractClass($this, [SVTCommandBase]);
}
hidden [SVTEventContext] CreateSVTEventContextObject()
{
return [SVTEventContext]@{
SubscriptionContext = $this.SubscriptionContext;
};
}
hidden [void] CommandStarted()
{
[SVTEventContext] $arg = $this.CreateSVTEventContextObject();
$versionMessage = $this.CheckModuleVersion();
if($versionMessage)
{
$arg.Messages += $versionMessage;
}
$this.PublishEvent([SVTEvent]::CommandStarted, $arg);
}
hidden [void] CommandError([System.Management.Automation.ErrorRecord] $exception)
{
[SVTEventContext] $arg = $this.CreateSVTEventContextObject();
$arg.ExceptionMessage = $exception;
$this.PublishEvent([SVTEvent]::CommandError, $arg);
}
hidden [void] CommandCompleted([SVTEventContext[]] $arguments)
{
$this.PublishEvent([SVTEvent]::CommandCompleted, $arguments);
}
[string] InvokeFunction([PSMethod] $methodToCall)
{
throw [System.NotSupportedException] "The method is not supported in the class"
}
[string] EvaluateControlStatus()
{
return ([CommandBase]$this).InvokeFunction($this.RunAllControls);
}
#hidden [SVTEventContext[]] RunAllControlsWithAttestation()
#{
# $result = $this.RunAllControls();
# if($this.AttestControls)
# {
# try
# {
# [SVTControlAttestation] $svtControlAttestation = [SVTControlAttestation]::new($result);
# $svtControlAttestation.StartControlAttestation();
# }
# catch
# {
# $this.CommandError($_);
# }
# }
# return $result;
#}
# Dummy function declaration to define the function signature
# Function is supposed to override in derived class
hidden [SVTEventContext[]] RunAllControls()
{
return @();
}
hidden [void] SetSVTBaseProperties([PSObject] $svtObject)
{
$svtObject.FilterTags = $this.ConvertToStringArray($this.FilterTags);
$svtObject.ExcludeTags = $this.ConvertToStringArray($this.ExcludeTags);
$svtObject.ControlIds = $this.ConvertToStringArray($this.ControlIds);
$this.InitializeControlState();
if($this.UserHasStateAccess)
{
$svtObject.ControlStateExt = $this.ControlStateExt;
}
}
hidden [void] InitializeControlState()
{
if(-not $this.ControlStateExt)
{
$this.ControlStateExt = [ControlStateExtension]::new();
$this.ControlStateExt.Initialize();
$this.UserHasStateAccess = $this.ControlStateExt.HasControlStateWriteAccessPermissions();
}
}
[void] PostCommandCompletedAction([SVTEventContext[]] $arguments)
{
if($this.AttestControls -ne [AttestControls]::None)
{
try
{
[SVTControlAttestation] $svtControlAttestation = [SVTControlAttestation]::new($arguments, $this.AttestControls);
$svtControlAttestation.StartControlAttestation();
}
catch
{
$this.CommandError($_);
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/CommandBase.ps1
|
CommandBase.ps1
|
using namespace System.Management.Automation
Set-StrictMode -Version Latest
# Base class for all classes being called from PS commands
# Provides functionality to fire important events at command call
class CommandBase: AzSdkRoot
{
[string[]] $FilterTags = @();
CommandBase([string] $subscriptionId, [InvocationInfo] $invocationContext):
Base($subscriptionId)
{
[Helpers]::AbstractClass($this, [CommandBase]);
if(-not $invocationContext)
{
throw [System.ArgumentException] ("The argument 'invocationContext' is null. Pass the `$PSCmdlet.MyInvocation from PowerShell command.");
}
$this.InvocationContext = $invocationContext;
}
[void] CommandStarted()
{
$this.PublishAzSdkRootEvent([AzSdkRootEvent]::CommandStarted, $this.CheckModuleVersion());
}
[void] CommandError([System.Management.Automation.ErrorRecord] $exception)
{
[AzSdkRootEventArgument] $arguments = $this.CreateRootEventArgumentObject();
$arguments.ExceptionMessage = $exception;
$this.PublishEvent([AzSdkRootEvent]::CommandError, $arguments);
}
[void] CommandCompleted([MessageData[]] $messages)
{
$this.PublishAzSdkRootEvent([AzSdkRootEvent]::CommandCompleted, $messages);
}
[string] InvokeFunction([PSMethod] $methodToCall)
{
return $this.InvokeFunction($methodToCall, @());
}
[string] InvokeFunction([PSMethod] $methodToCall, [System.Object[]] $arguments)
{
if(-not $methodToCall)
{
throw [System.ArgumentException] ("The argument 'methodToCall' is null. Pass the reference of method to call. e.g.: [YourClass]::new().YourMethod");
}
$this.PublishRunIdentifier($this.InvocationContext);
$this.CommandStarted();
$methodResult = @();
try
{
$methodResult = $methodToCall.Invoke($arguments);
}
catch
{
# Unwrapping the first layer of exception which is added by Invoke function
$this.CommandError($_.Exception.InnerException.ErrorRecord);
}
$this.CommandCompleted($methodResult);
$this.PostCommandCompletedAction($methodResult);
$folderPath = $this.GetOutputFolderPath();
$DoNotOpenOutputFolder = $this.InvocationContext.BoundParameters["DoNotOpenOutputFolder"];
if((-not $DoNotOpenOutputFolder) -and (-not [string]::IsNullOrEmpty($folderPath)))
{
try
{
Invoke-Item -Path $folderPath;
}
catch
{
#ignore if any exception occurs
}
}
return $folderPath;
}
[string] GetOutputFolderPath()
{
return [WriteFolderPath]::GetInstance().FolderPath;
}
[MessageData] CheckModuleVersion()
{
$serverVersion = [System.Version] ([ConfigurationManager]::GetAzSdkConfigData().GetLatestAzSDKVersion($this.GetModuleName()));
if($serverVersion -gt $this.GetCurrentModuleVersion())
{
return [MessageData]::new(([Constants]::VersionCheckMessage -f $serverVersion, [ConfigurationManager]::GetAzSdkConfigData().InstallationCommand), [MessageType]::Warning);
}
return $null;
}
[void] CommandProgress([int] $totalItems, [int] $currentItem)
{
$this.CommandProgress($totalItems, $currentItem, 1);
}
[void] CommandProgress([int] $totalItems, [int] $currentItem, [int] $granularity)
{
if($totalItems -gt 0)
{
# $granularity indicates the number of items after which percentage progress will be printed
# Set the max granularity to total items
if($granularity -gt $totalItems)
{
$granularity = $totalItems;
}
# conditions for posting progress: 0%, 100% and based on granularity
if($currentItem -eq 0 -or $currentItem -eq $totalItems -or (($currentItem % $granularity) -eq 0))
{
$this.PublishCustomMessage("$([int](($currentItem / $totalItems) * 100))% Completed");
}
}
}
# Dummy function declaration to define the function signature
[void] PostCommandCompletedAction([MessageData[]] $messages)
{ }
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/SVTBase.ps1
|
SVTBase.ps1
|
Set-StrictMode -Version Latest
class SVTBase: AzSdkRoot
{
hidden [string] $ResourceId = ""
[ResourceContext] $ResourceContext = $null;
hidden [SVTConfig] $SVTConfig
hidden [PSObject] $ControlSettings
#hidden [PSObject] $ControlStateIndexer = @()
#hidden [ControlState[]] $ControlStates =@()
#hidden [ControlItem] $CurrentControlItem;
hidden [ControlStateExtension] $ControlStateExt;
hidden [ControlState[]] $ResourceState;
hidden [ControlItem[]] $ApplicableControls = $null;
[string[]] $FilterTags = @();
[string[]] $ExcludeTags = @();
[string[]] $ControlIds = @();
SVTBase([string] $subscriptionId, [SVTResource] $svtResource):
Base($subscriptionId)
{
$this.CreateInstance($svtResource);
}
SVTBase([string] $subscriptionId):
Base($subscriptionId)
{
$this.CreateInstance();
}
SVTBase([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName):
Base($subscriptionId)
{
$this.CreateInstance([SVTResource]@{
ResourceGroupName = $resourceGroupName;
ResourceName = $resourceName;
});
}
hidden [void] CreateInstance()
{
[Helpers]::AbstractClass($this, [SVTBase]);
$this.LoadSvtConfig([SVTMapping]::SubscriptionMapping.JsonFileName);
#$this.ControlStateIndexer = [ControlStateManager]::ComputeControlStateIndexer();
#$this.ControlStates = $this.GetControlStates();
}
hidden [void] CreateInstance([SVTResource] $svtResource)
{
[Helpers]::AbstractClass($this, [SVTBase]);
if(-not $svtResource)
{
throw [System.ArgumentException] ("The argument 'svtResource' is null");
}
if([string]::IsNullOrEmpty($svtResource.ResourceGroupName))
{
throw [System.ArgumentException] ("The argument 'ResourceGroupName' is null or empty");
}
if([string]::IsNullOrEmpty($svtResource.ResourceName))
{
throw [System.ArgumentException] ("The argument 'ResourceName' is null or empty");
}
if(-not $svtResource.ResourceTypeMapping)
{
$svtResource.ResourceTypeMapping = [SVTMapping]::Mapping |
Where-Object { $_.ClassName -eq $this.GetType().Name } |
Select-Object -First 1
}
if (-not $svtResource.ResourceTypeMapping)
{
throw [System.ArgumentException] ("No ResourceTypeMapping found");
}
if ([string]::IsNullOrEmpty($svtResource.ResourceTypeMapping.JsonFileName))
{
throw [System.ArgumentException] ("Json file name is null or empty");
}
$this.ResourceId = $svtResource.ResourceId;
$this.LoadSvtConfig($svtResource.ResourceTypeMapping.JsonFileName);
$this.ResourceContext = [ResourceContext]@{
ResourceGroupName = $svtResource.ResourceGroupName;
ResourceName = $svtResource.ResourceName;
ResourceType = $svtResource.ResourceTypeMapping.ResourceType;
};
$this.ResourceContext.ResourceId = $this.GetResourceId();
}
hidden [void] LoadSvtConfig([string] $controlsJsonFileName)
{
$this.ControlSettings = $this.LoadServerConfigFile("ControlSettings.json");
if (-not $this.SVTConfig) {
$this.SVTConfig = [ConfigurationManager]::GetSVTConfig($controlsJsonFileName);
#Evaluate all code block in Description and Recommendation texts.
#Can use '$this.ControlSettings.xyz' in text to fill dynamic settings.
$this.SVTConfig.Controls | Foreach-Object {
$_.Description = $global:ExecutionContext.InvokeCommand.ExpandString($_.Description)
$_.Recommendation = $global:ExecutionContext.InvokeCommand.ExpandString($_.Recommendation)
if(-not [string]::IsNullOrEmpty($_.MethodName))
{
$_.MethodName = $_.MethodName.Trim();
}
}
}
}
hidden [string] GetResourceId()
{
if ([string]::IsNullOrEmpty($this.ResourceId))
{
if($this.ResourceContext)
{
$resource = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName
if($resource)
{
$this.ResourceId = $resource.ResourceId;
}
else
{
throw "Unable to find the Azure resource - [ResourceType: $($this.ResourceContext.ResourceType)] [ResourceGroupName: $($this.ResourceContext.ResourceGroupName)] [ResourceName: $($this.ResourceContext.ResourceName)]"
}
}
else
{
$this.ResourceId = $this.SubscriptionContext.Scope;
}
}
return $this.ResourceId;
}
[bool] ValidateMaintenanceState()
{
if ($this.SVTConfig.IsManintenanceMode) {
$this.PublishCustomMessage(([ConfigurationManager]::GetAzSdkConfigData().MaintenanceMessage -f $this.FeatureName), [MessageType]::Warning);
}
return $this.SVTConfig.IsManintenanceMode;
}
[ControlResult] CreateControlResult([string] $childResourceName, [VerificationResult] $verificationResult)
{
[ControlResult] $control = [ControlResult]@{
VerificationResult = $verificationResult;
};
if(-not [string]::IsNullOrEmpty($childResourceName))
{
$control.ChildResourceName = $childResourceName;
}
return $control;
}
[ControlResult] CreateControlResult()
{
return $this.CreateControlResult("", [VerificationResult]::Manual);
}
[ControlResult] CreateControlResult([string] $childResourceName)
{
return $this.CreateControlResult($childResourceName, [VerificationResult]::Manual);
}
hidden [SVTEventContext] CreateSVTEventContextObject()
{
return [SVTEventContext]@{
FeatureName = $this.SVTConfig.FeatureName;
Metadata = [Metadata]@{
Reference = $this.SVTConfig.Reference;
};
SubscriptionContext = $this.SubscriptionContext;
ResourceContext = $this.ResourceContext;
};
}
hidden [SVTEventContext] CreateErrorEventContext([System.Management.Automation.ErrorRecord] $exception)
{
[SVTEventContext] $arg = $this.CreateSVTEventContextObject();
$arg.ExceptionMessage = $exception;
return $arg;
}
hidden [void] ControlStarted([SVTEventContext] $arg)
{
$this.PublishEvent([SVTEvent]::ControlStarted, $arg);
}
hidden [void] ControlDisabled([SVTEventContext] $arg)
{
$this.PublishEvent([SVTEvent]::ControlDisabled, $arg);
}
hidden [void] ControlCompleted([SVTEventContext] $arg)
{
$this.PublishEvent([SVTEvent]::ControlCompleted, $arg);
}
hidden [void] ControlError([ControlItem] $controlItem, [System.Management.Automation.ErrorRecord] $exception)
{
$arg = $this.CreateErrorEventContext($exception);
$arg.ControlItem = $controlItem;
$this.PublishEvent([SVTEvent]::ControlError, $arg);
}
hidden [void] EvaluationCompleted([SVTEventContext[]] $arguments)
{
$this.PublishEvent([SVTEvent]::EvaluationCompleted, $arguments);
}
hidden [void] EvaluationStarted()
{
$this.PublishEvent([SVTEvent]::EvaluationStarted, $this.CreateSVTEventContextObject());
}
hidden [void] EvaluationError([System.Management.Automation.ErrorRecord] $exception)
{
$this.PublishEvent([SVTEvent]::EvaluationError, $this.CreateErrorEventContext($exception));
}
[SVTEventContext[]] EvaluateAllControls()
{
[SVTEventContext[]] $resourceSecurityResult = @();
if (-not $this.ValidateMaintenanceState()) {
if($this.GetApplicableControls().Count -eq 0)
{
$this.PublishCustomMessage("No controls have been found to evaluate for Resource [$($this.ResourceContext.ResourceName)]", [MessageType]::Warning);
}
else
{
$this.EvaluationStarted();
$resourceSecurityResult += $this.GetAutomatedSecurityStatus();
$resourceSecurityResult += $this.GetManualSecurityStatus();
$this.EvaluationCompleted($resourceSecurityResult);
}
}
return $resourceSecurityResult;
}
hidden [ControlItem[]] GetApplicableControls()
{
#Lazy load the list of the applicable controls
if($null -eq $this.ApplicableControls)
{
$this.ApplicableControls = @();
$filterControlsById = @();
if($this.ControlIds.Count -ne 0)
{
$filterControlsById += $this.SVTConfig.Controls | Where-Object { $this.ControlIds.Contains($_.ControlId) };
}
else
{
$filterControlsById += $this.SVTConfig.Controls
}
if(($this.FilterTags | Measure-Object).Count -ne 0 -or ($this.ExcludeTags | Measure-Object).Count -ne 0)
{
$filterControlsById | ForEach-Object {
Set-Variable -Name control -Value $_ -Scope Local
Set-Variable -Name filterMatch -Value $false -Scope Local
Set-Variable -Name excludeMatch -Value $false -Scope Local
$control.Tags | ForEach-Object {
Set-Variable -Name cTag -Value $_ -Scope Local
if(($this.FilterTags | Measure-Object).Count -ne 0 `
-and ($this.FilterTags | Where-Object { $_ -like $cTag} | Measure-Object).Count -ne 0)
{
$filterMatch = $true
}
elseif(($this.FilterTags | Measure-Object).Count -eq 0)
{
$filterMatch = $true
}
if(($this.ExcludeTags | Measure-Object).Count -ne 0 `
-and ($this.ExcludeTags | Where-Object { $_ -like $cTag} | Measure-Object).Count -ne 0)
{
$excludeMatch = $true
}
}
if(($filterMatch -and $excludeMatch -le 0) `
-or ($filterMatch -lt 0 -and $excludeMatch -le 0))
{
$this.ApplicableControls += $control
}
}
}
else
{
$this.ApplicableControls += $filterControlsById;
}
}
return $this.ApplicableControls;
}
hidden [SVTEventContext[]] GetManualSecurityStatus()
{
[SVTEventContext[]] $manualControlsResult = @();
try
{
$this.GetApplicableControls() | Where-Object { $_.Automated -eq "No" } |
ForEach-Object {
$controlItem = $_;
[SVTEventContext] $arg = $this.CreateSVTEventContextObject();
$arg.ControlItem = $controlItem;
$arg.ControlResults = [ControlResult]@{
VerificationResult = [VerificationResult]::Manual;
};
$this.ProcessStateData($arg);
$manualControlsResult += $arg;
}
}
catch
{
$this.EvaluationError($_);
}
return $manualControlsResult;
}
hidden [SVTEventContext[]] GetAutomatedSecurityStatus()
{
[SVTEventContext[]] $automatedControlsResult = @();
try
{
$this.GetApplicableControls() | Where-Object { -not [string]::IsNullOrEmpty($_.MethodName) } |
ForEach-Object {
$eventContext = $this.RunControl($_);
if($eventContext)
{
$automatedControlsResult += $eventContext;
}
};
}
catch
{
$this.EvaluationError($_);
}
return $automatedControlsResult;
}
hidden [SVTEventContext] RunControl([ControlItem] $controlItem)
{
[SVTEventContext] $singleControlResult = $this.CreateSVTEventContextObject();
$singleControlResult.ControlItem = $controlItem;
$this.ControlStarted($singleControlResult);
if($controlItem.Enabled -eq $false)
{
$this.ControlDisabled($singleControlResult);
}
else
{
$controlResult = $this.CreateControlResult();
try
{
$methodName = $controlItem.MethodName;
#$this.CurrentControlItem = $controlItem;
$singleControlResult.ControlResults += $this.$methodName($controlResult);
}
catch
{
$controlResult.VerificationResult = [VerificationResult]::Error
$controlResult.AddError($_);
$singleControlResult.ControlResults += $controlResult;
$this.ControlError($controlItem, $_);
}
$this.ProcessStateData($singleControlResult);
}
$this.ControlCompleted($singleControlResult);
return $singleControlResult;
}
hidden [void] ProcessStateData([SVTEventContext] $eventContext)
{
$controlState = @();
if($this.GetResourceState().Count -ne 0)
{
$controlState += $this.GetResourceState() | Where { $_.InternalId -eq $eventContext.ControlItem.Id };
}
$eventContext.ControlResults |
ForEach-Object {
$currentItem = $_;
# Copy the current result to Actual Result field
$currentItem.ActualVerificationResult = $currentItem.VerificationResult
if($controlState.Count -ne 0)
{
# Skip passed ones from State Management
if($currentItem.VerificationResult -ne [VerificationResult]::Passed)
{
# Process the state if its available
$childResourceState = $controlState | Where-Object { $_.ChildResourceName -eq $currentItem.ChildResourceName } | Select-Object -First 1;
if($childResourceState -and ($childResourceState.ActualVerificationResult -eq $currentItem.ActualVerificationResult) -and $childResourceState.State)
{
$currentItem.StateManagement.AttestedStateData = $childResourceState.State;
# Compare dataobject property of State
if($childResourceState.State.DataObject)
{
if($currentItem.StateManagement.CurrentStateData -and $currentItem.StateManagement.CurrentStateData.DataObject)
{
if([Helpers]::CompareObject($childResourceState.State.DataObject, $currentItem.StateManagement.CurrentStateData.DataObject))
{
# Objects match, change result based on attestation status
$this.ModifyControlResult($currentItem, $childResourceState);
}
#else
#{
# Drift in security state. Objects are not matching. No modification of result required
#}
}
#else
#{
# Drift in security state. Control State found but no dataobject is passed in current execution
#}
}
else
{
# No object is persisted, change result based on attestation status
$this.ModifyControlResult($currentItem, $childResourceState);
}
}
#else
#{
# No state object found which matches the verification result. Ignore the state. No modification of result required
#}
}
#else
#{
# Ignore State for passed ones. No modification of result required
#}
}
};
}
# State Machine implementation of modifying verification result
hidden [void] ModifyControlResult([ControlResult] $controlResult, [ControlState] $controlState)
{
# No action required if Attestation status is None OR verification result is Passed
if($controlState.AttestationStatus -ne [AttestationStatus]::None -or $controlResult.VerificationResult -ne [VerificationResult]::Passed)
{
$controlResult.AttestationStatus = $controlState.AttestationStatus;
$controlResult.VerificationResult = [Helpers]::EvaluateVerificationResult($controlResult.VerificationResult, $controlState.AttestationStatus);
}
}
hidden [ControlState[]] GetResourceState()
{
if($null -eq $this.ResourceState)
{
$this.ResourceState = @();
if($this.ControlStateExt)
{
$this.ResourceState += $this.ControlStateExt.GetControlState($this.GetResourceId());
}
}
return $this.ResourceState;
}
hidden [ControlResult] CheckDiagnosticsSettings([ControlResult] $controlResult)
{
$diagnostics = Get-AzureRmDiagnosticSetting -ResourceId $this.GetResourceId()
if($diagnostics -and ($diagnostics.Logs | Measure-Object).Count -ne 0)
{
$nonCompliantLogs = $diagnostics.Logs |
Where-Object { -not ($_.Enabled -and
($_.RetentionPolicy.Days -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Forever -or
$_.RetentionPolicy.Days -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Min))};
$selectedDiagnosticsProps = $diagnostics | Select-Object -Property Logs, Metrics, StorageAccountId, ServiceBusRuleId, Name;
if(($nonCompliantLogs | Measure-Object).Count -eq 0)
{
$controlResult.AddMessage([VerificationResult]::Passed,
"Diagnostics settings are correctly configured for resource - [$($this.ResourceContext.ResourceName)]",
$selectedDiagnosticsProps);
}
else
{
$controlResult.AddMessage([VerificationResult]::Failed,
"Diagnostics settings are either disabled OR not retaining logs for atleast $($this.ControlSettings.Diagnostics_RetentionPeriod_Min) days for resource - [$($this.ResourceContext.ResourceName)]",
$selectedDiagnosticsProps);
}
}
else
{
$controlResult.AddMessage("Not able to fetch diagnostics settings. Please validate diagnostics settings manually for resource - [$($this.ResourceContext.ResourceName)].");
}
return $controlResult;
}
hidden [ControlResult] CheckRBACAccess([ControlResult] $controlResult)
{
$accessList = [RoleAssignmentHelper]::GetAzSDKRoleAssignmentByScope($this.GetResourceId(), $false, $true);
$resourceAccessList = $accessList | Where-Object { $_.Scope -eq $this.GetResourceId() };
$controlResult.VerificationResult = [VerificationResult]::Verify;
if(($resourceAccessList | Measure-Object).Count -ne 0)
{
$controlResult.SetStateData("Identities having RBAC access at resource level", $resourceAccessList);
$controlResult.AddMessage("Validate that the following identities have explicitly provided with RBAC access to resource - [$($this.ResourceContext.ResourceName)]");
$controlResult.AddMessage([MessageData]::new($this.CreateRBACCountMessage($resourceAccessList), $resourceAccessList));
}
else
{
$controlResult.AddMessage("No identities have been explicitly provided with RBAC access to resource - [$($this.ResourceContext.ResourceName)]");
}
$inheritedAccessList = $accessList | Where-Object { $_.Scope -ne $this.GetResourceId() };
if(($inheritedAccessList | Measure-Object).Count -ne 0)
{
$controlResult.AddMessage("Note: " + $this.CreateRBACCountMessage($inheritedAccessList) + " have inherited RBAC access to resource. It's good practice to keep the RBAC access to minimum.");
}
else
{
$controlResult.AddMessage("No identities have inherited RBAC access to resource");
}
return $controlResult;
}
hidden [string] CreateRBACCountMessage([array] $resourceAccessList)
{
$nonNullObjectTypes = $resourceAccessList | Where-Object { -not [string]::IsNullOrEmpty($_.ObjectType) };
if(($nonNullObjectTypes | Measure-Object).Count -eq 0)
{
return "$($resourceAccessList.Count) identities";
}
else
{
$countBreakupString = [string]::Join(", ",
($nonNullObjectTypes |
Group-Object -Property ObjectType -NoElement |
ForEach-Object { "$($_.Name): $($_.Count)" }
));
return "$($resourceAccessList.Count) identities ($countBreakupString)";
}
}
hidden [bool] CheckMetricAlertConfiguration([PSObject[]] $metricSettings, [ControlResult] $controlResult, [string] $extendedResourceName)
{
$result = $false;
if($metricSettings -and $metricSettings.Count -ne 0)
{
$resId = $this.GetResourceId() + $extendedResourceName;
$resIdMessageString = "";
if(-not [string]::IsNullOrWhiteSpace($extendedResourceName))
{
$resIdMessageString = "for nested resource [$extendedResourceName]";
}
$resourceAlerts = (Get-AzureRmAlertRule -ResourceGroup $this.ResourceContext.ResourceGroupName -DetailedOutput) |
Where-Object { $_.Properties -and $_.Properties.Condition -and $_.Properties.Condition.DataSource } |
Where-Object { $_.Properties.Condition.DataSource.ResourceUri -eq $resId };
$nonConfiguredMetrices = @();
$misConfiguredMetrices = @();
$metricSettings |
ForEach-Object {
$currentMetric = $_;
$matchedMetrices = @();
$matchedMetrices += $resourceAlerts |
Where-Object { $_.Properties.Condition.DataSource.MetricName -eq $currentMetric.Condition.DataSource.MetricName }
if($matchedMetrices.Count -eq 0)
{
$nonConfiguredMetrices += $currentMetric;
}
else
{
$misConfigured = @();
$misConfigured += $matchedMetrices | Where-Object { -not [Helpers]::CompareObject($currentMetric, $_.Properties) };
if($misConfigured.Count -eq $matchedMetrices.Count)
{
$misConfiguredMetrices += $misConfigured;
}
}
}
$controlResult.AddMessage("Following metric alerts must be configured $resIdMessageString with settings mentioned below:", $metricSettings);
$controlResult.VerificationResult = [VerificationResult]::Failed;
if($nonConfiguredMetrices.Count -ne 0)
{
$controlResult.AddMessage("Following metric alerts are not configured $($resIdMessageString):", $nonConfiguredMetrices);
}
if($misConfiguredMetrices.Count -ne 0)
{
$controlResult.AddMessage("Following metric alerts are not correctly configured $resIdMessageString. Please update the metric settings in order to comply.", $misConfiguredMetrices);
}
if($nonConfiguredMetrices.Count -eq 0 -and $misConfiguredMetrices.Count -eq 0)
{
$result = $true;
$controlResult.AddMessage([VerificationResult]::Passed , "All mandatory metric alerts are correctly configured $resIdMessageString.");
}
}
else
{
throw [System.ArgumentException] ("The argument 'metricSettings' is null or empty");
}
return $result;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/FileOutputBase.ps1
|
FileOutputBase.ps1
|
Set-StrictMode -Version Latest
class FileOutputBase: ListenerBase
{
static [string] $ETCFolderPath = "Etc";
[string] $FilePath = "";
[string] $FolderPath = "";
[string] $BasePath = "";
FileOutputBase()
{
[Helpers]::AbstractClass($this, [FileOutputBase]);
}
[string] CalculateFolderPath([SubscriptionContext] $context, [string] $subFolderPath)
{
$outputPath = "";
if($context -and (-not [string]::IsNullOrWhiteSpace($context.SubscriptionName)) -and (-not [string]::IsNullOrWhiteSpace($context.SubscriptionId)))
{
$isDefaultPath = $false;
if([System.String]::IsNullOrEmpty($this.BasePath))
{
$isDefaultPath = $true;
$this.BasePath = [Constants]::AzSdkLogFolderPath;
}
if (-not $this.BasePath.EndsWith("\")) {
$this.BasePath += "\";
}
$outputPath = $this.BasePath + "AzSDKLogs\"
$sanitizedPath = [Helpers]::SanitizeFolderName($context.SubscriptionName);
if ([string]::IsNullOrEmpty($sanitizedPath)) {
$sanitizedPath = $context.SubscriptionId;
}
if ([string]::IsNullOrEmpty($sanitizedPath)) {
$outputPath += ("Default\{0}\" -f $this.RunIdentifier);
}
else {
$outputPath += ("Sub_{0}\{1}\" -f $sanitizedPath, $this.RunIdentifier);
}
if (-not [string]::IsNullOrEmpty($subFolderPath)) {
$sanitizedPath = [Helpers]::SanitizeFolderName($subFolderPath);
if (-not [string]::IsNullOrEmpty($sanitizedPath)) {
$outputPath += ("{0}\" -f $sanitizedPath);
}
}
if(-not (Test-Path $outputPath))
{
try
{
mkdir -Path $outputPath -ErrorAction Stop | Out-Null
}
catch
{
$outputPath = "";
if(-not $isDefaultPath)
{
$this.BasePath = "";
$outputPath = $this.CalculateFolderPath($context, $subFolderPath);
}
}
}
}
return $outputPath;
}
[string] CalculateFolderPath([SubscriptionContext] $context)
{
return $this.CalculateFolderPath($context, "");
}
[void] SetFolderPath([SubscriptionContext] $context)
{
$this.SetFolderPath($context, "");
}
[void] SetFolderPath([SubscriptionContext] $context, [string] $subFolderPath)
{
$this.FolderPath = $this.CalculateFolderPath($context, $subFolderPath);
}
[string] CalculateFilePath([SubscriptionContext] $context, [string] $fileName)
{
return $this.CalculateFilePath($context, "", $fileName);
}
[string] CalculateFilePath([SubscriptionContext] $context, [string] $subFolderPath, [string] $fileName)
{
$outputPath = "";
$this.SetFolderPath($context, $subFolderPath);
if ([string]::IsNullOrEmpty($this.FolderPath)) {
return $outputPath;
}
$outputPath = $this.FolderPath;
if (-not $outputPath.EndsWith("\")) {
$outputPath += "\";
}
if ([string]::IsNullOrEmpty($fileName)) {
$outputPath += $(Get-Date -format "yyyyMMdd_HHmmss") + ".log";
}
else {
$outputPath += $fileName;
}
return $outputPath;
}
[void] SetFilePath([SubscriptionContext] $context, [string] $fileName)
{
$this.SetFilePath($context, "", $fileName);
}
[void] SetFilePath([SubscriptionContext] $context, [string] $subFolderPath, [string] $fileName)
{
$this.FilePath = $this.CalculateFilePath($context, $subFolderPath, $fileName);
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/ListenerBase.ps1
|
ListenerBase.ps1
|
Set-StrictMode -Version Latest
class ListenerBase: EventBase
{
[array] $RegisteredEvents = @();
ListenerBase()
{
[Helpers]::AbstractClass($this, [ListenerBase]);
}
[void] SetRunIdentifier([AzSdkRootEventArgument] $arguments)
{
$data = $arguments.Messages | Select-Object -First 1
if ($data) {
$this.RunIdentifier = $data.Message;
# Sending Invocation context in DataObject while firing RunIdentifier event
if($data.DataObject)
{
$this.InvocationContext = $data.DataObject;
}
}
}
[void] UnregisterEvents()
{
$this.RegisteredEvents | Sort-Object -Descending |
ForEach-Object {
Unregister-Event -SubscriptionId $_ -Force -ErrorAction SilentlyContinue
Remove-Job -Id $_ -Force -ErrorAction SilentlyContinue
}
$this.RegisteredEvents = @();
}
[void] RegisterEvent([string] $sourceIdentifier, [ScriptBlock] $action)
{
$this.RegisteredEvents += (Register-EngineEvent -SourceIdentifier $sourceIdentifier -Action $action).Id;
}
[void] HandleException([ScriptBlock] $script, [System.Management.Automation.PSEventArgs] $event)
{
try
{
& $script $event $this
}
catch
{
$this.PublishException($_);
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Abstracts/AzSdkRoot.ps1
|
AzSdkRoot.ps1
|
Set-StrictMode -Version Latest
class AzSdkRoot: EventBase
{
[SubscriptionContext] $SubscriptionContext;
AzSdkRoot([string] $subscriptionId)
{
[Helpers]::AbstractClass($this, [AzSdkRoot]);
#Set up subscription
$this.SubscriptionContext = [SubscriptionContext]@{
SubscriptionId = $subscriptionId;
Scope = "/subscriptions/$subscriptionId";
};
$this.SetAzureContext();
}
hidden [void] SetAzureContext()
{
$isContextNull = $false;
$currentContext = $null;
try
{
$currentContext = Get-AzureRmContext -ErrorAction Stop
}
catch
{
$isContextNull = $true
}
if(($null -eq $currentContext) -or $isContextNull)
{
$this.PublishCustomMessage("No active Azure login session found. Initiating login flow...", [MessageType]::Warning);
$currentContext = Add-AzureRmAccount
try
{
$currentContext = Get-AzureRmContext -ErrorAction Stop
}
catch
{
throw [System.ArgumentException] ("Subscription Id [" + $this.SubscriptionContext.SubscriptionId + "] is invalid or you may not have permissions.")
}
}
if($currentContext.Subscription -and $currentContext.Subscription.SubscriptionId)
{
if($currentContext.Subscription.SubscriptionId -ne $this.SubscriptionContext.SubscriptionId)
{
$currentContext = Set-AzureRmContext -SubscriptionId $this.SubscriptionContext.SubscriptionId -ErrorAction Stop
# $currentContext will contain the desired subscription (or $null if id is wrong or no permission)
if ($null -eq $currentContext)
{
throw [System.ArgumentException] ("Invalid Subscription Id: [" + $this.SubscriptionContext.SubscriptionId + "]")
}
}
}
else
{
throw [System.ArgumentException] ("Subscription Id [" + $this.SubscriptionContext.SubscriptionId + "] is invalid or you may not have permissions.")
}
if ($null -ne $currentContext)
{
$this.SubscriptionContext.SubscriptionName = $currentContext.Subscription.SubscriptionName;
}
}
[PSObject] LoadServerConfigFile([string] $fileName)
{
return [ConfigurationManager]::LoadServerConfigFile($fileName);
}
hidden [AzSdkRootEventArgument] CreateRootEventArgumentObject()
{
return [AzSdkRootEventArgument]@{
SubscriptionContext = $this.SubscriptionContext;
};
}
hidden [void] PublishAzSdkRootEvent([string] $eventType, [MessageData[]] $messages)
{
[AzSdkRootEventArgument] $arguments = $this.CreateRootEventArgumentObject();
if($messages)
{
$arguments.Messages += $messages;
}
$this.PublishEvent($eventType, $arguments);
}
hidden [void] PublishAzSdkRootEvent([string] $eventType, [string] $message, [MessageType] $messageType)
{
if (-not [string]::IsNullOrEmpty($message))
{
[MessageData] $data = [MessageData]@{
Message = $message;
MessageType = $messageType;
};
$this.PublishAzSdkRootEvent($eventType, $data);
}
else
{
[MessageData[]] $blankMessages = @();
$this.PublishAzSdkRootEvent($eventType, $blankMessages);
}
}
hidden [void] PublishAzSdkRootEvent([string] $eventType, [PSObject] $dataObject)
{
if ($dataObject)
{
[MessageData] $data = [MessageData]@{
DataObject = $dataObject;
};
$this.PublishAzSdkRootEvent($eventType, $data);
}
else
{
[MessageData[]] $blankMessages = @();
$this.PublishAzSdkRootEvent($eventType, $blankMessages);
}
}
[void] PublishCustomMessage([MessageData[]] $messages)
{
if($messages)
{
$this.PublishAzSdkRootEvent([AzSdkRootEvent]::CustomMessage, $messages);
}
}
[void] CommandProcessing([MessageData[]] $messages)
{
if($messages)
{
$this.PublishAzSdkRootEvent([AzSdkRootEvent]::CommandProcessing, $messages);
}
}
[void] PublishRunIdentifier([System.Management.Automation.InvocationInfo] $invocationContext)
{
if($invocationContext)
{
$this.InvocationContext = $invocationContext;
}
$this.RunIdentifier = $this.GenerateRunIdentifier();
$this.PublishAzSdkRootEvent([AzSdkRootEvent]::GenerateRunIdentifier, [MessageData]::new($this.RunIdentifier, $invocationContext));
}
hidden [string[]] ConvertToStringArray([string] $stringArray)
{
$result = @();
if(-not [string]::IsNullOrWhiteSpace($stringArray))
{
$result += $stringArray.Split(',', [StringSplitOptions]::RemoveEmptyEntries) |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
ForEach-Object { $_.Trim() } |
Select-Object -Unique;
}
return $result;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/IdentityHelpers.ps1
|
IdentityHelpers.ps1
|
Set-StrictMode -Version Latest
class IdentityHelpers
{
hidden static [bool] IsServiceAccount($ObjectId, $SignInName, $ObjectType, $GraphAccessToken)
{
$return = $null
$header = "Bearer " + $GraphAccessToken
$RMContext = Get-AzureRmContext -ErrorAction Ignore
$headers = @{"Authorization"=$header;"Content-Type"="application/json"}
$uri=""
$output = $null
if($ObjectType -eq "User")
{
if($null -ne $ObjectId -and [System.Guid]::Empty -ne $ObjectId)
{
$uri = [string]::Format("https://graph.windows.net/{0}/users/{1}?api-version=1.6",$RMContext.Tenant.TenantId, $ObjectId)
}
elseif ($null -ne $SignInName) {
$uri = [string]::Format("https://graph.windows.net/{0}/users/{1}?api-version=1.6",$RMContext.Tenant.TenantId, $SignInName)
}
else {
return $false
}
}
elseif($ObjectType -eq "ServicePrincipal"){
return $false
}
else
{
#in the case of coadmins
return $false
}
$err = $null
$result = ""
try {
$result = Invoke-WebRequest -Method GET -Uri $uri -Headers $headers -UseBasicParsing
if($result.StatusCode -ge 200 -and $result.StatusCode -le 399){
if($null -ne $result.Content){
$json = (ConvertFrom-Json $result.Content)
if($null -ne $json){
$output = $json
if($null -ne ($json | Get-Member value) )
{
$output = $json.value
}
}
}
$isGuid = [IdentityHelpers]::IsADObjectGUID($output.immutableId)
return $isGuid
}
}
catch{
$err = $_
if($null -ne $err)
{
if($null -ne $err.ErrorDetails.Message){
$json = (ConvertFrom-Json $err.ErrorDetails.Message)
if($null -ne $json){
$return = $json
if($json.'odata.error'.code -eq "Request_ResourceNotFound")
{
return $false;
}
}
}
}
}
return $null
}
hidden static [bool] IsADObjectGUID($immutableId){
try {
$decodedII = [system.convert]::frombase64string($immutableId)
$guid = [GUID]$decodedII
}
catch {
return $false
}
return $true
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/RoleAssignmentHelper.ps1
|
RoleAssignmentHelper.ps1
|
using namespace Microsoft.Azure.Commands.Resources.Models.Authorization
Set-StrictMode -Version Latest
class RoleAssignmentHelper
{
static [PSRoleAssignment[]] GetAzSDKRoleAssignmentByScope([string] $scope, [bool] $recurse, [bool] $includeClassicAdministrators)
{
[PSRoleAssignment[]] $roleAssignments = @();
try
{
if($includeClassicAdministrators)
{
$roleAssignments = Get-AzureRmRoleAssignment -Scope $scope -IncludeClassicAdministrators -ErrorAction Stop;
}
else
{
$roleAssignments = Get-AzureRmRoleAssignment -Scope $scope -ErrorAction Stop;
}
return $roleAssignments;
}
catch
{ }
$requestUri = [WebRequestHelper]::AzureManagementUri + $scope;
$roleAssignments = [RoleAssignmentHelper]::GetRMRoleAssignment($requestUri, $recurse);
if($includeClassicAdministrators)
{
$roleAssignments += [RoleAssignmentHelper]::GetAzSDKClassicAdministrators();
}
return $roleAssignments;
}
static [PSRoleAssignment[]] GetAzSDKRoleAssignment([bool] $recurse, [bool] $includeClassicAdministrators)
{
[PSRoleAssignment[]] $roleAssignments = @();
try
{
if($includeClassicAdministrators)
{
$roleAssignments = Get-AzureRmRoleAssignment -IncludeClassicAdministrators -ErrorAction Stop;
}
else
{
$roleAssignments = Get-AzureRmRoleAssignment -ErrorAction Stop;
}
return $roleAssignments;
}
catch
{ }
$roleAssignments = [RoleAssignmentHelper]::GetAzSDKRoleAssignment("", "", "", $recurse, $includeClassicAdministrators);
return $roleAssignments;
}
static [PSRoleAssignment[]] GetAzSDKRoleAssignment([string] $resourceGroupName, [bool] $recurse, [bool] $includeClassicAdministrators)
{
[PSRoleAssignment[]] $roleAssignments = @();
try
{
if($includeClassicAdministrators)
{
$roleAssignments = Get-AzureRmRoleAssignment -ResourceGroupName $resourceGroupName -IncludeClassicAdministrators -ErrorAction Stop;
}
else
{
$roleAssignments = Get-AzureRmRoleAssignment -ResourceGroupName $resourceGroupName -ErrorAction Stop;
}
return $roleAssignments;
}
catch
{ }
$roleAssignments = [RoleAssignmentHelper]::GetAzSDKRoleAssignment($resourceGroupName, "", "", $recurse, $includeClassicAdministrators);
return $roleAssignments;
}
static [PSRoleAssignment[]] GetAzSDKRoleAssignment([string] $resourceGroupName, [string] $resourceName, [string] $resourceType, [bool] $recurse, [bool] $includeClassicAdministrators)
{
[PSRoleAssignment[]] $roleAssignments = @();
try
{
if($includeClassicAdministrators)
{
$roleAssignments = Get-AzureRmRoleAssignment -ResourceGroupName $resourceGroupName -ResourceName $resourceName -ResourceType $resourceType -IncludeClassicAdministrators -ErrorAction Stop;
}
else
{
$roleAssignments = Get-AzureRmRoleAssignment -ResourceGroupName $resourceGroupName -ResourceName $resourceName -ResourceType $resourceType -ErrorAction Stop;
}
return $roleAssignments;
}
catch
{ }
$currentContext = Get-AzureRmContext -ErrorAction Stop;
$subscriptionId = $currentContext.Subscription.SubscriptionId;
$subscriptionPath = "subscriptions/$subscriptionId";
$resourceGroupPath = "/resourceGroups/$resourceGroupName";
$resourceNamePath = "/providers/$resourceType/$resourceName";
$requestUri = [WebRequestHelper]::AzureManagementUri + $subscriptionPath;
if(-not [string]::IsNullOrEmpty($resourceGroupName))
{
$requestUri += $resourceGroupPath;
if((-not [string]::IsNullOrEmpty($resourceType)) -and (-not [string]::IsNullOrEmpty($resourceName)))
{
$requestUri += $resourceNamePath;
}
}
$roleAssignments = [RoleAssignmentHelper]::GetRMRoleAssignment($requestUri, $recurse);
if($includeClassicAdministrators)
{
$roleAssignments += [RoleAssignmentHelper]::GetAzSDKClassicAdministrators();
}
return $roleAssignments;
}
hidden static [PSRoleAssignment[]] GetRMRoleAssignment([string] $roleAssignmentUri, [bool] $recurse)
{
$recurseParam = "&`$filter=atScope()";
$roleAssignmentPath = "/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01";
$roleAssignmentUri += $roleAssignmentPath;
if(-not $recurse)
{
$roleAssignmentUri += $recurseParam;
}
$webResponse = [WebRequestHelper]::InvokeGetWebRequest($roleAssignmentUri);
[PSRoleAssignment[]] $roleAssignments = @();
$webResponse |
ForEach-Object {
$roleDefinitionId = $_.properties.roleDefinitionId.Substring($_.properties.roleDefinitionId.LastIndexOf("/") + 1);
$roleDefinitionName = "";
$roleDefinition = (Get-AzureRmRoleDefinition -Id $roleDefinitionId -ErrorAction SilentlyContinue) | Select-Object -First 1
if($roleDefinition)
{
$roleDefinitionName = $roleDefinition.Name;
};
$roleAssignments += [PSRoleAssignment]@{
RoleAssignmentId = $_.id;
Scope = $_.properties.scope;
RoleDefinitionName = $roleDefinitionName;
RoleDefinitionId = $roleDefinitionId;
ObjectId = $_.properties.principalId;
};
}
if($roleAssignments.Count -gt 0)
{
$objectIds = $roleAssignments | Select-Object -Property ObjectId -Unique | ForEach-Object { "$($_.ObjectId)" };
$objectIdResponse = [RoleAssignmentHelper]::GetADObjectsByObjectIds($objectIds);
$roleAssignments | ForEach-Object {
$currentItem = $_;
if($objectIdResponse.Count -ne 0)
{
$filteredResponse = $objectIdResponse | Where-Object { $_.ObjectId -eq $currentItem.ObjectId } | Select-Object -First 1
if($filteredResponse)
{
$currentItem.ObjectType = $filteredResponse.objectType;
$currentItem.DisplayName = $filteredResponse.displayName;
if(($filteredResponse | Get-Member -Name "userPrincipalName"))
{
$currentItem.SignInName = $filteredResponse.userPrincipalName;
}
}
}
else
{
if(-not [string]::IsNullOrWhiteSpace($currentItem.ObjectId))
{
$currentItem.ObjectType = "NOGRAPHACCESS"
$currentItem.DisplayName = "NOGRAPHACCESS"
$currentItem.SignInName = "NOGRAPHACCESS"
}
else
{
$currentItem.ObjectId = "00000000-0000-0000-0000-000000000000"
}
}
}
}
return $roleAssignments;
}
hidden static [PSRoleAssignment[]] GetAzSDKClassicAdministrators()
{
$currentContext = Get-AzureRmContext -ErrorAction Stop;
$subscriptionId = $currentContext.Subscription.SubscriptionId;
$subscriptionPath = "subscriptions/$subscriptionId";
$requestUri = [WebRequestHelper]::AzureManagementUri + $subscriptionPath;
$requestUri += "/providers/Microsoft.Authorization/classicAdministrators?api-version=2015-06-01";
$webResponse = [WebRequestHelper]::InvokeGetWebRequest($requestUri);
[PSRoleAssignment[]] $roleAssignments = @();
$webResponse |
ForEach-Object {
$roleAssignments += [PSRoleAssignment]@{
SignInName = $_.properties.emailAddress;
DisplayName = $_.properties.emailAddress;
Scope = "/subscriptions/$subscriptionId";
RoleDefinitionName = $_.properties.role;
RoleDefinitionId = $_.id;
ObjectId = "00000000-0000-0000-0000-000000000000";
ObjectType = $_.properties.role
};
}
return $roleAssignments;
}
hidden static [System.Object[]] GetADObjectsByObjectIds([string[]] $objectIds)
{
$rmContext = Get-AzureRmContext -ErrorAction Stop;
$tenantId = $rmContext.Tenant.TenantId
$uri = [WebRequestHelper]::GraphApiUri + "$tenantId/getObjectsByObjectIds?api-version=1.6"
$body = "{`"objectIds`":" + ($objectIds | ConvertTo-Json ) + "}";
$webResponse = @();
try
{
$webResponse = [WebRequestHelper]::InvokePostWebRequest($uri, $body);
}
catch
{
#Access denied exception occurs here.
#[EventBase]::PublishGenericException($_);
}
return $webResponse;
}
hidden static [bool] HasGraphAccess()
{
$hasAccess = $false;
$rmContext = Get-AzureRmContext -ErrorAction Stop;
$tenantId = $rmContext.Tenant.TenantId
$uri = [WebRequestHelper]::GraphApiUri + "$tenantId/users?`$top=1&api-version=1.6"
$webResponse = @();
try
{
$webResponse = [WebRequestHelper]::InvokeGetWebRequest($uri);
$hasAccess = $true;
}
catch
{
$hasAccess = $false;
}
return $hasAccess;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/RemoteApiHelper.ps1
|
RemoteApiHelper.ps1
|
Set-StrictMode -Version Latest
class RemoteApiHelper {
# TODO: Move to config
hidden static [string] $ApiBaseEndpoint = [ConfigurationManager]::GetAzSdkConfigData().AzSDKApiBaseURL; #https://localhost:44380/api
hidden static [Newtonsoft.Json.JsonSerializerSettings] $SerializerSettings;
static RemoteApiHelper() {
[RemoteApiHelper]::SerializerSettings = [Newtonsoft.Json.JsonSerializerSettings]::new()
[RemoteApiHelper]::SerializerSettings.Converters.Add([Newtonsoft.Json.Converters.StringEnumConverter]::new())
[RemoteApiHelper]::SerializerSettings.Formatting = [Newtonsoft.Json.Formatting]::None
[RemoteApiHelper]::SerializerSettings.NullValueHandling = [Newtonsoft.Json.NullValueHandling]::Ignore
[RemoteApiHelper]::SerializerSettings.ReferenceLoopHandling = [Newtonsoft.Json.ReferenceLoopHandling]::Ignore
}
hidden static [string] GetAccessToken() {
#TODO: Move resource to config
return [Helpers]::GetAccessToken("https://management.core.windows.net/");
}
hidden static [psobject] PostContent($uri, $content, $type) {
try{
$accessToken = [RemoteApiHelper]::GetAccessToken()
$result = Invoke-WebRequest -Uri $([RemoteApiHelper]::ApiBaseEndpoint + $uri) `
-Method Post `
-Body $content `
-ContentType $type `
-Headers @{"Authorization" = "Bearer $accessToken"} `
-UseBasicParsing
return $result
}
catch{
return "ERROR"
}
}
hidden static [psobject] PostJsonContent($uri, $obj) {
$postContent = [Newtonsoft.Json.JsonConvert]::SerializeObject($obj, [RemoteApiHelper]::SerializerSettings)
return [RemoteApiHelper]::PostContent($uri, $postContent, "application/json")
}
static [void] PostSubscriptionScanResult($scanResult) {
[RemoteApiHelper]::PostJsonContent("/scanresults/subscription", $scanResult) | Out-Null
}
static [void] PostServiceScanResult($scanResult) {
[RemoteApiHelper]::PostJsonContent("/scanresults/service", $scanResult) | Out-Null
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/SVTMapping.ps1
|
SVTMapping.ps1
|
Set-StrictMode -Version Latest
class SVTMapping
{
static [string] GetResourceTypeEnumItems()
{
return ([SVTMapping]::Mapping |
Where-Object { -not [string]::IsNullOrEmpty($_.ResourceTypeName) } |
ForEach-Object { "$($_.ResourceTypeName.Replace(' ', '')) `r`n" } |
Sort-Object);
}
static [ResourceTypeMapping[]] $Mapping = (
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Logic/Workflows";
JsonFileName = "LogicApps.json";
ClassName = "LogicApps";
ResourceTypeName = "LogicApps";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Compute/virtualMachines";
JsonFileName = "VirtualMachine.json";
ClassName = "VirtualMachine";
ResourceTypeName = "VirtualMachine";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.DataLakeStore/accounts";
JsonFileName = "DataLakeStore.json";
ClassName = "DataLakeStore";
ResourceTypeName = "DataLakeStore";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.DataLakeAnalytics/accounts";
JsonFileName = "DataLakeAnalytics.json";
ClassName = "DataLakeAnalytics";
ResourceTypeName = "DataLakeAnalytics";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.KeyVault/vaults";
JsonFileName = "KeyVault.json";
ClassName = "KeyVault";
ResourceTypeName = "KeyVault";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Sql/servers";
JsonFileName = "SQLDatabase.json";
ClassName = "SQLDatabase";
ResourceTypeName = "SQLDatabase";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Web/sites";
JsonFileName = "AppService.json";
ClassName = "AppService";
ResourceTypeName = "AppService";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.DataFactory/dataFactories";
JsonFileName = "DataFactory.json";
ClassName = "DataFactory";
ResourceTypeName = "DataFactory";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Storage/storageAccounts";
JsonFileName = "Storage.json";
ClassName = "Storage";
ResourceTypeName = "StorageAccount";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.NotificationHubs/namespaces/notificationHubs";
JsonFileName = "NotificationHub.json";
ClassName = "NotificationHub";
ResourceTypeName = "NotificationHub";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Cdn/profiles";
JsonFileName = "CDN.json";
ClassName = "CDN";
ResourceTypeName = "CDN";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Network/virtualNetworks";
JsonFileName = "VirtualNetwork.json";
ClassName = "VirtualNetwork";
ResourceTypeName = "VirtualNetwork";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Network/virtualNetworks";
JsonFileName = "ERvNet.json";
ClassName = "ERvNet";
ResourceTypeName = "ERvNet";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.AnalysisServices/servers";
JsonFileName = "AnalysisServices.json";
ClassName = "AnalysisServices";
ResourceTypeName = "AnalysisService";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Search/searchServices";
JsonFileName = "Search.json";
ClassName = "Search";
ResourceTypeName = "Search";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Batch/batchAccounts";
JsonFileName = "Batch.json";
ClassName = "Batch";
ResourceTypeName = "Batch";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.ClassicCompute/domainNames";
JsonFileName = "CloudService.json";
ClassName = "CloudService";
ResourceTypeName = "CloudService";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.ServiceBus/namespaces";
JsonFileName = "ServiceBus.json";
ClassName = "ServiceBus";
ResourceTypeName = "ServiceBus";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Eventhub/namespaces";
JsonFileName = "EventHub.json";
ClassName = "EventHub";
ResourceTypeName = "EventHub";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Cache/Redis";
JsonFileName = "RedisCache.json";
ClassName = "RedisCache";
ResourceTypeName = "RedisCache";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.ServiceFabric/clusters";
JsonFileName = "ServiceFabric.json";
ClassName = "ServiceFabric";
ResourceTypeName = "ServiceFabric";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Web/connectionGateways";
JsonFileName = "ODG.json";
ClassName = "ODG";
ResourceTypeName = "ODG";
},
[ResourceTypeMapping]@{
ResourceType = "Microsoft.Network/trafficmanagerprofiles";
JsonFileName = "TrafficManager.json";
ClassName = "TrafficManager";
ResourceTypeName = "TrafficManager";
}
);
static [SubscriptionMapping] $SubscriptionMapping =@{
ClassName = "SubscriptionCore";
JsonFileName = "SubscriptionCore.json";
};
}
Invoke-Expression "enum ResourceTypeName { `r`n All `r`n $([SVTMapping]::GetResourceTypeEnumItems()) }";
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/ConfigurationHelper.ps1
|
ConfigurationHelper.ps1
|
Set-StrictMode -Version Latest
#
# ConfigurationHelper.ps1
#
class ConfigurationHelper {
hidden static [PSObject] LoadOfflineConfigFile([string] $fileName) {
#Load file from AzSDK App folder
$rootConfigPath = [Constants]::AzSdkAppFolderPath + "\" ;
$extension = [System.IO.Path]::GetExtension($fileName);
$filePath = $null
if(Test-Path -Path $rootConfigPath)
{
$filePath = (Get-ChildItem $rootConfigPath -Name -Recurse -Include $fileName) | Select-Object -First 1
}
#If file not present in App folder load settings from Configurations in Module folder
if (!$filePath) {
$rootConfigPath = (Get-Item $PSScriptRoot).Parent.FullName + "\Configurations\";
$filePath = (Get-ChildItem $rootConfigPath -Name -Recurse -Include $fileName) | Select-Object -First 1
}
if ($filePath) {
if($extension -eq ".json")
{
$fileContent = (Get-Content -Raw -Path ($rootConfigPath + $filePath)) | ConvertFrom-Json
}
else
{
$fileContent = (Get-Content -Raw -Path ($rootConfigPath + $filePath))
}
}
else {
throw "Unable to find the specified file '$fileName'"
}
if (-not $fileContent) {
throw "The specified file '$fileName' is empty"
}
return $fileContent;
}
hidden static [PSObject] LoadServerConfigFile([string] $policyFileName, [bool] $useOnlinePolicyStore, [string] $onlineStoreUri, [bool] $enableAADAuthForOnlinePolicyStore) {
[PSObject] $fileContent = "";
if ([string]::IsNullOrWhiteSpace($policyFileName)) {
throw [System.ArgumentException] ("The argument 'policyFileName' is null");
}
if ($useOnlinePolicyStore) {
if ([string]::IsNullOrWhiteSpace($onlineStoreUri))
{
throw [System.ArgumentException] ("The argument 'onlineStoreUri' is null");
}
#Evaluate all code block in onlineStoreUri.
#Can use '$FileName' in uri to fill dynamic file name.
$FileName = $policyFileName
#Revisit
$Version = [System.Version] ($global:ExecutionContext.SessionState.Module.Version);
$uri = $global:ExecutionContext.InvokeCommand.ExpandString($onlineStoreUri)
[System.Uri] $validatedUri = $null;
if([System.Uri]::TryCreate($uri, [System.UriKind]::Absolute, [ref] $validatedUri))
{
try
{
if($enableAADAuthForOnlinePolicyStore)
{
$accessToken = [Helpers]::GetAccessToken("https://management.core.windows.net/")
$fileContent = Invoke-RestMethod `
-Method GET `
-Uri $validatedUri `
-Headers @{"Authorization" = "Bearer $accessToken"} `
-UseBasicParsing
}
else
{
$fileContent = Invoke-RestMethod `
-Method GET `
-Uri $validatedUri `
-UseBasicParsing
}
}
catch
{
[EventBase]::PublishGenericCustomMessage(("Error while fetching the policy [$fileName] from online store. " + [Constants]::OfflineModeWarning), [MessageType]::Warning);
[EventBase]::PublishGenericException($_);
}
}
else
{
[EventBase]::PublishGenericCustomMessage(("'UseOnlinePolicyStore' is enabled but the 'OnlinePolicyStoreUrl' is not valid Uri: [$uri]. `r`n" + [Constants]::OfflineModeWarning), [MessageType]::Warning);
}
if (-not $fileContent) {
#Fire special event to notify user about switching to offline policy
$fileContent = [ConfigurationHelper]::LoadOfflineConfigFile($policyFileName)
}
# return $updateResult
}
else {
[EventBase]::PublishGenericCustomMessage(([Constants]::OfflineModeWarning + " Policy: $policyFileName"), [MessageType]::Warning);
$fileContent = [ConfigurationHelper]::LoadOfflineConfigFile($policyFileName)
}
if (-not $fileContent) {
throw "The specified file '$policyFileName' is empty"
}
return $fileContent;
}
#Need to rethink on this function logic
hidden static [PSObject] LoadModuleJsonFile([string] $fileName) {
$rootConfigPath = (Get-Item $PSScriptRoot).Parent.FullName + "\Configurations\";
$filePath = (Get-ChildItem $rootConfigPath -Name -Recurse -Include $fileName) | Select-Object -First 1
if ($filePath) {
$fileContent = (Get-Content -Raw -Path ($rootConfigPath + $filePath)) | ConvertFrom-Json
}
else {
throw "Unable to find the specified file '$fileName'"
}
return $fileContent;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/Helpers.ps1
|
Helpers.ps1
|
using namespace Newtonsoft.Json
Set-StrictMode -Version Latest
class Helpers {
static AbstractClass($obj, $classType) {
$type = $obj.GetType()
if ($type -eq $classType) {
throw("Class '$type' must be inherited")
}
}
static [string] SanitizeFolderName($folderPath) {
return ($folderPath -replace '[<>:"/\\|?*]', '');
}
static [string] ConvertObjectToString([PSObject] $dataObject, [bool] $defaultPsOutput) {
[string] $msg = "";
if ($dataObject) {
if ($dataObject.GetType().FullName -eq "System.Management.Automation.ErrorRecord") {
if ($defaultPsOutput) {
$msg = $dataObject.ToString();
}
else {
$msg = ($dataObject | Out-String) + "`r`nStackTrace: " + $dataObject. ScriptStackTrace
}
}
else {
if ($defaultPsOutput -or $dataObject.GetType() -eq [string]) {
$msg = $dataObject | Out-String;
}
else {
try {
#$msg = $dataObject | ConvertTo-Json -Depth 5 | Out-String;
#$msg = [Helpers]::ConvertToJsonCustom($dataObject);
$msg = [Helpers]::ConvertToPson($dataObject);
}
catch {
$e = $_
$msg = $dataObject | Format-List | Out-String;
}
$msg = $msg.Trim();
}
}
}
return $msg;
}
static [JsonSerializerSettings] $SerializerSettings = $null;
hidden static [JsonSerializerSettings] GetSerializerSettings() {
if (-not [Helpers]::SerializerSettings) {
$settings = [JsonSerializerSettings]::new();
$settings.Converters.Add([Converters.StringEnumConverter]::new());
$settings.Formatting = [Formatting]::Indented;
$settings.NullValueHandling = [NullValueHandling]::Ignore;
$settings.ReferenceLoopHandling = [ReferenceLoopHandling]::Ignore;
[Helpers]::SerializerSettings = $settings;
}
return [Helpers]::SerializerSettings;
}
static [string] ConvertToJson([PSObject] $dataObject) {
if ($dataObject) {
if ($dataObject.GetType() -eq [System.Object[]] -and $dataObject.Count -ne 0) {
$list = New-Object -TypeName "System.Collections.Generic.List[$($dataObject[0].GetType().fullname)]";
$dataObject | ForEach-Object {
if ($_) {
$list.Add($_);
}
}
return [JsonConvert]::SerializeObject($list, [Helpers]::GetSerializerSettings());
}
return [JsonConvert]::SerializeObject($dataObject, [Helpers]::GetSerializerSettings());
}
return "";
}
static [string] ConvertToJsonCustom([PSObject] $Object) {
Set-StrictMode -Off
$res = [Helpers]::ConvertToJsonCustomNotStrict($Object, 10, 10, $false)
Set-StrictMode -Version Latest
return $res
}
static [string] ConvertToPson([PSObject] $Object) {
Set-StrictMode -Off
$res = [Helpers]::ConvertToPsonNotStrict($Object, 10, 10, $false, $false, (Get-Variable -Name PSVersionTable).Value.PSVersion)
Set-StrictMode -Version Latest
return $res
}
static [string] ConvertToJsonCustomNotStrict([PSObject] $Object, [Int]$Depth, [Int]$Layers, [bool]$IsWind) {
$Format = $Null
$Quote = If ($Depth -le 0) {""}
Else {""""}
$Space = If ($Layers -le 0) {""}
Else {" "}
If ($Object -eq $Null) { return "null"}
Else {
$JSON = If ($Object -is "Array") {
$Format = "[", ",$Space", "]"
If ($Depth -gt 1) {
For ($i = 0; $i -lt $Object.Count; $i++) {
[Helpers]::ConvertToJsonCustomNotStrict($Object[$i], $Depth - 1, $Layers - 1, $IsWind)
}
}
}
ElseIf ($Object -is "Xml") {
$String = New-Object System.IO.StringWriter
$Object.Save($String)
$Xml = "'" + ([String]$String).Replace("`'", "'") + "'"
If ($Layers -le 0) {
($Xml -Replace "\r\n\s*", "") -Replace "\s+", " "
}
ElseIf ($Layers -eq 1) {
$Xml
}
Else {
$Xml.Replace("`r`n", "`r`n ")
}
$String.Dispose()
}
ElseIf ($Object -is "Enum") {
"$Quote$($Object.ToString())$Quote"
}
ElseIf ($Object -is "DateTime") {
"$Quote$($Object.ToString("o"))$Quote"
}
ElseIf ($Object -is "String") {
$Object = ConvertTo-Json $Object -Depth 1
"$Object"
}
ElseIf ($Object -is "Boolean") {
If ($Object) {"true"}
Else {"false"}
}
ElseIf ($Object -is "Char") {
"$Quote$Object$Quote"
}
ElseIf ($Object -is "guid") {
"$Quote$Object$Quote"
}
ElseIf ($Object -is "ValueType") {
$Object
}
ElseIf ($Object.Keys -ne $Null) {
$Format = "{", ",$Space", "}"
If ($Depth -gt 1) {
$Object.GetEnumerator() | ForEach-Object {
$Quote + $_.Name + $Quote + "$Space`:$Space" + ([Helpers]::ConvertToJsonCustomNotStrict($_.Value, $Depth - 1, $Layers - 1, $IsWind))
}
}
}
ElseIf ($Object -is "Object") {
If ($Object -is "System.Management.Automation.ErrorRecord" -and !$IsWind) {
$Depth = 3
$Layers = 3
$IsWind = $true
}
$Format = "{", ",$Space", "}"
If ($Depth -gt 1) {
Get-Member -InputObject $Object -MemberType Properties | ForEach-Object {
$Quote + $_.Name + $Quote + "$Space`:$Space" + ([Helpers]::ConvertToJsonCustomNotStrict($Object.$($_.Name), $Depth - 1, $Layers - 1, $IsWind))
}
}
}
Else {$Object}
If ($Format) {
$JSON = $Format[0] + (& {
If (($Layers -le 1) -or ($JSON.Count -le 0)) {
$JSON -Join $Format[1]
}
Else {
("`r`n" + ($JSON -Join "$($Format[1])`r`n")).Replace("`r`n", "`r`n ") + "`r`n"
}
}) + $Format[2]
}
return "$JSON"
}
}
# Adapted from https://stackoverflow.com/questions/15139552/save-hash-table-in-powershell-object-notation-pson
# Added case for enum
# PSON - PowerShell Object Notation
static [string] ConvertToPsonNotStrict($Object, [Int]$Depth, [Int]$Layers, [bool]$IsWind, [bool]$Strict, [Version]$Version) {
$Format = $Null
$Quote = If ($Depth -le 0) {""}
Else {""""}
$Space = If ($Layers -le 0) {""}
Else {" "}
If ($Object -eq $Null) {
return "`$Null"
}
Else {
$Type = "[" + $Object.GetType().Name + "]"
$PSON = If ($Object -is "Array") {
$Format = "@(", ",$Space", ")"
If ($Depth -gt 1) {
For ($i = 0; $i -lt $Object.Count; $i++) {
[Helpers]::ConvertToPsonNotStrict($Object[$i], $Depth - 1, $Layers - 1, $IsWind, $Strict, $Version)
}
}
}
ElseIf ($Object -is "Xml") {
$Type = "[Xml]"
$String = New-Object System.IO.StringWriter
$Object.Save($String)
$Xml = "'" + ([String]$String).Replace("`'", "'") + "'"
If ($Layers -le 0) {
($Xml -Replace "\r\n\s*", "") -Replace "\s+", " "
}
ElseIf ($Layers -eq 1) {
$Xml
}
Else {
$Xml.Replace("`r`n", "`r`n ")
}
$String.Dispose()
}
ElseIf ($Object -is "Enum") {
"$Quote$($Object.ToString())$Quote"
}
ElseIf ($Object -is "DateTime") {
"$Quote$($Object.ToString('s'))$Quote"
}
ElseIf ($Object -is "String") {
0..11 | ForEach-Object {
$Object = $Object.Replace([String]"```'""`0`a`b`f`n`r`t`v`$"[$_], ('`' + '`''"0abfnrtv$'[$_]))}; "$Quote$Object$Quote"
}
ElseIf ($Object -is "Boolean") {
If ($Object) {"`$True"}
Else {"`$False"}
}
ElseIf ($Object -is "Char") {
If ($Strict) {[Int]$Object}
Else {"$Quote$Object$Quote"}
}
ElseIf ($Object -is "guid") {
"$Quote$Object$Quote"
}
ElseIf ($Object -is "ValueType") {
$Object
}
ElseIf ($Object.Keys -ne $Null) {
If ($Type -eq "[OrderedDictionary]") {$Type = "[Ordered]"}
$Format = "@{", ";$Space", "}"
If ($Depth -gt 1) {
$Object.GetEnumerator() | ForEach-Object {
$Quote + $_.Name + $Quote + "$Space=$Space" + ([Helpers]::ConvertToPsonNotStrict($_.Value, $Depth - 1, $Layers - 1, $IsWind, $Strict, $Version))
}
}
}
ElseIf ($Object -is "Object") {
If ($Object -is "System.Management.Automation.ErrorRecord" -and !$IsWind) {
$Depth = 3
$Layers = 3
$IsWind = $true
}
If ($Version -le [Version]"2.0") {$Type = "New-Object PSObject -Property "}
$Format = "@{", ";$Space", "}"
If ($Depth -gt 1) {
Get-Member -InputObject $Object -MemberType Properties | ForEach-Object {
$Quote + $_.Name + $Quote + "$Space=$Space" + ([Helpers]::ConvertToPsonNotStrict($Object.$($_.Name), $Depth - 1, $Layers - 1, $IsWind, $Strict, $Version))
}
}
}
Else {$Object}
If ($Format) {
$PSON = $Format[0] + (& {
If (($Layers -le 1) -or ($PSON.Count -le 0)) {
$PSON -Join $Format[1]
}
Else {
("`r`n" + ($PSON -Join "$($Format[1])`r`n")).Replace("`r`n", "`r`n ") + "`r`n"
}
}) + $Format[2]
}
If ($Strict) {
return "$Type$PSON"
}
Else {
return "$PSON"
}
}
}
static [string] GetAccessToken([string] $resourceAppIdUri, [string] $tenantId) {
<#
$isContextNull = $false;
$rmContext = $null;
try
{
$rmContext = Get-AzureRmContext -ErrorAction Stop
}
catch
{
$isContextNull = $true
}
if(($null -eq $rmContext) -or $isContextNull)
{
[EventBase]::PublishGenericCustomMessage("No active Azure login session found. Initiating login flow...", [MessageType]::Warning);
$rmContext = Add-AzureRmAccount
}
#>
$rmContext = Get-AzureRmContext -ErrorAction Stop;
if ([string]::IsNullOrEmpty($tenantId)) {
$tenantId = $rmContext.Tenant.TenantId
}
$environment = [Microsoft.Azure.Commands.Common.Authentication.Models.AzureEnvironment] $rmContext.Environment
$resourceEnum = $environment.Endpoints.GetEnumerator() |
Where-Object { ([string] $_.Value).Trimend('/') -eq $resourceAppIdUri.Trimend('/') } |
Select-Object -First 1
if (!$resourceEnum) {
throw "The resource url is not supported. Supported values are: " + ($environment.Endpoints.Values -join ", ")
}
$authFactory = [Microsoft.Azure.Commands.Common.Authentication.IAuthenticationFactory] [Microsoft.Azure.Commands.Common.Authentication.AzureSession]:: AuthenticationFactory
$authResult = $authFactory.Authenticate(`
$rmContext.Account, `
$rmContext.Environment, `
$tenantId, `
[System.Security.SecureString] $null, `
[Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Auto, `
$resourceEnum.Key)
if ($null -eq $authResult) {
throw "Unable to get access token. Authentication Failed."
}
if (-not $authResult.AccessToken) {
throw "Unable to get access token. Authentication Failed."
}
return $authResult.AccessToken
}
static [string] GetAccessToken([string] $resourceAppIdUri) {
return [Helpers]::GetAccessToken($resourceAppIdUri, "");
}
static [System.Management.Automation.RuntimeDefinedParameterDictionary] NewDynamicParam([string] $parameterName, [string[]] $options, [bool] $mandatory, [string] $parameterSetName, [string] $helpMessage) {
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
#$ParameterAttribute.ValueFromPipeline = $false
#$ParameterAttribute.ValueFromPipelineByPropertyName = $false
$ParameterAttribute.Mandatory = $mandatory
if (-not [string]::IsNullOrEmpty($helpMessage)) {
$ParameterAttribute.HelpMessage = $helpMessage;
}
if (-not [string]::IsNullOrEmpty($parameterSetName)) {
$ParameterAttribute.ParameterSetName = $parameterSetName;
}
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($options)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($parameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($parameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
static [bool] CompareObject($referenceObject, $differenceObject) {
$result = $true;
if($null -ne $referenceObject)
{
if($null -ne $differenceObject)
{
($referenceObject | Get-Member -MemberType Properties) |
ForEach-Object {
$refProp = $referenceObject."$($_.Name)";
if ($differenceObject | Get-Member -Name $_.Name) {
$compareProp = $differenceObject."$($_.Name)";
if($null -ne $refProp)
{
if($null -ne $compareProp)
{
if ($refProp.GetType().Name -eq "PSCustomObject")
{
$result = $result -and [Helpers]::CompareObject($refProp, $compareProp);
}
else
{
$result = $result -and (((Compare-Object $refProp $compareProp) | Where-Object { $_.SideIndicator -eq "<=" } | Measure-Object).Count -eq 0)
}
}
else
{
$result = $result -and $false;
}
}
elseif($null -eq $compareProp)
{
$result = $result -and $true;
}
else
{
$result = $result -and $false;
}
}
else
{
$result = $false;
}
}
}
else
{
$result = $false;
}
}
elseif($null -eq $differenceObject)
{
$result = $true;
}
else
{
$result = $false;
}
return $result;
}
static [bool] CheckMember([PSObject] $refObject, [string] $memberPath) {
[bool]$result = $false;
if ($refObject) {
$properties = @();
$properties += $memberPath.Split(".");
if ($properties.Count -gt 0) {
$currentItem = $properties.Get(0);
if (-not [string]::IsNullOrEmpty($currentItem)) {
if (($refObject | Get-Member -Name $currentItem) -and $refObject.$currentItem) {
$result = $true;
if ($properties.Count -gt 1) {
$result = $result -and [Helpers]::CheckMember($refObject.$currentItem, [string]::Join(".", $properties[1..($properties.length - 1)]));
}
}
}
}
}
return $result;
}
static [PSObject] NewAzsdkCompliantStorage([string]$Name, [string]$ResourceGroup, [string]$Location) {
$storageSku = "Standard_GRS"
$storageObject = $null
try {
#create storage
$newStorage = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroup -Name $Name -Type $storageSku -Location $Location `
-Kind BlobStorage -AccessTier Cool -EnableEncryptionService Blob -ErrorAction Stop
$retryAccount = 0
do {
$storageObject = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroup -Name $Name -ErrorAction SilentlyContinue
Start-Sleep -seconds 2
$retryAccount++
}while (!$storageObject -and $retryAccount -ne 6)
if ($storageObject) {
#create alert rules
$emailAction = New-AzureRmAlertRuleEmail -SendToServiceOwners -ErrorAction Stop
$targetId = $storageObject.Id + "/services/" + "blob"
$alertName = $Name + "alert"
Add-AzureRmMetricAlertRule -Location $storageObject.Location -MetricName AnonymousSuccess -Name $alertName -Operator GreaterThan `
-ResourceGroup $storageObject.ResourceGroupName `
-TargetResourceId $targetId `
-Threshold 0 -TimeAggregationOperator Total -WindowSize 01:00:00 -Actions $emailAction `
-WarningAction SilentlyContinue `
-ErrorAction Stop
#set diagnostics on
$currentContext = $storageObject.Context
Set-AzureStorageServiceLoggingProperty -ServiceType Blob -LoggingOperations All -Context $currentContext -RetentionDays 365 -PassThru -ErrorAction Stop
Set-AzureStorageServiceMetricsProperty -MetricsType Hour -ServiceType Blob -Context $currentContext -MetricsLevel ServiceAndApi -RetentionDays 365 -PassThru -ErrorAction Stop
}
}
catch {
#cleanup storage if error occurs
if ((Find-AzureRmResource -ResourceGroupNameEquals $ResourceGroup -ResourceNameEquals $Name|Measure-Object).Count -gt 0) {
Remove-AzureRmStorageAccount -ResourceGroupName $ResourceGroup -Name $Name -Force -ErrorAction SilentlyContinue
}
}
return $storageObject
}
static [bool] NewAzSDKResourceGroup([string]$ResourceGroup, [string]$Location, [string] $Version)
{
try
{
if([string]::IsNullOrWhiteSpace($Version))
{
$RGTags += @{
"AzSDKFeature" = "ContinuousAssurance";
"CreationTime"=$(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss");
}
}
else
{
$RGTags += @{
"AzSDKFeature" = "ContinuousAssurance";
"AzSDKVersion"=$Version;
"CreationTime"=$(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss");
}
}
$newRG = New-AzureRmResourceGroup -Name $ResourceGroup -Location $Location `
-Tag $RGTags `
-ErrorAction Stop
return $true
}
catch
{
return $false
}
}
static [string] ComputeHash([String] $data)
{
$HashValue = [System.Text.StringBuilder]::new()
[System.Security.Cryptography.HashAlgorithm]::Create("SHA256").ComputeHash([System.Text.Encoding]::UTF8.GetBytes($data))| ForEach-Object {
[void]$HashValue.Append($_.ToString("x"))
}
return $HashValue.ToString()
}
static [string] GetCurrentSessionUser()
{
$context = Get-AzureRmContext -ErrorAction SilentlyContinue
if($null -ne $context)
{
return $context.Account.Id
}
else
{
return "NO_ACTIVE_SESSION"
}
}
static [VerificationResult] EvaluateVerificationResult([VerificationResult] $verificationResult, [AttestationStatus] $attestationStatus)
{
[VerificationResult] $result = $verificationResult;
# No action required if Attestation status is None OR verification result is Passed
if($attestationStatus -ne [AttestationStatus]::None -or $verificationResult -ne [VerificationResult]::Passed)
{
# Changing State Machine logic
#if($verificationResult -eq [VerificationResult]::Verify -or $verificationResult -eq [VerificationResult]::Manual)
#{
switch ($attestationStatus)
{
([AttestationStatus]::NotAnIssue)
{
$result = [VerificationResult]::Passed;
break;
}
([AttestationStatus]::NotFixed)
{
$result = [VerificationResult]::RiskAck;
break;
}
}
#}
#elseif($verificationResult -eq [VerificationResult]::Failed -or $verificationResult -eq [VerificationResult]::Error)
#{
# $result = [VerificationResult]::RiskAck;
#}
}
return $result;
}
static [PSObject] NewSecurePassword()
{
#create password
$randomBytes = New-Object Byte[] 32
$provider = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
$provider.GetBytes($randomBytes)
$provider.Dispose()
$pwstring = [System.Convert]::ToBase64String($randomBytes)
$newPassword = new-object securestring
$pwstring.ToCharArray() | ForEach-Object{
$newPassword.AppendChar($_)
}
$encryptedPassword = ConvertFrom-SecureString -SecureString $newPassword -Key (1..16)
$securePassword = ConvertTo-SecureString -String $encryptedPassword -Key (1..16)
return $securePassword
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/SecurityCenterHelper.ps1
|
SecurityCenterHelper.ps1
|
using namespace Microsoft.Azure.Commands.Resources.Models.Authorization
Set-StrictMode -Version Latest
class SecurityCenterHelper
{
static [string] $PoliciesApi = "policies";
static [string] $AlertsApi = "alerts";
static [string] $TasksApi = "tasks";
static [string] $SecurityStatusApi = "securityStatuses";
static [string] $ApiVersion = "?api-version=2015-06-01-preview";
static [System.Object[]] InvokeGetSecurityCenterRequest([string] $subscriptionId, [string] $apiType)
{
if([string]::IsNullOrWhiteSpace($subscriptionId))
{
throw [System.ArgumentException] ("The argument 'subscriptionId' is null");
}
if([string]::IsNullOrWhiteSpace($apiType))
{
throw [System.ArgumentException] ("The argument 'apiType' is null");
}
$uri = [WebRequestHelper]::AzureManagementUri + "subscriptions/$subscriptionId/providers/microsoft.Security/$($apiType)$([SecurityCenterHelper]::ApiVersion)";
return [WebRequestHelper]::InvokeGetWebRequest($uri);
}
static [System.Object[]] InvokePutSecurityCenterRequest([string] $resourceId, [System.Object] $body)
{
if([string]::IsNullOrWhiteSpace($resourceId))
{
throw [System.ArgumentException] ("The argument 'resourceId' is null");
}
$uri = [WebRequestHelper]::AzureManagementUri.TrimEnd("/") + $resourceId + [SecurityCenterHelper]::ApiVersion;
return [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Put, $uri, $body);
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/Constants.ps1
|
Constants.ps1
|
Set-StrictMode -Version Latest
class Constants
{
#All constant used across all modules Defined Here.
static [string] $DoubleDashLine = "================================================================================"
static [string] $HashLine = "################################################################################"
static [string] $SingleDashLine = "--------------------------------------------------------------------------------"
static [string] $UnderScoreLineLine= "________________________________________________________________________________"
static [string] $Info = "Info:"
static [string] $OutputLogFilePath = "null"
static [string] $RemediationMsg = "** Next steps **`r`n
Look at the individual control evaluation status in the CSV file.`r
a) If the control has passed, no action is necessary.`r
b) If the control has failed, look at the control evaluation detail in the LOG file to understand why.`r
c) If the control status says 'Verify', it means that human judgement is required to determine the final control status. Look at the control evaluation output in the LOG file to make a determination.`r
d) Lastly, if the control status says 'Manual', it means that AzSDK (currently) does not cover the control via automation OR AzSDK is not able to fetch the data. You need to manually implement/verify it.`r"
static [string] $OfflineModeWarning = "Running in offline policy mode. Commands will run against local JSON files!"
#Constants for SVTs
static [string] $ModuleStartHeading = [Constants]::DoubleDashLine +
"`r`nInfo: Starting analysis - [FeatureName: {0}] [ResourceGroupName: {1}] [ResourceName: {2}] `r`n" + [Constants]::SingleDashLine
static [string] $ModuleStartHeadingSub = [Constants]::DoubleDashLine +
"`r`nInfo: Starting analysis - [FeatureName: {0}] [SubscriptionName: {1}] [SubscriptionId: {2}] `r`n" + [Constants]::SingleDashLine
static [string] $AnalysingControlHeading = "Info: Checking: [{0}]-[{1}]"
static [string] $AnalysingControlHeadingSub = "Info: Checking: [{0}]-[{1}]"
static [string] $CompletedAnalysis = [Constants]::SingleDashLine + "`r`nCompleted analysis: [FeatureName: {0}] [ResourceGroupName: {1}] [ResourceName: {2}] `r`n" + [Constants]::DoubleDashLine
static [string] $CompletedAnalysisSub = [Constants]::SingleDashLine + "`r`nCompleted analysis: [FeatureName: {0}] [SubscriptionName: {1}] [SubscriptionId: {2}] `r`n" + [Constants]::DoubleDashLine
#Constants for Attestation
static [string] $ModuleAttestStartHeading = [Constants]::DoubleDashLine +
"`r`nInfo: Starting attestation - [FeatureName: {0}] [ResourceGroupName: {1}] [ResourceName: {2}] `r`n" + [Constants]::SingleDashLine
static [string] $ModuleAttestStartHeadingSub = [Constants]::DoubleDashLine +
"`r`nInfo: Starting attestation - [FeatureName: {0}] [SubscriptionName: {1}] [SubscriptionId: {2}] `r`n" + [Constants]::SingleDashLine
static [string] $CompletedAttestAnalysis = [Constants]::SingleDashLine + "`r`nCompleted attestation: [FeatureName: {0}] [ResourceGroupName: {1}] [ResourceName: {2}] `r`n" + [Constants]::DoubleDashLine
static [string] $CompletedAttestAnalysisSub = [Constants]::SingleDashLine + "`r`nCompleted attestation: [FeatureName: {0}] [SubscriptionName: {1}] [SubscriptionId: {2}] `r`n" + [Constants]::DoubleDashLine
static [string] $AzSdkAppFolderPath = $Env:LOCALAPPDATA + "\Microsoft\AzSDK"
static [string] $AzSdkLogFolderPath = $Env:LOCALAPPDATA + "\Microsoft\"
static [string] $AzSdkTempFolderPath = $env:TEMP + "\AzSDK\"
static [string] $ARMManagementUri = "https://management.azure.com/";
static [string] $VersionCheckMessage = "Warning: You are not running on latest version: {0} `r`nYou can get latest version by executing: {1} `r`n" + [Constants]::DoubleDashLine;
static [string] $UsageTelemetryKey = "cf4c5e1a-d68d-4ea1-9901-37b67f58a192";
static [string] $AzSDKRGLocation = "eastus2";
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/ActiveDirectoryHelper.ps1
|
ActiveDirectoryHelper.ps1
|
Set-StrictMode -Version Latest
class ActiveDirectoryHelper {
static [PSObject] GetADAppServicePrincipalByAppId($ApplicationId)
{
$TenantId = (Get-AzureRmContext -ErrorAction Stop).Tenant.TenantId
$ApiVersion = "1.6"
$GraphApiUrl = [WebRequestHelper]::GraphApiUri + $TenantId + "/servicePrincipals/{0}?api-version=$ApiVersion"
$uri = [string]::Format($GraphApiUrl + "&`$filter=(appId eq '{1}')", [string]::Empty , $ApplicationId);
$resultObject = [WebRequestHelper]::InvokeGetWebRequest($uri);
#this returns array of objects. Actual object is present at 1st index
if($resultObject)
{
return $resultObject[0]
}
else
{
return $null
}
}
static [void] UpdateADAppServicePrincipalCredential(
$ApplicationID,
[System.Security.Cryptography.X509Certificates.X509Certificate2]
$PublicCert,
[System.DateTime]
$NotBefore = (Get-Date).AddDays(-1),
[System.DateTime]
$NotAfter = $NotBefore.AddMonths(6),
[string]
$Delete = "False"
)
{
#Initialization
$TenantId = (Get-AzureRmContext -ErrorAction Stop).Tenant.TenantId
$ApiVersion = "1.6"
$GraphApiUrl = [WebRequestHelper]::GraphApiUri + $TenantId + "/servicePrincipals/{0}?api-version=$ApiVersion"
$addMode = $False;
$startDateString = $NotBefore.ToString("O");
$endDateString = $NotAfter.ToString("O");
if($Delete -eq "False")
{
if(-not $PublicCert)
{
throw "Public Certificate cannot be null"
}
}
$servicePrincipal = [ActiveDirectoryHelper]::GetADAppServicePrincipalByAppId($ApplicationID)
if($Delete -eq "False")
{
if($null -eq $servicePrincipal)
{
$addMode = $True;
$servicePrincipal = New-Object -TypeName PSObject;
$servicePrincipal | Add-Member -MemberType NoteProperty -Name appId -Value $ApplicationID -PassThru
}
$publicCertString = [System.Convert]::ToBase64String($PublicCert.GetRawCertData());
$credentialObject = New-Object -TypeName PSObject
$credentialObject | Add-Member -MemberType NoteProperty -Name endDate -Value $endDateString -PassThru `
| Add-Member -MemberType NoteProperty -Name startDate -Value $startDateString -PassThru
$credentialObject | Add-Member -MemberType NoteProperty -Name type -Value "AsymmetricX509Cert" -PassThru `
| Add-Member -MemberType NoteProperty -Name usage -Value "Verify" -PassThru `
| Add-Member -MemberType NoteProperty -Name value -Value $publicCertString
if ([bool](Get-Member -InputObject $servicePrincipal -Name "keyCredentials"))
{
[System.Collections.ArrayList]$keys = $servicePrincipal.keyCredentials
$credentialCound = $keys.Add($credentialObject)
$servicePrincipal.keyCredentials = $keys
}
else
{
$servicePrincipal | Add-Member -MemberType NoteProperty -Name keyCredentials -Value @($credentialObject)
}
}
elseif($Delete -eq "True")
{
$servicePrincipal.keyCredentials = $servicePrincipal.keyCredentials | Where-Object {
[System.DateTime]::Parse($_.startDate).ToUniversalTime() -ne $NotBefore.ToUniversalTime() `
-and [System.DateTime]::Parse($_.endDate).ToUniversalTime() -ne $NotAfter.ToUniversalTime() `
}
}
elseif($Delete -eq "All")
{
$servicePrincipal.keyCredentials = @()
}
$body = ConvertTo-Json -InputObject $servicePrincipal
$operation = [string]::Empty;
$requestUri = [string]::Empty;
$GraphAPIAccessToken = Get-AzSDKAccessToken -ResourceAppIdURI "https://graph.windows.net/";
if($addMode)
{
$operation = "POST";
$requestUri = [string]::Format($GraphApiUrl, [string]::Empty);
}
else
{
$operation = "PATCH";
$requestUri = [string]::Format($GraphApiUrl, $servicePrincipal.objectId);
}
$updateResult = Invoke-RestMethod `
-Method $operation `
-Uri $requestUri `
-Headers @{ Authorization = "Bearer " + $GraphAPIAccessToken } `
-ContentType "application/json" `
-Body $body `
-UseBasicParsing
if($null -eq $updateResult)
{
Throw "There was a problem while updating the service principal with new certificate"
}
}
static [PSObject] GetADAppByAppId($ApplicationId)
{
$TenantId = (Get-AzureRmContext -ErrorAction Stop).Tenant.TenantId
$ApiVersion = "1.6"
$GraphApiUrl = [WebRequestHelper]::GraphApiUri + $TenantId + "/applications/{0}?api-version=$ApiVersion"
$uri = [string]::Format($GraphApiUrl + "&`$filter=(appId eq '{1}')", [string]::Empty , $ApplicationId);
$resultObject = [WebRequestHelper]::InvokeGetWebRequest($uri);
#this returns array of objects. Actual object is present at 1st index
if($resultObject)
{
return $resultObject[0]
}
else
{
return $null
}
}
static [void] UpdateADAppCredential(
$ApplicationID,
[System.Security.Cryptography.X509Certificates.X509Certificate2]
$PublicCert,
[System.DateTime]
$NotBefore = (Get-Date).AddDays(-1),
[System.DateTime]
$NotAfter = $NotBefore.AddMonths(6),
[string]
$Delete = "False"
)
{
#Initialization
$TenantId = (Get-AzureRmContext -ErrorAction Stop).Tenant.TenantId
$ApiVersion = "1.6"
$GraphApiUrl = [WebRequestHelper]::GraphApiUri + $TenantId + "/applications/{0}?api-version=$ApiVersion"
$addMode = $False;
$startDateString = $NotBefore.ToString("O");
$endDateString = $NotAfter.ToString("O");
if($Delete -eq "False")
{
if(-not $PublicCert)
{
throw "Public Certificate cannot be null"
}
}
$ADApplication = [ActiveDirectoryHelper]::GetADAppByAppId($ApplicationID)
if($Delete -eq "False")
{
if($null -eq $ADApplication)
{
$addMode = $True;
$ADApplication = New-Object -TypeName PSObject;
$ADApplication | Add-Member -MemberType NoteProperty -Name appId -Value $ApplicationID -PassThru
}
$publicCertString = [System.Convert]::ToBase64String($PublicCert.GetRawCertData());
$credentialObject = New-Object -TypeName PSObject
$credentialObject | Add-Member -MemberType NoteProperty -Name endDate -Value $endDateString -PassThru `
| Add-Member -MemberType NoteProperty -Name startDate -Value $startDateString -PassThru
$credentialObject | Add-Member -MemberType NoteProperty -Name type -Value "AsymmetricX509Cert" -PassThru `
| Add-Member -MemberType NoteProperty -Name usage -Value "Verify" -PassThru `
| Add-Member -MemberType NoteProperty -Name value -Value $publicCertString
if ([bool](Get-Member -InputObject $ADApplication -Name "keyCredentials"))
{
[System.Collections.ArrayList]$keys = $ADApplication.keyCredentials
$credentialCound = $keys.Add($credentialObject)
$ADApplication.keyCredentials = $keys
}
else
{
$ADApplication | Add-Member -MemberType NoteProperty -Name keyCredentials -Value @($credentialObject)
}
}
elseif($Delete -eq "True")
{
$ADApplication.keyCredentials = $ADApplication.keyCredentials | Where-Object {
[System.DateTime]::Parse($_.startDate).ToUniversalTime() -ne $NotBefore.ToUniversalTime() `
-and [System.DateTime]::Parse($_.endDate).ToUniversalTime() -ne $NotAfter.ToUniversalTime() `
}
}
elseif($Delete -eq "All")
{
$ADApplication.keyCredentials = @()
}
$body = ConvertTo-Json -InputObject $ADApplication
$operation = [string]::Empty;
$requestUri = [string]::Empty;
$GraphAPIAccessToken = Get-AzSDKAccessToken -ResourceAppIdURI "https://graph.windows.net/";
if($addMode)
{
$operation = "POST";
$requestUri = [string]::Format($GraphApiUrl, [string]::Empty);
}
else
{
$operation = "PATCH";
$requestUri = [string]::Format($GraphApiUrl, $ADApplication.objectId);
}
$updateResult = Invoke-RestMethod `
-Method $operation `
-Uri $requestUri `
-Headers @{ Authorization = "Bearer " + $GraphAPIAccessToken } `
-ContentType "application/json" `
-Body $body `
-UseBasicParsing
if($null -eq $updateResult)
{
Throw "There was a problem while updating the service principal with new certificate"
}
}
static [PSObject] NewSelfSignedCertificate($AppName,$CertStartDate,$CertEndDate,$Provider)
{
$newCertificate = New-SelfSignedCertificate -DnsName $AppName `
-Subject "CN=$AppName" `
-CertStoreLocation Cert:\CurrentUser\My `
-KeyExportPolicy Exportable `
-NotBefore $CertStartDate `
-NotAfter $CertEndDate `
-Type DocumentEncryptionCert `
-KeyUsage DataEncipherment `
-KeySpec KeyExchange `
-KeyUsageProperty Decrypt `
-Provider $Provider `
-ErrorAction Stop
return $newCertificate
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Helpers/WebRequestHelper.ps1
|
WebRequestHelper.ps1
|
Set-StrictMode -Version Latest
class WebRequestHelper {
hidden static [string] $AzureManagementUri = "https://management.azure.com/";
hidden static [string] $GraphApiUri = "https://graph.windows.net/";
hidden static [string] $ClassicManagementUri = "https://management.core.windows.net/";
static [System.Object[]] InvokeGetWebRequest([string] $uri, [Hashtable] $headers)
{
return [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null);
}
static [System.Object[]] InvokeGetWebRequest([string] $uri)
{
return [WebRequestHelper]::InvokeGetWebRequest($uri, [WebRequestHelper]::GetAuthHeaderFromUri($uri));
}
hidden static [Hashtable] GetAuthHeaderFromUri([string] $uri)
{
[System.Uri] $validatedUri = $null;
if([System.Uri]::TryCreate($uri, [System.UriKind]::Absolute, [ref] $validatedUri))
{
return @{
"Authorization"= ("Bearer " + [Helpers]::GetAccessToken($validatedUri.GetLeftPart([System.UriPartial]::Authority)));
"Content-Type"="application/json"
};
}
return @{ "Content-Type"="application/json" };
}
static [System.Object[]] InvokePostWebRequest([string] $uri, [Hashtable] $headers, [System.Object] $body)
{
return [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Post, $uri, $headers, $body);
}
static [System.Object[]] InvokePostWebRequest([string] $uri, [System.Object] $body)
{
return [WebRequestHelper]::InvokePostWebRequest($uri, [WebRequestHelper]::GetAuthHeaderFromUri($uri), $body);
}
static [System.Object[]] InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod] $method, [string] $uri, [System.Object] $body)
{
return [WebRequestHelper]::InvokeWebRequest($method, $uri, [WebRequestHelper]::GetAuthHeaderFromUri($uri), $body);
}
static [System.Object[]] InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod] $method, [string] $uri, [Hashtable] $headers, [System.Object] $body)
{
$outputValues = @();
[System.Uri] $validatedUri = $null;
while ([System.Uri]::TryCreate($uri, [System.UriKind]::Absolute, [ref] $validatedUri))
{
$requestResult = $null;
if ($method -eq [Microsoft.PowerShell.Commands.WebRequestMethod]::Get)
{
$requestResult = Invoke-WebRequest -Method $method -Uri $validatedUri -Headers $headers -UseBasicParsing
}
elseif ($method -eq [Microsoft.PowerShell.Commands.WebRequestMethod]::Post -or $method -eq [Microsoft.PowerShell.Commands.WebRequestMethod]::Put)
{
$requestResult = Invoke-WebRequest -Method $method -Uri $validatedUri -Headers $headers -Body ($body | ConvertTo-Json -Depth 10 -Compress)
}
else
{
throw [System.ArgumentException] ("The web request method type '$method' is not supported.")
}
if ($null -ne $requestResult -and $requestResult.StatusCode -ge 200 -and $requestResult.StatusCode -le 399) {
if ($null -ne $requestResult.Content) {
$json = (ConvertFrom-Json $requestResult.Content)
if ($null -ne $json) {
if (($json | Get-Member -Name "value") -and $json.value) {
$outputValues += $json.value;
}
else {
$outputValues += $json;
}
if (($json | Get-Member -Name "nextLink") -and $json.nextLink) {
$uri = $json.nextLink
}
else {
$uri = [string]::Empty;
}
}
}
}
}
return $outputValues;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/AzSdkSettings.ps1
|
AzSdkSettings.ps1
|
#
# AzSdkSettings.ps1
#
Set-StrictMode -Version Latest
class AzSdkSettings {
[string] $OMSWorkspaceId;
[string] $OMSSharedKey;
[string] $OMSType;
[string] $OMSSource;
[bool] $EnableAADAuthForOnlinePolicyStore;
[bool] $UseOnlinePolicyStore;
[string] $OnlinePolicyStoreUrl;
[string] $UsageTelemetryLevel;
[string] $LocalControlTelemetryKey;
[bool] $LocalEnableControlTelemetry;
hidden static [AzSdkSettings] $Instance = $null;
hidden static [string] $FileName = "AzSdkSettings.json";
hidden AzSdkSettings() {
$this.OMSWorkspaceId = ""
$this.OMSSharedKey = ""
$this.OMSType = "AzSDK"
$this.OMSSource = "SDL"
}
static [AzSdkSettings] GetInstance() {
if (-not [AzSdkSettings]::Instance)
{
[AzSdkSettings]::Instance = [AzSdkSettings]::new();
[AzSdkSettings]::Instance.LoadAzSdkSettings();
}
return [AzSdkSettings]::Instance
}
hidden [void] LoadAzSdkSettings() {
#Filename will be static.
#For AzSDK Settings, never use online policy store. Its assumed that file will be available offline
$localSettings = [ConfigurationHelper]::LoadOfflineConfigFile([AzSdkSettings]::FileName)
#Validate settings content is not null
if ($localSettings) {
try
{
# Try parsing the object
[AzSdkSettings]::Instance = [AzSdkSettings] $localSettings
}
catch
{
# Any error occured while converting local json file indicates change in schema
#Load v2 AzSDKSettings from modules folder
[AzSdkSettings]::Instance = [ConfigurationHelper]::LoadModuleJsonFile([AzSdkSettings]::FileName)
$migratedPropNames = @();
[AzSdkSettings]::Instance | Get-Member -MemberType Properties |
ForEach-Object {
$propertyName = $_.Name;
if([Helpers]::CheckMember($localSettings, $propertyName))
{
[AzSdkSettings]::Instance.$propertyName = $localSettings.$propertyName;
$migratedPropNames += $propertyName;
}
};
if($migratedPropNames.Count -ne 0)
{
[AzSdkSettings]::Instance.Update()
[EventBase]::PublishGenericCustomMessage("Local AzSDK settings file was not compatible with the latest version. `r`nMigrated the existing values for properties: [$([string]::Join(", ", $migratedPropNames))] ", [MessageType]::Warning);
}
}
}
}
[void] Update()
{
if (-not (Test-Path $([Constants]::AzSdkAppFolderPath)))
{
mkdir -Path $([Constants]::AzSdkAppFolderPath) -ErrorAction Stop | Out-Null
}
#persisting back to file
[AzSdkSettings]::Instance | ConvertTo-Json | Out-File -Force -FilePath ([Constants]::AzSdkAppFolderPath + "\" + [AzSdkSettings]::FileName)
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/AzSdkGenericEvent.ps1
|
AzSdkGenericEvent.ps1
|
Set-StrictMode -Version Latest
class AzSdkGenericEvent
{
static [string] $CustomMessage = "AzSdk.Generic.CustomMessage"; #EventArgument: MessageData
static [string] $Exception = "AzSdk.Generic.Exception"; #EventArgument: ErrorRecord
}
class MessageDataBase
{
[string] $Message = "";
[PSObject] $DataObject;
MessageDataBase()
{ }
MessageDataBase([string] $message, [PSObject] $dataObject)
{
if($dataObject -and ($dataObject | Measure-Object).Count -ne 0)
{
$this.DataObject = $dataObject;
$this.Message = $message;
}
else
{
throw [System.ArgumentException] ("The argument 'dataObject' is null or empty");
}
}
}
class MessageData: MessageDataBase
{
[MessageType] $MessageType = [MessageType]::Info;
MessageData()
{ }
MessageData([string] $message, [MessageType] $messageType)
{
$this.Message = $message;
$this.MessageType = $messageType;
}
MessageData([string] $message, [PSObject] $dataObject, [MessageType] $messageType)
{
$this.Message = $message;
$this.DataObject = $dataObject;
$this.MessageType = $messageType;
}
MessageData([string] $message, [PSObject] $dataObject)
{
$this.Message = $message;
$this.DataObject = $dataObject;
}
MessageData([string] $message)
{
$this.Message = $message;
}
MessageData([PSObject] $dataObject)
{
$this.DataObject = $dataObject;
}
MessageData([PSObject] $dataObject, [MessageType] $messageType)
{
$this.MessageType = $messageType;
$this.DataObject = $dataObject;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/AzSdkConfig.ps1
|
AzSdkConfig.ps1
|
Set-StrictMode -Version Latest
class AzSdkConfig
{
[string] $MaintenanceMessage
[Environment] $Environment
[string] $AzSDKRGName
[string] $AzSDKRepoURL
[string] $AzSDKServerVersion
[string[]] $SubscriptionMandatoryTags = @()
[string] $ERvNetResourceGroupNames
[string] $UpdateCompatibleCCVersion
[string] $AzSDKApiBaseURL;
[bool] $PublishVulnDataToApi;
[string] $ControlTelemetryKey;
[bool] $EnableControlTelemetry;
[string] $PolicyMessage;
[string] $InstallationCommand;
hidden static [AzSdkConfig] $Instance = $null;
static [AzSdkConfig] GetInstance([bool] $useOnlinePolicyStore, [string] $onlineStoreUri, [bool] $enableAADAuthForOnlinePolicyStore)
{
if ( $null -eq [AzSdkConfig]::Instance)
{
[AzSdkConfig]::Instance = [AzSdkConfig]::LoadRootConfiguration($useOnlinePolicyStore,$onlineStoreUri,$enableAADAuthForOnlinePolicyStore)
}
return [AzSdkConfig]::Instance
}
hidden static [AzSdkConfig] LoadRootConfiguration([bool] $useOnlinePolicyStore, [string] $onlineStoreUri, [bool] $enableAADAuthForOnlinePolicyStore)
{
#Filename will be static.
return [AzSdkConfig] ([ConfigurationHelper]::LoadServerConfigFile("AzSdk.json", $useOnlinePolicyStore, $onlineStoreUri, $enableAADAuthForOnlinePolicyStore));
}
hidden [string] GetLatestAzSDKVersion([string] $moduleName)
{
if([string]::IsNullOrWhiteSpace($this.AzSDKServerVersion))
{
$this.AzSDKServerVersion = "0.0.0.0";
try
{
$moduleDetails = (Find-Module $moduleName -Repository "PSGallery")
$this.AzSDKServerVersion = $moduleDetails.Version
}
catch
{
$this.AzSDKServerVersion = "0.0.0.0";
}
}
return $this.AzSDKServerVersion;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/ControlState.ps1
|
ControlState.ps1
|
Set-StrictMode -Version Latest
class ControlState
{
ControlState()
{
}
ControlState([string]$ControlId, [string] $InternalId, [string] $ChildResourceName, [string] $ActualVerificationResult, [string]$Version)
{
$this.ControlId = $ControlId;
$this.InternalId = $InternalId;
$this.ChildResourceName = $ChildResourceName;
$this.ActualVerificationResult = $ActualVerificationResult;
#setting the effective control result default value actual. It would be reset once it is computed based on user input
$this.EffectiveVerificationResult = $ActualVerificationResult;
$this.Version = $Version;
}
[string] $ControlId
[string] $InternalId
[string] $ResourceId
[string] $HashId
[StateData] $State
[string] $ChildResourceName
[VerificationResult] $ActualVerificationResult
[VerificationResult] $EffectiveVerificationResult
[AttestationStatus] $AttestationStatus = [AttestationStatus]::None;
[string] $Version
}
class ControlStateIndexer
{
[string] $ResourceId
[string] $HashId
[DateTime] $ExpiryTime
[string] $AttestedBy
[DateTime] $AttestedDate
[string] $Version
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/Enums.ps1
|
Enums.ps1
|
Set-StrictMode -Version Latest
enum VerificationResult
{
Manual
Passed
RiskAck
Verify
Failed
Error
Disabled
}
enum AttestationStatus
{
None
NotAnIssue
NotFixed
}
enum AttestControls
{
None
All
AlreadyAttested
NotAttested
}
enum MessageType
{
Critical
Error
Warning
Info
Update
Deprecated
}
enum ControlSeverity
{
Critical
High
Medium
Low
}
enum Environment
{
SDL
CICD
CC
}
enum ScanSource
{
SpotCheck
VSO
Runbook
}
enum FeatureGroup
{
Unknown
Subscription
Service
}
enum ServiceScanKind
{
Partial
ResourceGroup
Subscription
}
enum SubscriptionScanKind
{
Partial
Complete
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/AzSdkEvent.ps1
|
AzSdkEvent.ps1
|
Set-StrictMode -Version Latest
class AzSdkRootEvent
{
static [string] $CustomMessage = "AzSdk.CustomMessage"; #EventArgument: AzSdkRootEventArgument
static [string] $GenerateRunIdentifier = "AzSdk.GenerateRunIdentifier"; #Creates a timestamp and publish, Initialize listeners #EventArgument: AzSdkRootEventArgument
static [string] $UnsupportedResources = "AzSdk.UnsupportedResources";
#Command level event
static [string] $CommandStarted = "AzSdk.Command.Started"; #Initialize listeners #Command execution started #EventArgument: AzSdkRootEventArgument
static [string] $CommandCompleted = "AzSdk.Command.Completed"; #Cleanup listeners #Command execution completed #EventArgument: AzSdkRootEventArgument
static [string] $CommandError = "AzSdk.Command.Error"; #EventArgument: AzSdkRootEventArgument
static [string] $CommandProcessing = "AzSdk.Command.Processing"; #EventArgument: AzSdkRootEventArgument
}
class SubscriptionContext
{
[string] $SubscriptionId = "";
[string] $SubscriptionName = "";
[string] $Scope = "";
}
class AzSdkRootEventArgument
{
[SubscriptionContext] $SubscriptionContext;
[MessageData[]] $Messages = @();
hidden [System.Management.Automation.ErrorRecord] $ExceptionMessage
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SubscriptionCore/ManagementCertificate.ps1
|
ManagementCertificate.ps1
|
Set-StrictMode -Version Latest
class ManagementCertificate
{
[string] $CertThumbprint
[string] $SubjectName
[string] $Issuer
[PSObject] $Created
[PSObject] $ExpiryDate
[string] $IsExpired
[PSObject] $Difference
[bool] $Whitelisted
hidden static [ManagementCertificate[]] ListManagementCertificates([PSObject] $certObjects)
{
[ManagementCertificate[]] $certs = @()
$certObjects | ForEach-Object{
[ManagementCertificate] $certObject = [ManagementCertificate]::new();
$b64cert = $_.SubscriptionCertificateData
$certData = [System.Convert]::FromBase64String($b64Cert)
$certX = [System.Security.Cryptography.X509Certificates.X509Certificate2]($certData)
$certObject.ExpiryDate = $certX.NotAfter.ToString("yyyy-MM-dd HH:mm:ss")
$certObject.CertThumbprint = $_.SubscriptionCertificateThumbprint
$certObject.SubjectName = $certX.Subject
$certObject.Issuer = $certX.Issuer
$certObject.Created = $_.Created
$certObject.IsExpired = "False"
$certObject.Difference = New-TimeSpan -Start ([datetime]$certX.NotBefore) -End ([datetime]$certX.NotAfter)
if([System.DateTime]::UtcNow -ge $certX.NotAfter)
{
$certObject.IsExpired = "True"
}
#Has to be moved to new confiuration model
$certObject.Whitelisted = $false
$certs += $certObject
}
return $certs;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SubscriptionCore/AzureSecurityCenter.ps1
|
AzureSecurityCenter.ps1
|
Set-StrictMode -Version Latest
class AzureSecurityCenter
{
[PSObject] $Policies
[PSObject] $Alerts
[PSObject] $Tasks
hidden static [PSObject] GetASCPolicies([PSObject] $policyObjects)
{
$pols =@()
if($null -ne $policyObjects -and ($policyObjects | Measure-Object).Count -gt 0)
{
$policyObjects | ForEach-Object {
$out = "" | Select-Object PolicyLevel, Name, Unique, DataCollection, SystemUpdates, OSVulnerabilities, EndpointProtection, DiskEncryption, NetworkSecurityGroups, WebApplicationFirewall, NextGenerationFirewall, VulnerabilityAssessment, SQLAuditingAndThreatDetection, SQLTDE, StorageSSE, SecurityContactEmails, SecurityContactPhone, AreEmailNotificationsOn, SendToSubscriptionOwners, IsCompliant
Set-Variable -Name policyLevel -Value $_.properties.policyLevel
Set-Variable -Name logCollection -Value $_.properties.logCollection
Set-Variable -Name name -Value $_.name
Set-Variable -Name patch -Value $_.properties.recommendations.patch
Set-Variable -Name unique -Value $_.properties.unique
Set-Variable -Name baseline -Value $_.properties.recommendations.baseline
Set-Variable -Name antimalware -Value $_.properties.recommendations.antimalware
Set-Variable -Name diskEncryption -Value $_.properties.recommendations.diskEncryption
Set-Variable -Name acls -Value $_.properties.recommendations.acls
Set-Variable -Name waf -Value $_.properties.recommendations.waf
Set-Variable -Name sqlAuditing -Value $_.properties.recommendations.sqlAuditing
Set-Variable -Name sqlTde -Value $_.properties.recommendations.sqlTde
Set-Variable -Name ngfw -Value $_.properties.recommendations.ngfw
Set-Variable -Name vulnerabilityAssessment -Value $_.properties.recommendations.vulnerabilityAssessment
Set-Variable -Name storageEncryption -Value $_.properties.recommendations.storageEncryption
Set-Variable -Name securityContactEmails -Value $_.properties.securityContactConfiguration.securityContactEmails
Set-Variable -Name securityContactEmailsString
Set-Variable -Name securityContactPhone -Value $_.properties.securityContactConfiguration.securityContactPhone
Set-Variable -Name areNotificationsOn -Value $_.properties.securityContactConfiguration.areNotificationsOn
Set-Variable -Name sendToAdminOn -Value $_.properties.securityContactConfiguration.sendToAdminOn
Set-Variable -Name isPolicyViolation -Value $false
$out.PolicyLevel = $policyLevel
$out.Name = $name
$out.Unique = $unique
if($logCollection -eq "off" -or
$patch -eq "off" -or
$baseline -eq "off" -or
$antimalware -eq "off" -or
$diskEncryption -eq "off" -or
$acls -eq "off" -or
$waf -eq "off" -or
$ngfw -eq "off" -or
$vulnerabilityAssessment -eq "off" -or
$sqlAuditing -eq "off" -or
$storageEncryption -eq "off" -or
$sqlTde -eq "off"
)
{
$out.IsCompliant = $false
}
$out.DataCollection = $logCollection
$out.SystemUpdates = $patch
$out.OSVulnerabilities = $baseline
$out.EndpointProtection = $antimalware
$out.DiskEncryption = $diskEncryption
$out.NetworkSecurityGroups = $acls
$out.WebApplicationFirewall = $waf
$out.NextGenerationFirewall = $ngfw
$out.VulnerabilityAssessment = $vulnerabilityAssessment
$out.SQLAuditingAndThreatDetection = $sqlAuditing
$out.SQLTDE = $sqlTde
$out.StorageSSE = $storageEncryption
#SecurityContactEmails, SecurityContactPhone, AreEmailNotificationsOn, SendToSubscriptionOwners
$securityContactEmailsString = ""
if(($securityContactEmails | Measure-Object).Count -gt 0)
{
$securityContactEmails | ForEach-Object{ $securityContactEmailsString = $securityContactEmailsString + "," + $_.Trim() }
}
$securityContactEmailsString = $securityContactEmailsString.Replace(',','')
if([System.String]::IsNullOrWhiteSpace($securityContactEmailsString) -or
[System.String]::IsNullOrWhiteSpace($securityContactPhone) -or
$areNotificationsOn -eq $false -or
$sendToAdminOn -eq $false
)
{
$out.IsCompliant = $false
}
$out.SecurityContactEmails = $securityContactEmailsString
$out.SecurityContactPhone = $securityContactPhone
$out.AreEmailNotificationsOn = $areNotificationsOn
$out.SendToSubscriptionOwners = $sendToAdminOn
$pols += $out
}
}
return $pols;
}
hidden static [PSObject] GetASCAlerts([PSObject] $alertObjects)
{
$activeAlerts =@()
if($null -ne $alertObjects -and ($alertObjects | Measure-Object).Count -gt 0)
{
$alertObjects | ForEach-Object {
$out = "" | Select-Object AlertDisplayName, AlertName, Description, State, ReportedTimeUTC, RemediationSteps
Set-Variable -Name AlertDisplayName -Value $_.properties.alertDisplayName
Set-Variable -Name AlertName -Value $_.properties.alertName
Set-Variable -Name Description -Value $_.properties.description
Set-Variable -Name State -Value $_.properties.state
Set-Variable -Name ReportedTimeUTC -Value $_.properties.reportedTimeUtc
Set-Variable -Name RemediationSteps -Value $_.properties.remediationSteps
$out.AlertDisplayName = $AlertDisplayName
$out.AlertName = $AlertName
$out.Description = $Description
$out.State = $State
$out.ReportedTimeUTC = $ReportedTimeUTC
$out.RemediationSteps = $RemediationSteps
$activeAlerts += $out
}
}
return $activeAlerts;
}
hidden static [PSObject] GetASCTasks([PSObject] $taskObjects)
{
$activeTasks =@()
if($null -ne $taskObjects -and ($taskObjects | Measure-Object).Count -gt 0)
{
$taskObjects | ForEach-Object {
$out = "" | Select-Object Name, State, ResourceId
Set-Variable -Name Name -Value $_.properties.securityTaskParameters.name
Set-Variable -Name State -Value $_.properties.state
Set-Variable -Name ResourceId -Value $_.properties.securityTaskParameters.resourceId
$out.Name = $Name
$out.State = $State
$out.ResourceId = $ResourceId
$activeTasks += $out
}
}
return $activeTasks
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SVT/PSCloudService.ps1
|
PSCloudService.ps1
|
#
# CloudService.ps1
#
Set-StrictMode -Version Latest
class PSCloudService
{
[PSObject] $Name
[PSObject] $Configuration
[PSObject] $DeploymentSlot
[RoleInstance[]] $RoleInstances
[Role[]] $Roles
[PSObject] $VirtualIps
[PSObject] $UpgradeType
[PSObject] $UpgradeDomainCount
[Extension[]] $Extensions
hidden [void] LoadCloudConfiguration([xml] $CloudServiceResponse)
{
#$controlResult.AddMessage([MessageData]::new("Compliance details of Azure Active Directory applications:",
# $outputList));
# Get the results from the API as XML
#Write-Host ServiceName: -ForegroundColor DarkYellow
if($null -ne $CloudServiceResponse.hostedservice)
{
$this.Name = $CloudServiceResponse.hostedservice.ServiceName
if($null -ne $CloudServiceResponse.hostedservice.Deployments){
foreach($svc in $CloudServiceResponse.hostedservice.Deployments.Deployment)
{
$this.Configuration = [xml]([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($svc.Configuration)))
$this.DeploymentSlot = $svc.DeploymentSlot
$this.RoleInstances = @()
if($null -ne $svc.RoleInstanceList)
{
foreach($instance in $svc.RoleInstanceList.RoleInstance)
{
[RoleInstance] $roleInstance = [RoleInstance]::new()
$roleInstance.RoleName = $instance.RoleName
$roleInstance.InstanceName = $instance.RoleName
$roleInstance.PowerState = $instance.PowerState
$roleInstance.IPAddress = $instance.IpAddress
if($null -ne $instance.InstanceEndpoints -and $null -ne $instance.InstanceEndpoints.InstanceEndpoint)
{
$roleInstance.InstanceEndpoints = [array]($instance.InstanceEndpoints.InstanceEndpoint | Select-Object Name, Vip, PublicPort, LocalPort, Protocol)
}
$this.RoleInstances += $roleInstance
$this.Roles = @()
if($null -ne $svc.RoleList)
{
foreach($instance in $svc.RoleList.Role)
{
[Role] $role = [Role]::new()
$role.RoleName = $instance.RoleName
$role.OSVersion = $instance.OsVersion
if($null -ne $instance.ConfigurationSets.ConfigurationSet.InputEndpoints)
{
$role.InputEndpoint = [array]($instance.ConfigurationSets.ConfigurationSet.InputEndpoints.InputEndpoint | Select-Object Port, Protocol, Vip)
}
$this.Roles += $role
}
}
$this.VirtualIps = [array]($svc.VirtualIPs.VirtualIP | Select-Object Address, IsDnsProgrammed)
#if( $svc.UpgradeStatus -eq $null)
# {
# $this.UpgradeType = "Manual"
# }
# else
# {
# $this.UpgradeType = $svc.UpgradeStatus.UpgradeType
# }
$this.UpgradeDomainCount = $svc.UpgradeDomainCount
# Write-Host `nRole Extensions: -ForegroundColor DarkYellow
# Write-Host ------------------
$this.Extensions = @()
if($null -ne $svc.ExtensionConfiguration -and $null -ne $svc.ExtensionConfiguration.NamedRoles)
{
foreach($instance in $svc.ExtensionConfiguration.NamedRoles.Role)
{
[Extension] $extension = [Extension]::new()
$extension.RoleName = $instance.RoleName
if($null -ne $instance.Extensions.Extension)
{
$extension.ExtensionId = ($instance.Extensions.Extension | Select-Object Id )
}
$this.Extensions += $extension
}
}
}
}
}
}
}
}
}
class RoleInstance
{
[PSObject] $RoleName
[PSObject] $InstanceName
[PSObject] $PowerState
[PSObject] $IPAddress
[PSObject] $InstanceEndpoints
}
class Role
{
[PSObject] $RoleName
[PSObject] $OSVersion
[PSObject] $InputEndpoint
}
class Extension
{
[PSObject] $RoleName
[PSObject] $ExtensionId
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SVT/SVTResource.ps1
|
SVTResource.ps1
|
Set-StrictMode -Version Latest
class ResourceTypeMapping
{
[string] $ResourceTypeName
[string] $ResourceType
[string] $JsonFileName
[string] $ClassName
}
class SubscriptionMapping
{
[string] $JsonFileName
[string] $ClassName
}
class SVTResource
{
[string] $ResourceId = "";
[string] $ResourceGroupName = "";
[string] $ResourceName = "";
[string] $Location = "";
[string] $ResourceType = "";
hidden [ResourceTypeMapping] $ResourceTypeMapping = $null;
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SVT/SVTEvent.ps1
|
SVTEvent.ps1
|
Set-StrictMode -Version Latest
class SVTEvent
{
#First level event
#Command level event
static [string] $CommandStarted = "AzSdk.SVT.Command.Started"; #Initialize listeners #Function execution started
static [string] $CommandCompleted = "AzSdk.SVT.Command.Completed"; #Cleanup listeners #Function execution completed
static [string] $CommandError = "AzSdk.SVT.Command.Error";
#Second level event for every resource
static [string] $EvaluationStarted = "AzSdk.SVT.Evaluation.Started"; #Individual Resource execution started
static [string] $EvaluationCompleted = "AzSdk.SVT.Evaluation.Completed"; #Individual Resource execution completed
static [string] $EvaluationError = "AzSdk.SVT.Evaluation.Error";
#Control level events
static [string] $ControlStarted = "AzSdk.SVT.Control.Started"; #No DataObject
static [string] $ControlCompleted = "AzSdk.SVT.Control.Completed"; #All DataObjects
static [string] $ControlError = "AzSdk.SVT.Control.Error";
static [string] $ControlDisabled = "AzSdk.SVT.Control.Disabled"; #No DataObject
#static [string] $ControlProcessing = "AzSdk.SVT.Control.Processing"; #Individual DataObject
}
class ResourceContext
{
[string] $ResourceId =""
[string] $ResourceGroupName = ""
[string] $ResourceName = ""
[string] $ResourceType = ""
}
class ControlResult
{
[string] $ChildResourceName = "";
[VerificationResult] $VerificationResult = [VerificationResult]::Manual;
[VerificationResult] $ActualVerificationResult = [VerificationResult]::Manual;
[AttestationStatus] $AttestationStatus = [AttestationStatus]::None;
[StateManagement] $StateManagement = [StateManagement]::new();
[MessageData[]] $Messages = @();
[void] AddMessage([MessageData] $messageData)
{
if((-not [string]::IsNullOrEmpty($messageData.Message)) -or ($null -ne $messageData.DataObject))
{
$this.Messages += $messageData;
}
}
[void] AddMessage([VerificationResult] $result, [MessageData] $messageData)
{
$this.VerificationResult = $result;
$this.AddMessage($messageData);
}
[void] AddMessage([VerificationResult] $result, [string] $message, [PSObject] $dataObject)
{
$this.VerificationResult = $result;
$this.AddMessage([MessageData]::new($message, $dataObject));
}
[void] AddMessage([string] $message, [PSObject] $dataObject)
{
$this.AddMessage([MessageData]::new($message, $dataObject));
}
[void] AddMessage([PSObject] $dataObject)
{
$this.AddMessage([MessageData]::new($dataObject));
}
[void] AddMessage([string] $message)
{
$this.AddMessage([MessageData]::new($message));
}
[void] AddError([System.Management.Automation.ErrorRecord] $exception)
{
$this.AddMessage([MessageData]::new($exception, [MessageType]::Error));
}
[void] SetStateData([string] $message, [PSObject] $dataObject)
{
$this.StateManagement.CurrentStateData = [StateData]::new($message, $dataObject);
}
}
class StateManagement
{
[StateData] $AttestedStateData;
[StateData] $CurrentStateData;
}
class Metadata
{
[string] $Reference = ""
}
class StateData: MessageDataBase
{
[string] $Justification = "";
[string] $AttestedBy =""
[DateTime] $AttestedDate
StateData()
{
}
StateData([string] $message, [PSObject] $dataObject) :
Base($message, $dataObject)
{
}
}
class SVTEventContext: AzSdkRootEventArgument
{
[string] $FeatureName = ""
[Metadata] $Metadata
[ResourceContext] $ResourceContext;
[ControlItem] $ControlItem;
[ControlResult[]] $ControlResults = @();
[bool] IsResource()
{
if($this.ResourceContext)
{
return $true;
}
else
{
return $false;
}
}
[string] GetUniqueId()
{
$uniqueId = "";
if($this.IsResource())
{
$uniqueId = $this.ResourceContext.ResourceId;
}
else
{
$uniqueId = $this.SubscriptionContext.Scope;
}
# Unique Id validation
if([string]::IsNullOrWhiteSpace($uniqueId))
{
throw "Error while evaluating Unique Id. The parameter 'ResourceContext.ResourceId' OR 'SubscriptionContext.Scope' is null or empty."
}
return $uniqueId;
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SVT/SVTConfig.ps1
|
SVTConfig.ps1
|
Set-StrictMode -Version Latest
class SVTConfig
{
[string] $FeatureName = ""
[string] $Reference = ""
[bool] $IsManintenanceMode
[ControlItem[]] $Controls = @();
hidden static [SVTConfig] LoadServerConfigFile([string] $fileName, [bool] $useOnlinePolicyStore, [string] $onlineStoreUri, [bool] $enableAADAuthForOnlinePolicyStore)
{
return [SVTConfig]([ConfigurationHelper]::LoadServerConfigFile($fileName, $useOnlinePolicyStore, $onlineStoreUri, $enableAADAuthForOnlinePolicyStore));
}
}
class ControlItem
{
#Fields from JSON
[string] $ControlID = ""
[string] $Id = ""
[ControlSeverity] $ControlSeverity = [ControlSeverity]::High
[string] $Description = ""
[string] $Automated = ""
[string[]] $Tags = @()
[bool] $Enabled
hidden [string] $MethodName = ""
[string] $Recommendation = ""
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/RemoteReports/ScanResultModels.ps1
|
ScanResultModels.ps1
|
Set-StrictMode -Version Latest
class ScanInfoBase {
[ScanInfoVersion] $ScanInfoVersion;
[string] $SubscriptionId;
[string] $SubscriptionName;
[ScanSource] $Source;
[string] $ScannerVersion;
[string] $ControlVersion;
ScanInfoBase() {
$this.ScanInfoVersion = [ScanInfoVersion]::V1
}
}
class ControlResultBase {
[string] $ControlId;
[ControlSeverity] $ControlSeverity;
[VerificationResult] $ActualVerificationResult;
[AttestationStatus] $AttestationStatus;
[VerificationResult] $VerificationResult;
}
class SubscriptionControlResult : ControlResultBase {
}
class ServiceControlResult : ControlResultBase {
[bool] $IsNestedResource;
[string] $NestedResourceName;
}
class SubscriptionScanInfo : ScanInfoBase {
[SubscriptionScanKind] $ScanKind;
[SubscriptionControlResult[]] $ControlResults;
}
class ServiceScanInfo : ScanInfoBase {
[string] $Feature;
[ServiceScanKind] $ScanKind;
[string] $ResourceGroup;
[string] $ResourceName;
[string] $ResourceId;
[ServiceControlResult[]] $ControlResults;
}
enum ScanInfoVersion {
V1
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/ContinuousCompliance/AutomationAccount.ps1
|
AutomationAccount.ps1
|
Set-StrictMode -Version Latest
enum ScheduleFrequency
{
Hour
Day
}
class AutomationAccount
{
hidden [string] $Name
hidden [string] $ResourceGroup
hidden [string] $Location
hidden [string] $AzureADAppName
hidden [Hashtable] $RGTags
hidden [Hashtable] $AccountTags
}
class UserConfig
{
hidden [string] $ResourceGroupNames
hidden [OMSCredential] $OMSCredential
hidden [string] $StorageAccountName
hidden [string] $StorageAccountRG
}
class OMSCredential
{
hidden [string] $OMSWorkspaceId
hidden [string] $OMSSharedKey
}
class SelfSignedCertificate
{
hidden [DateTime] $CertStartDate
hidden [DateTime] $CertEndDate
hidden [DateTime] $CredStartDate
hidden [DateTime] $CredEndDate
hidden [string] $Provider
SelfSignedCertificate()
{
$this.CertStartDate = (Get-Date).AddDays(-1);
$this.CertEndDate = (Get-Date).AddMonths(6).AddDays(1);
$this.CredStartDate = (Get-Date);
$this.CredEndDate = (Get-Date).AddMonths(6);
$this.Provider = "Microsoft Enhanced RSA and AES Cryptographic Provider"
}
}
class Runbook
{
hidden [string] $Name
hidden [string] $Type
hidden [string] $Description
hidden [boolean] $LogProgress
hidden [boolean] $LogVerbose
hidden [string] $Key
#tags of dictionery type
}
class RunbookSchedule
{
hidden [string] $Name
hidden [string] $Frequency
hidden [int] $Interval
hidden [System.DateTime] $StartTime
hidden [System.DateTime] $ExpiryTime
hidden [string] $Description
hidden [string[]] $LinkedRubooks
hidden [string] $Key
}
class Variable
{
hidden [string] $Name
hidden [string] $Value
hidden [boolean] $IsEncrypted
hidden [string] $Description
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Models/SubscriptionSecurity/SubscriptionRBAC.ps1
|
SubscriptionRBAC.ps1
|
Set-StrictMode -Version Latest
# Defines data structure for subscription RBAC json
class SubscriptionRBAC
{
[ActiveRBACAccount[]] $ValidActiveAccounts = @();
[RBACAccount[]] $DeprecatedAccounts = @();
}
class RBACAccount
{
#Fields from JSON
[string] $Name = "";
[string] $Description = "";
[bool] $Enabled = $false;
[string] $ObjectId = "";
[string] $ObjectType = "";
[RBACAccountType] $Type = [RBACAccountType]::Validate;
}
class ActiveRBACAccount: RBACAccount
{
[string[]] $Tags = @();
[string] $RoleDefinitionName = "";
[string] $Scope = "";
}
enum RBACAccountType
{
# AzSDK should not Add/Delete the account
Validate
# The account can be fully managed (Add/Delete) from AzSDK
Provision
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/ContinuousCompliance/ContinuousCompliance.ps1
|
ContinuousCompliance.ps1
|
Set-StrictMode -Version Latest
function Install-AzSDKContinuousAssurance
{
<#
.SYNOPSIS
This command would help in installing Automation Account in your subscription to setup Continous Assurance feature of AzSDK
.DESCRIPTION
This command will install an Automation Account (Name: AzSDKContinuousAssurance) which runs security scan on subscription and resource groups which are specified during installation.
Security scan results will be populated in OMS which is configured during installation. Also detailed logs will be stored in storage account (Name: azsdkyyyyMMddHHmmss format).
.PARAMETER SubscriptionId
Subscription id in which Automation Account needs to be installed
.PARAMETER AutomationAccountLocation
Location of resource group which contains Automation Account. This is optional. Default location is EastUS2.
.PARAMETER ResourceGroupNames
Comma separated Application resource group names on which security scan should be performed by Automation Account.
.PARAMETER OMSWorkspaceId
Workspace ID of OMS where security scan results will be populated
.PARAMETER OMSSharedKey
Shared key of OMS which is used to monitor security scan results
.PARAMETER AzureADAppName
Name for the Azure Active Directory(AD) Application that will be created in the subscription for running the runbook
.NOTES
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[Parameter(Mandatory = $true)]
[string]
$SubscriptionId ,
[Parameter(Mandatory = $false)]
[string]
$AutomationAccountLocation="EastUS2",
[Parameter(Mandatory = $true)]
[string]
$ResourceGroupNames ,
[Parameter(Mandatory = $true)]
[string]
[ValidateNotNullOrEmpty()]
$OMSWorkspaceId,
[Parameter(Mandatory = $true)]
[string]
[ValidateNotNullOrEmpty()]
$OMSSharedKey,
[Parameter(Mandatory = $true)]
[string]
[ValidateNotNullOrEmpty()]
$AzureADAppName
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
try
{
$ccAccount = [CCAutomation]::new($SubscriptionId, $PSCmdlet.MyInvocation,`
$AutomationAccountLocation, $ResourceGroupNames,$OMSWorkspaceId,$OMSSharedKey,`
$AzureADAppName);
if ($ccAccount)
{
return $ccAccount.InvokeFunction($ccAccount.InstallAzSDKContinuousAssurance);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Update-AzSDKContinuousAssurance
{
<#
.SYNOPSIS
This command would help in updating user configurable properties of Continuous Assurance Automation Account in your subscription
.DESCRIPTION
This command is helpful if you want to update any of the following properties. 1. App Resource Groups 2. OMS Workspace ID 3. OMS Shared Key
4. Connection in Run As Account 5. Update/Renew Certificate in Run As Account
.PARAMETER SubscriptionId
Subscription id in which Automation Account exists
.PARAMETER ResourceGroupNames
Comma separated Application resource group names on which security scan should be performed by Automation Account
.PARAMETER OMSWorkspaceId
Workspace ID of OMS where security scan results will be populated
.PARAMETER OMSSharedKey
Shared key of OMS which is used to monitor security scan results
.PARAMETER AzureADAppName
Name for the Azure Active Directory(AD) Application that will be created to update automation account Connection in Run As Account for running the runbook
.PARAMETER UpdateCertificate
Switch to update certificate credential for AzureADApp SPN and also upload the certificate to automation account.
.NOTES
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[Parameter(Mandatory = $true)]
[string]
$SubscriptionId ,
[Parameter(Mandatory = $false)]
[string]
$ResourceGroupNames ,
[Parameter(Mandatory = $false)]
[string]
$OMSWorkspaceId,
[Parameter(Mandatory = $false)]
[string]
$OMSSharedKey,
[Parameter(Mandatory = $false)]
[string]
$AzureADAppName,
[Parameter(Mandatory = $false)]
[switch]
$UpdateCertificate
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
try
{
$ccAccount = [CCAutomation]::new($SubscriptionId, $PSCmdlet.MyInvocation);
if ($ccAccount)
{
return $ccAccount.InvokeFunction($ccAccount.UpdateAzSDKContinuousAssurance,@($ResourceGroupNames,$OMSWorkspaceId,$OMSSharedKey,$AzureADAppName,$UpdateCertificate));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Get-AzSDKContinuousAssurance
{
<#
.SYNOPSIS
This command would help in getting details of Continuous Assurance Automation Account in your subscription
.DESCRIPTION
.PARAMETER SubscriptionId
Subscription id in which Automation Account exists
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[Parameter(Mandatory = $true)]
[string]
$SubscriptionId
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
try
{
$ccAccount = [CCAutomation]::new($SubscriptionId, $PSCmdlet.MyInvocation);
if ($ccAccount)
{
return $ccAccount.InvokeFunction($ccAccount.GetAzSDKContinuousAssurance);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Remove-AzSDKContinuousAssurance
{
<#
.SYNOPSIS
This command would help in removing resources created by Continuous Assurance installation in your subscription
.DESCRIPTION
.PARAMETER SubscriptionId
Subscription id in which Automation Account exists
.PARAMETER DeleteStorageReports
Switch to specify whether security scan logs/reports stored in storage account also should be removed permanently.
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[Parameter(Mandatory = $true)]
[string]
$SubscriptionId ,
[Parameter(Mandatory = $false)]
[switch]
$DeleteStorageReports
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
try
{
$ccAccount = [CCAutomation]::new($SubscriptionId, $PSCmdlet.MyInvocation);
if ($ccAccount)
{
return $ccAccount.InvokeFunction($ccAccount.RemoveAzSDKContinuousAssurance,@($DeleteStorageReports));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SubscriptionSecurity/ARMPolicy.ps1
|
ARMPolicy.ps1
|
Set-StrictMode -Version Latest
function Set-AzSDKARMPolicies
{
<#
.SYNOPSIS
This command would help in setting up the AzSDK ARM Policies for a Subscription
.DESCRIPTION
This command would help in setting up the AzSDK ARM Policies for a Subscription
.LINK
https://aka.ms/azsdkdocs
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
# Adding all mandatory tags
$modifiedTags = [string]::Join(",", [ConfigurationManager]::GetAzSdkConfigData().SubscriptionMandatoryTags);
if(-not [string]::IsNullOrWhiteSpace($Tags))
{
$modifiedTags = $modifiedTags + "," +$Tags;
}
$armPolicy = [ARMPolicy]::new($SubscriptionId, $PSCmdlet.MyInvocation, $modifiedTags);
if ($armPolicy)
{
return $armPolicy.InvokeFunction($armPolicy.SetARMPolicy);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Remove-AzSDKARMPolicies
{
<#
.SYNOPSIS
This command would remove ARM policies which was set up by AzSDK
.DESCRIPTION
This command would remove ARM policies which was set up by AzSDK
.LINK
https://aka.ms/azsdkdocs
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $true, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
$armPolicy = [ARMPolicy]::new($SubscriptionId, $PSCmdlet.MyInvocation, $Tags);
if ($armPolicy)
{
return $armPolicy.InvokeFunction($armPolicy.RemoveARMPolicy);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SubscriptionSecurity/Alerts.ps1
|
Alerts.ps1
|
Set-StrictMode -Version Latest
function Set-AzSDKAlerts
{
<#
.SYNOPSIS
This command would help in setting up the Alert rules for the all the critical actions across different Azure Resources under a given Subscription
.DESCRIPTION
This command can be used to setup alert rules for critical resource actions.
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $true, HelpMessage = "Provide a security contact email address. Recommended a mail enabled Security Group with receiving of external emails option turned ON. Note: Only 1 email address will be accepted.")]
$SecurityContactEmails,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide the ResourceGroup on which the AlertPackage has to be configured")]
$TargetResourceGroup,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide the location for alert ResourceGroup")]
$AlertResourceGroupLocation = "East US",
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
# Adding all mandatory tags
$modifiedTags = [string]::Join(",", [ConfigurationManager]::GetAzSdkConfigData().SubscriptionMandatoryTags);
if(-not [string]::IsNullOrWhiteSpace($Tags))
{
$modifiedTags = $modifiedTags + "," +$Tags;
}
$alertObj = [Alerts]::new($SubscriptionId, $PSCmdlet.MyInvocation, $modifiedTags);
if ($alertObj)
{
return $alertObj.InvokeFunction($alertObj.SetAlerts, @($TargetResourceGroup, $SecurityContactEmails, $AlertResourceGroupLocation));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Remove-AzSDKAlerts
{
<#
.SYNOPSIS
This command removes all the alert rules being set up by AzSDK.
.DESCRIPTION
This command removes all the alert rules being set up by AzSDK.
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $true, ParameterSetName= "Tags", HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[Parameter(ParameterSetName= "Alert Names", Mandatory = $true, HelpMessage = "Provide the comma seperated values of alert names")]
[string]
$AlertNames,
[switch]
[Parameter(ParameterSetName= "Delete Resource Group", Mandatory = $true, HelpMessage = "Switch to specify whether to delete resource group containing all alerts or not")]
$DeleteResourceGroup,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
$alertObj = [Alerts]::new($SubscriptionId, $PSCmdlet.MyInvocation, $Tags);
if ($alertObj)
{
return $alertObj.InvokeFunction($alertObj.RemoveAlerts, @([bool] $DeleteResourceGroup, $AlertNames));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SubscriptionSecurity/SubscriptionSecurity.ps1
|
SubscriptionSecurity.ps1
|
Set-StrictMode -Version Latest
function Set-AzSDKSubscriptionSecurity
{
<#
.SYNOPSIS
This command would help in setting up the all the critical subscription security packages
.DESCRIPTION
This command would help in setting up the all the critical subscription security packages
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[string]
[Parameter(Mandatory = $true, HelpMessage = "Provide a security contact email address or addresses separated by a comma. Recommended a mail enabled Security Group with receiving of external emails option turned ON.")]
$SecurityContactEmails,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide a security contact international information phone number including the country code (for example, +1-425-1234567)")]
$SecurityPhoneNumber,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide the ResourceGroup on which the AlertPackage has to be configured")]
$TargetResourceGroup,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide the location for alert ResourceGroup")]
$AlertResourceGroupLocation = "East US",
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
# Adding all mandatory tags
$modifiedTags = [string]::Join(",", [ConfigurationManager]::GetAzSdkConfigData().SubscriptionMandatoryTags);
if(-not [string]::IsNullOrWhiteSpace($Tags))
{
$modifiedTags = $modifiedTags + "," +$Tags;
}
$subSec = [SubscriptionSecurity]::new($SubscriptionId, $PSCmdlet.MyInvocation, $modifiedTags);
if ($subSec)
{
return $subSec.InvokeFunction($subSec.SetSubscriptionSecurity, @($SecurityContactEmails, $SecurityPhoneNumber, $TargetResourceGroup, $AlertResourceGroupLocation));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Remove-AzSDKSubscriptionSecurity
{
<#
.SYNOPSIS
This command would help in cleaning up the AzSDK Subscription Security package for a Subscription
.DESCRIPTION
This command would help in cleaning up the AzSDK Subscription Security package for a Subscription
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $true, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to delete resource group containing all alerts or not")]
$DeleteResourceGroup,
[Parameter(Mandatory = $false, HelpMessage = "Provide the comma seperated values of alert names")]
[string]
$AlertNames,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
$subSec = [SubscriptionSecurity]::new($SubscriptionId, $PSCmdlet.MyInvocation, $Tags);
if ($subSec)
{
return $subSec.InvokeFunction($subSec.RemoveSubscriptionSecurity, @([bool] $DeleteResourceGroup, $AlertNames));
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SubscriptionSecurity/RBAC.ps1
|
RBAC.ps1
|
Set-StrictMode -Version Latest
function Set-AzSDKSubscriptionRBAC
{
<#
.SYNOPSIS
This command would help in setting up the RBAC rules for a given Subscription
.DESCRIPTION
This command would help in setting up the RBAC rules for a given Subscription
.LINK
https://aka.ms/azsdkdocs
#>
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
# Adding all mandatory tags
$modifiedTags = [string]::Join(",", [ConfigurationManager]::GetAzSdkConfigData().SubscriptionMandatoryTags);
if(-not [string]::IsNullOrWhiteSpace($Tags))
{
$modifiedTags = $modifiedTags + "," +$Tags;
}
$rbac = [RBAC]::new($SubscriptionId, $PSCmdlet.MyInvocation, $modifiedTags);
if ($rbac)
{
return $rbac.InvokeFunction($rbac.SetRBACAccounts);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
function Remove-AzSDKSubscriptionRBAC
{
<#
.SYNOPSIS
This command clears all RBAC Rules set up by AzSDK.
.DESCRIPTION
This command clears all RBAC Rules set up by AzSDK.
.LINK
https://aka.ms/azsdkdocs
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $true, HelpMessage = "Provide tag names for processing specific policies. Comma seperated values are supported.")]
$Tags,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
$rbac = [RBAC]::new($SubscriptionId, $PSCmdlet.MyInvocation, $Tags);
if ($rbac)
{
return $rbac.InvokeFunction($rbac.RemoveRBACAccounts);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SubscriptionSecurity/SecurityCenter.ps1
|
SecurityCenter.ps1
|
Set-StrictMode -Version Latest
function Set-AzSDKAzureSecurityCenterPolicies
{
<#
.SYNOPSIS
This command would help in setting up the Security Center policies for a Subscription
.DESCRIPTION
This command would help in setting up the Security Center policies for a Subscription
.LINK
https://aka.ms/azsdkdocs
#>
[OutputType([String])]
[CmdletBinding(SupportsShouldProcess = $true)]
Param
(
[string]
[Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")]
[ValidateNotNullOrEmpty()]
$SubscriptionId,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide a security contact email address or addresses separated by a comma. Recommended a mail enabled Security Group with receiving of external emails option turned ON.")]
$SecurityContactEmails,
[string]
[Parameter(Mandatory = $false, HelpMessage = "Provide a security contact international information phone number including the country code (for example, +1-425-1234567)")]
$SecurityPhoneNumber,
[switch]
[Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")]
$DoNotOpenOutputFolder
)
Begin
{
[ListenerHelper]::RegisterListeners();
}
Process
{
젨젨 try
{
$secCenter = [SecurityCenterStatus]::new($SubscriptionId, $PSCmdlet.MyInvocation);
if ($secCenter)
{
return $secCenter.SetPolicies($SecurityContactEmails, $SecurityPhoneNumber);
}
}
catch
{
[EventBase]::PublishGenericException($_);
}
}
End
{
[ListenerHelper]::UnregisterListeners();
}
}
|
PowerShellCorpus/PowerShellGallery/PoshPrivilege/0.3.0.0/Scripts/Remove-Privilege.ps1
|
Remove-Privilege.ps1
|
Function Remove-Privilege {
<#
.SYNOPSIS
Removes a specified privilege for a user or group
.DESCRIPTION
Removes a specified privilege for a user or group. This will remain until
re-added using Add-Privilege or a policy is refreshed.
.PARAMETER AccountName
The user or group which will have the privilege removed.
.PARAMETER Privilege
Specific privilege/s to remove from the local machine
.NOTES
Name: Remove-Privilege
Author: Boe Prox
Version History:
1.0 - Initial Version
.EXAMPLE
Remove-Privilege -AccountName Domain\SomeUser -Privilege SeBackupPrivilege
Description
-----------
Removes the SeBackupPrivilege privilege for Domain\SomeUser on the local machine
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(Mandatory=$True)]
[string]$AccountName,
[parameter(Mandatory=$True)]
[Privileges[]]$Privilege
)
#No point going through everything if just using -WhatIf
If ($PSCmdlet.ShouldProcess($AccountName,"Remove Privilege(s): $($Privilege -join ', ')")) {
#region SID Information
Write-Verbose "Gathering SID information"
$AccountSID = ([System.Security.Principal.NTAccount]$AccountName).Translate([System.Security.Principal.SecurityIdentifier])
$ByteBuffer = New-Object Byte[] -ArgumentList $AccountSID.BinaryLength
$AccountSID.GetBinaryForm($ByteBuffer,0)
$SIDPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($AccountSID.BinaryLength)
[System.Runtime.InteropServices.Marshal]::Copy(
$ByteBuffer,
0,
$SIDPtr,
$AccountSID.BinaryLength
)
#endregion SID Information
#region LsaOpenPolicy
$Computer = New-Object LSA_UNICODE_STRING
$Computer.Buffer = $env:COMPUTERNAME
$Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
$Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
$PolicyHandle = [intptr]::Zero
$ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
[uint32]$Access = [LSA_AccessPolicy]::POLICY_CREATE_ACCOUNT -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
Write-Verbose "Opening policy handle"
$NTStatus = [PoShPrivilege]::LsaOpenPolicy(
[ref]$Computer,
[ref]$ObjectAttributes,
$Access,
[ref]$PolicyHandle
)
#region winErrorCode
If ($NTStatus -ne 0) {
$Win32ErrorCode = [PoShPrivilege]::LsaNtStatusToWinError($return)
Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
BREAK
}
#endregion winErrorCode
#endregion LsaOpenPolicy
#region LsaAddAccountRights
ForEach ($Priv in $Privilege) {
$PrivilegeName = [privileges]::$Priv
$_UserRights = New-Object LSA_UNICODE_STRING
$_UserRights.Buffer = $Priv.ToString()
#SF edts: replaced the two below lines to fix the buffer size
$_UserRights.Length = ($_UserRights.Buffer.length * [System.Text.UnicodeEncoding]::CharSize)
$_UserRights.MaximumLength = ($_UserRights.Length + [System.Text.UnicodeEncoding]::CharSize)
$UserRights = New-Object LSA_UNICODE_STRING[] -ArgumentList 1
$UserRights[0] = $_UserRights
Write-Verbose "Removing Privilege: $($PrivilegeName.ToString())"
$NTStatus = [PoShPrivilege]::LsaRemoveAccountRights(
$PolicyHandle,
$SIDPtr,
$false, #SF edit: originally was true which would delete all privs and the account
$UserRights,
1
)
#region winErrorCode
If ($NTStatus -ne 0) {
$Win32ErrorCode = [PoShPrivilege]::LsaNtStatusToWinError($return)
Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
BREAK
}
}
#endregion winErrorCode
#endregion LsaAddAccountRights
#region Cleanup
#region Close Policy Handle
Write-Verbose "Closing policy handle"
[void][PoShPrivilege]::LsaClose($PolicyHandle)
#endregion Close Policy Handle
#region Clear Pointers
Write-Verbose "Clearing SID pointers"
[void][System.Runtime.InteropServices.Marshal]::FreeHGlobal($SIDPtr)
#endregion Clear Pointers
#endregion Cleanup
}
}
|
PowerShellCorpus/PowerShellGallery/PoshPrivilege/0.3.0.0/Scripts/Add-Privilege.ps1
|
Add-Privilege.ps1
|
Function Add-Privilege {
<#
.SYNOPSIS
Adds a specified privilege for a user or group
.DESCRIPTION
Adds a specified privilege for a user or group. This will remain until
removed using Remove-Privilege or a policy is refreshed.
.PARAMETER AccountName
The user or group which will have the privilege added for.
.PARAMETER Privilege
Specific privilege/s to add on the local machine
.NOTES
Name: Add-Privilege
Author: Boe Prox
Version History:
1.0 - Initial Version
.EXAMPLE
Add-Privilege -AccountName Domain\SomeUser -Privilege SeBackupPrivilege
Description
-----------
Adds the SeBackupPrivilege privilege for Domain\SomeUser
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter()]
[string]$AccountName = ("{0}\{1}" -f ($env:USERDOMAIN, $env:USERNAME)),
[parameter(Mandatory=$True)]
[Privileges[]]$Privilege
)
#No point going through everything if just using -WhatIf
If ($PSCmdlet.ShouldProcess($AccountName,"Add Privilege(s): $($Privilege -join ', ')")) {
#region ConvertSIDStringToSID
Write-Verbose "Gathering SID information"
$AccountSID = ([System.Security.Principal.NTAccount]$AccountName).Translate([System.Security.Principal.SecurityIdentifier])
$SID = [intptr]::Zero
[void][PoshPrivilege]::ConvertStringSidToSid($AccountSID, [ref]$SID)
#endregion ConvertSIDStringToSID
#region LsaOpenPolicy
$Computer = New-Object LSA_UNICODE_STRING
$Computer.Buffer = $env:COMPUTERNAME
$Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
$Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
$PolicyHandle = [intptr]::Zero
$ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
[uint32]$Access = [LSA_AccessPolicy]::POLICY_CREATE_ACCOUNT -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
Write-Verbose "Opening policy handle"
$NTStatus = [PoshPrivilege]::LsaOpenPolicy(
[ref]$Computer,
[ref]$ObjectAttributes,
$Access,
[ref]$PolicyHandle
)
#region winErrorCode
If ($NTStatus -ne 0) {
$Win32ErrorCode = [PoshPrivilege]::LsaNtStatusToWinError($return)
Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
BREAK
}
#endregion winErrorCode
#endregion LsaOpenPolicy
#region LsaAddAccountRights'
ForEach ($Priv in $Privilege) {
$PrivilegeName = [privileges]::$Priv
$_UserRights = New-Object LSA_UNICODE_STRING
$_UserRights.Buffer = $Priv.ToString()
$_UserRights.Length = ($_UserRights.Buffer.length * [System.Text.UnicodeEncoding]::CharSize)
$_UserRights.MaximumLength = ($_UserRights.Length + [System.Text.UnicodeEncoding]::CharSize)
$UserRights = New-Object LSA_UNICODE_STRING[] -ArgumentList 1
$UserRights[0] = $_UserRights
Write-Verbose "Adding Privilege: $($PrivilegeName.ToString())"
$NTStatus = [PoshPrivilege]::LsaAddAccountRights(
$PolicyHandle,
$SID,
$UserRights,
1
)
#region winErrorCode
If ($NTStatus -ne 0) {
$Win32ErrorCode = [PoshPrivilege]::LsaNtStatusToWinError($return)
Write-Warning $(New-Object System.ComponentModel.Win32Exception -ArgumentList $Win32ErrorCode)
BREAK
}
}
#endregion winErrorCode
#endregion LsaAddAccountRights
#region Cleanup
#region Close Policy Handle
[void][PoshPrivilege]::LsaClose($PolicyHandle)
#endregion Close Policy Handle
#region Clear Pointers
[void][System.Runtime.InteropServices.Marshal]::FreeHGlobal($SID)
#endregion Clear Pointers
#endregion Cleanup
}
}
|
PowerShellCorpus/PowerShellGallery/PoshPrivilege/0.3.0.0/Scripts/Enable-Privilege.ps1
|
Enable-Privilege.ps1
|
Function Enable-Privilege {
<#
.SYNOPSIS
Enables specific privilege or privileges on the current process.
.DESCRIPTION
Enables specific privilege or privileges on the current process.
.PARAMETER Privilege
Specific privilege/s to enable on the current process
.NOTES
Name: Enable-Privilege
Author: Boe Prox
Version History:
1.0 - Initial Version
.EXAMPLE
Enable-Privilege -Privilege SeBackupPrivilege
Description
-----------
Enables the SeBackupPrivilege on the existing process
.EXAMPLE
Enable-Privilege -Privilege SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege
Description
-----------
Enables the SeBackupPrivilege, SeRestorePrivilege and SeTakeOwnershipPrivilege on the existing process
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(Mandatory = $True)]
[Privileges[]]$Privilege
)
If ($PSCmdlet.ShouldProcess("Process ID: $PID", "Enable Privilege(s): $($Privilege -join ', ')")) {
#region Constants
$SE_PRIVILEGE_ENABLED = 0x00000002
$SE_PRIVILEGE_DISABLED = 0x00000000
$TOKEN_QUERY = 0x00000008
$TOKEN_ADJUST_PRIVILEGES = 0x00000020
#endregion Constants
$TokenPriv = New-Object TokPriv1Luid
$HandleToken = [intptr]::Zero
$TokenPriv.Count = 1
$TokenPriv.Attr = $SE_PRIVILEGE_ENABLED
#Open the process token
$Return = [PoshPrivilege]::OpenProcessToken(
[PoshPrivilege]::GetCurrentProcess(),
($TOKEN_QUERY -BOR $TOKEN_ADJUST_PRIVILEGES),
[ref]$HandleToken
)
If (-NOT $Return) {
Write-Warning "Unable to open process token! Aborting!"
Break
}
ForEach ($Priv in $Privilege) {
$PrivValue = $Null
$TokenPriv.Luid = 0
#Lookup privilege value
$Return = [PoshPrivilege]::LookupPrivilegeValue($Null, $Priv, [ref]$PrivValue)
If ($Return) {
$TokenPriv.Luid = $PrivValue
#Adjust the process privilege value
$return = [PoshPrivilege]::AdjustTokenPrivileges(
$HandleToken,
$False,
[ref]$TokenPriv,
[System.Runtime.InteropServices.Marshal]::SizeOf($TokenPriv),
[IntPtr]::Zero,
[IntPtr]::Zero
)
If (-NOT $Return) {
Write-Warning "Unable to enable privilege <$priv>! "
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PoshPrivilege/0.3.0.0/Scripts/Get-Privilege.ps1
|
Get-Privilege.ps1
|
Function Get-Privilege {
<#
.SYNOPSIS
Gets all privileges on a local or remote system.
.DESCRIPTION
Gets the currently applied privileges or current user privileges.
.PARAMETER Privilege
Specific privilege/s to view.
.PARAMETER Computername
View privileges on a remote system
.PARAMETER CurrentUser
View the currently applied privileges for the current user
.NOTES
Name: Get-Privilege
Author: Boe Prox
Version History:
1.0 - Initial Version
.EXAMPLE
Get-Privilege
Computername Privilege Accounts
------------ --------- --------
BOE-PC SeAssignPrimaryTokenPrivilege {IIS APPPOOL\.NET v4.5 Cl...
BOE-PC SeAuditPrivilege {IIS APPPOOL\.NET v4.5 Cl...
BOE-PC SeBackupPrivilege {BUILTIN\Backup Operators...
BOE-PC SeBatchLogonRight {BUILTIN\IIS_IUSRS, BUILT...
BOE-PC SeChangeNotifyPrivilege {Window Manager\Window Ma...
BOE-PC SeCreateGlobalPrivilege {NT AUTHORITY\SERVICE, BU...
BOE-PC SeCreatePagefilePrivilege {BUILTIN\Administrators}
BOE-PC SeCreatePermanentPrivilege {}
BOE-PC SeCreateSymbolicLinkPrivilege {BUILTIN\Administrators}
...
Description
-----------
Enables the SeBackupPrivilege on the existing process
.EXAMPLE
Get-Privilege -CurrentUser
Privilege Description Enabled
--------- ----------- -------
SeLockMemoryPrivilege Lock pages in memory False
SeIncreaseQuotaPrivilege Adjust memory quotas for a process False
SeTcbPrivilege Act as part of the operating system False
SeSecurityPrivilege Manage auditing and security log False
SeTakeOwnershipPrivilege Take ownership of files or other objects False
SeLoadDriverPrivilege Load and unload device drivers False
SeSystemProfilePrivilege Profile system performance False
SeSystemtimePrivilege Change the system time False
SeProfileSingleProcessPrivilege Profile single process False
SeIncreaseBasePriorityPrivilege Increase scheduling priority False
SeCreatePagefilePrivilege Create a pagefile False
SeBackupPrivilege Back up files and directories False
SeRestorePrivilege Restore files and directories False
SeShutdownPrivilege Shut down the system False
SeDebugPrivilege Debug programs True
SeSystemEnvironmentPrivilege Modify firmware environment values False
SeChangeNotifyPrivilege Bypass traverse checking True
SeRemoteShutdownPrivilege Force shutdown from a remote system False
SeUndockPrivilege Remove computer from docking station False
SeManageVolumePrivilege Perform volume maintenance tasks False
SeImpersonatePrivilege Impersonate a client after authentica... True
SeCreateGlobalPrivilege Create global objects True
SeIncreaseWorkingSetPrivilege Increase a process working set False
SeTimeZonePrivilege Change the time zone False
SeCreateSymbolicLinkPrivilege Create symbolic links False
Description
-----------
Displays currently applied privileges for current user.
.EXAMPLE
Get-Privilege -Privilege SeDebugPrivilege
Computername Privilege Accounts
------------ --------- --------
BOE-PC SeDebugPrivilege {}
Description
-----------
Shows all accounts/groups that have been given SeDebugPrivilege
.OutputType
PSPrivilege.Privilege
PSPrivilege.CurrentUserPrivilege
#>
#REQUIRES -Version 3.0
[OutputType('PSPrivilege.Privilege','PSPrivilege.CurrentUserPrivilege')]
[cmdletbinding(
DefaultParameterSetName = 'Default'
)]
Param (
[parameter(ParameterSetName='Default')]
[Privileges[]]$Privilege,
[parameter(ParameterSetName='Default')]
[string]$Computername = $Env:Computername ,
[parameter(ParameterSetName='CurrentUser')]
[switch]$CurrentUser
)
Switch ($PSCmdlet.ParameterSetName) {
'CurrentUser' {
$Process = Get-Process -Id $PID
$PROCESS_QUERY_INFORMATION = [ProcessAccessFlags]::QueryInformation
$TOKEN_ALL_ACCESS = [System.Security.Principal.TokenAccessLevels]::AllAccess
$hProcess = [PoShPrivilege]::OpenProcess(
$PROCESS_QUERY_INFORMATION,
$True,
$Process.Id
)
Write-Debug "ProcessHandle: $($hProcess)"
$hProcessToken = [intptr]::Zero
[void][PoShPrivilege]::OpenProcessToken(
$hProcess,
$TOKEN_ALL_ACCESS,
[ref]$hProcessToken
)
Write-Debug "ProcessToken: $($hProcessToken)"
[void][PoShPrivilege]::CloseHandle($hProcess)
[UInt32]$TokenPrivSize = 1000
[IntPtr]$TokenPrivPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
[uint32]$ReturnLength = 0
[void][PoShPrivilege]::GetTokenInformation(
$hProcessToken,
[TOKEN_INFORMATION_CLASS]::TokenPrivileges,
$TokenPrivPtr,
$TokenPrivSize,
[ref]$ReturnLength
)
$TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivPtr, [Type][TOKEN_PRIVILEGES])
[IntPtr]$PrivilegesBasePtr = [IntPtr](AddSignedIntAsUnsigned $TokenPrivPtr ([System.Runtime.InteropServices.Marshal]::OffsetOf(
[Type][TOKEN_PRIVILEGES], "Privileges"
)))
$LuidAndAttributeSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][LUID_AND_ATTRIBUTES])
for ($i=0; $i -lt $TokenPrivileges.PrivilegeCount; $i++) {
$LuidAndAttributePtr = [IntPtr](AddSignedIntAsUnsigned $PrivilegesBasePtr ($LuidAndAttributeSize * $i))
$LuidAndAttribute = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidAndAttributePtr, [Type][LUID_AND_ATTRIBUTES])
[UInt32]$PrivilegeNameSize = 60
$PrivilegeNamePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PrivilegeNameSize)
$PLuid = $LuidAndAttributePtr
[void][PoShPrivilege]::LookupPrivilegeNameW(
[IntPtr]::Zero,
$PLuid,
$PrivilegeNamePtr,
[Ref]$PrivilegeNameSize
)
$PrivilegeName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($PrivilegeNamePtr)
$Enabled = $False
If ($LuidAndAttribute.Attributes -ne 0) {
$Enabled = $True
}
$Object = [pscustomobject]@{
Computername = $env:COMPUTERNAME
Account = "{0}\{1}" -f ($env:USERDOMAIN, $env:USERNAME)
Privilege = $PrivilegeName
Description = GetPrivilegeDisplayName -Privilege $PrivilegeName
Enabled = $Enabled
}
$Object.pstypenames.insert(0,'PSPrivilege.CurrentUserPrivilege')
$Object
}
}
Default {
If (-NOT $PSBoundParameters.ContainsKey('Privilege')) {
$Privilege = [Privileges].GetEnumNames()
}
#region LsaOpenPolicy
$Computer = New-Object LSA_UNICODE_STRING
$Computer.Buffer = $Computername
$Computer.Length = ($Computer.buffer.length * [System.Text.UnicodeEncoding]::CharSize)
$Computer.MaximumLength = (($Computer.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
$PolicyHandle = [intptr]::Zero
$ObjectAttributes = New-Object LSA_OBJECT_ATTRIBUTES
[uint32]$Access = [LSA_AccessPolicy]::POLICY_VIEW_LOCAL_INFORMATION -BOR [LSA_AccessPolicy]::POLICY_LOOKUP_NAMES
Write-Verbose "Opening policy handle"
[void][PoShPrivilege]::LsaOpenPolicy(
[ref]$Computer,
[ref]$ObjectAttributes,
$Access,
[ref]$PolicyHandle
)
#endregion LsaOpenPolicy
#region LsaEnumerateAccountsWithUserRight
ForEach ($Priv in $Privilege) {
$UserRight = New-Object LSA_UNICODE_STRING
$UserRight.Buffer = $Priv.ToString()
$UserRight.Length = ($UserRight.Buffer.Length * [System.Text.UnicodeEncoding]::CharSize)
$UserRight.MaximumLength = (($UserRight.buffer.length+1) * [System.Text.UnicodeEncoding]::CharSize)
$EnumerationBuffer = [intptr]::Zero
[uint32]$Count = 0
Write-Verbose "Gathering enumerating accounts with user right"
$NTStatus = [PoShPrivilege]::LsaEnumerateAccountsWithUserRight(
$PolicyHandle,
$UserRight,
[ref]$EnumerationBuffer,
[ref]$Count
)
$Accounts = New-Object System.Collections.Arraylist
If ($NTStatus -eq 0) {
$LSAInfo = [intptr]::Zero
$StructSize = [System.Runtime.InteropServices.Marshal]::SizeOf([type][LSA_ENUMERATION_INFORMATION])
Write-Debug "StructSize: $($StructSize)"
Write-Verbose "Gathering privilege information"
For ($i=0; $i -lt $Count; $i++) {
Write-Debug "Iteration: $($i)"
$EnumerationItem = [intptr]($EnumerationBuffer.ToInt64() + ([long]$StructSize*[long]$i))
$Sid = [System.Runtime.InteropServices.Marshal]::PtrToStructure(
$EnumerationItem,
[type][LSA_ENUMERATION_INFORMATION]
)
[string]$SIDString = [string]::Empty
[void][PoShPrivilege]::ConvertSidToStringSid($Sid.sid, [ref]$SIDString)
Try {
$Account = ([system.security.principal.securityidentifier]$SIDString).Translate([System.Security.Principal.NTAccount]).Value
} Catch {
$Account = $SIDString
}
[void]$Accounts.Add($Account)
}
}
$Object = [pscustomobject]@{
Computername = $Computername
Privilege = $Priv.ToString()
Description = GetPrivilegeDisplayName -Privilege $Priv.ToString()
Accounts = $Accounts
}
$Object.pstypenames.insert(0,'PSPrivilege.Privilege')
$Object
}
#endregion LsaEnumerateAccountsWithUserRight
#region Close Policy Handle
Write-Verbose "Closing policy handle"
[void][PoShPrivilege]::LsaClose($PolicyHandle)
$PolicyHandle = [intptr]::Zero
#region Close Policy Handle
}
}
}
|
PowerShellCorpus/PowerShellGallery/PoshPrivilege/0.3.0.0/Scripts/Disable-Privilege.ps1
|
Disable-Privilege.ps1
|
Function Disable-Privilege {
<#
.SYNOPSIS
Disables specific privilege or privileges on the current process.
.DESCRIPTION
Disables specific privilege or privileges on the current process.
.PARAMETER Privilege
Specific privilege/s to enable on the current process
.NOTES
Name: Enable-Privilege
Author: Boe Prox
Version History:
1.0 - Initial Version
.EXAMPLE
Disable-Privilege -Privilege SeBackupPrivilege
Description
-----------
Disables the SeBackupPrivilege on the existing process
.EXAMPLE
Disable-Privilege -Privilege SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege
Description
-----------
Disables the SeBackupPrivilege, SeRestorePrivilege and SeTakeOwnershipPrivilege on the existing process
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(Mandatory = $True)]
[Privileges[]]$Privilege
)
If ($PSCmdlet.ShouldProcess("Process ID: $PID", "Disable Privilege(s): $($Privilege -join ', ')")) {
#region Constants
$SE_PRIVILEGE_ENABLED = 0x00000002
$SE_PRIVILEGE_DISABLED = 0x00000000
$TOKEN_QUERY = 0x00000008
$TOKEN_ADJUST_PRIVILEGES = 0x00000020
#endregion Constants
$TokenPriv = New-Object TokPriv1Luid
$HandleToken = [intptr]::Zero
$TokenPriv.Count = 1
$TokenPriv.Attr = $SE_PRIVILEGE_DISABLED
#Open the process token
$Return = [PoshPrivilege]::OpenProcessToken(
[PoshPrivilege]::GetCurrentProcess(),
($TOKEN_QUERY -BOR $TOKEN_ADJUST_PRIVILEGES),
[ref]$HandleToken
)
If (-NOT $Return) {
Write-Warning "Unable to open process token! Aborting!"
Break
}
ForEach ($Priv in $Privilege) {
$PrivValue = $Null
$TokenPriv.Luid = 0
#Lookup privilege value
$Return = [PoshPrivilege]::LookupPrivilegeValue($Null, $Priv, [ref]$PrivValue)
If ($Return) {
$TokenPriv.Luid = $PrivValue
#Adjust the process privilege value
$return = [PoshPrivilege]::AdjustTokenPrivileges(
$HandleToken,
$False,
[ref]$TokenPriv,
[System.Runtime.InteropServices.Marshal]::SizeOf($TokenPriv),
[IntPtr]::Zero,
[IntPtr]::Zero
)
If (-NOT $Return) {
Write-Warning "Unable to disable privilege <$priv>! "
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzureRM.Sql/3.1.0/SqlStartup.ps1
|
SqlStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
@{
# Sql aliases
"Get-AzureRmSqlDatabaseServerAuditingPolicy" = "Get-AzureRmSqlServerAuditingPolicy";
"Remove-AzureRmSqlDatabaseServerAuditing" = "Remove-AzureRmSqlServerAuditing";
"Set-AzureRmSqlDatabaseServerAuditingPolicy" = "Set-AzureRmSqlServerAuditingPolicy";
"Use-AzureRmSqlDatabaseServerAuditingPolicy" = "Use-AzureRmSqlServerAuditingPolicy";
}.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias"
# SIG # Begin signature block
# MIIkHgYJKoZIhvcNAQcCoIIkDzCCJAsCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC1Cb+d9hFpqiVW
# EzcV8SUmDXnMIbZUOih5VNUTdvSnJaCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR
# pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTYxMTE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oTFU1pY3Jvc29mdCBD
# b3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIw
# MTACEzMAAACxcRN533X2NcgAAAAAALEwFgQUY5PT1w9QOVVq1TeM6l6HuZQQSfAw
# DQYJKoZIhvcNAQELBQAEggEABuemOymH/AYT4vfyR1m67e6jwoxprXFHQl+ODT35
# cKFhdyj+g46jo/y7OB8UKuMk1HORkc9Bxs5vo1qyCsj73HmY+gh0NwBe6GNLZ7uO
# fX9yCPSK9YCs/831XGLd6xSMWK5eM8jdXvIZPWASH3O5r7XGdbVneQ49fVD21QCs
# kgKnRLxShgv0+yLv409prv7GpU3eGEOtFup7foMVQ7aLNBvEqji2ZgcIKA0UagP2
# UpkMGUFpMjCyzCx/B8HoLf1AbAaWn1Zh3b6B1YoAGAgUf/YVk0ucWn56EAshAD5A
# tav0noCSu1M7aLMhIcu6f9+54+Uhj7pkUBiyC8mloL0xAg==
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/AzureRM.Sql/3.1.0/ResourceManagerStartup.ps1
|
ResourceManagerStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
# Authorization script commandlet that builds on top of existing Insights comandlets.
# This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet
function Get-AzureRmAuthorizationChangeLog {
<#
.SYNOPSIS
Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators).
Maximum duration that can be queried is 15 days (going back up to past 90 days).
.DESCRIPTION
The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range.
The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days).
.PARAMETER StartTime
Start time of the query. Optional.
.PARAMETER EndTime
End time of the query. Optional
.EXAMPLE
Get-AzureRmAuthorizationChangeLog
Gets the access change logs for the past hour.
.EXAMPLE
Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00"
Gets all access change logs between the specified dates
Timestamp : 2015-09-23 21:52:41Z
Caller : admin@rbacCliTest.onmicrosoft.com
Action : Revoked
PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c
PrincipalName : testUser
PrincipalType : User
Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource
ScopeName : testresource
ScopeType : Resource
RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c
RoleName : Contributor
.EXAMPLE
Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType
Gets access change logs for the past 5 days and format the output
Caller Action RoleName PrincipalName ScopeType
------ ------ -------- ------------- ---------
admin@contoso.com Revoked Contributor User1 Subscription
admin@contoso.com Granted Reader User1 Resource Group
admin@contoso.com Revoked Contributor Group1 Resource
.LINK
New-AzureRmRoleAssignment
.LINK
Get-AzureRmRoleAssignment
.LINK
Remove-AzureRmRoleAssignment
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional
If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")]
[DateTime] $StartTime,
[parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional.
If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")]
[DateTime] $EndTime
)
PROCESS {
# Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet
$events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime
$startEvents = @{}
$endEvents = @{}
$offlineEvents = @()
# StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted.
# i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination
$startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" }
$events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ }
# This filters non-RBAC events like classic administrator write or delete
$events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ }
$output = @()
# Get all role definitions once from the service and cache to use for all 'startevents'
$azureRoleDefinitionCache = @{}
Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ }
$principalDetailsCache = @{}
# Process StartEvents
# Find matching EndEvents that succeeded and relating to role assignments only
$startEvents | ? { $endEvents.ContainsKey($_.OperationId) `
-and $endEvents[$_.OperationId] -ne $null `
-and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) `
-and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % {
$endEvent = $endEvents[$_.OperationId];
# Create the output structure
$out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName
$out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u
$out.Caller = $_.Caller
if ($_.HttpRequest.Method -ieq "PUT") {
$out.Action = "Granted"
if ($_.Properties.Content.ContainsKey("requestbody")) {
$messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"]
}
$out.Scope = $_.Authorization.Scope
}
elseif ($_.HttpRequest.Method -ieq "DELETE") {
$out.Action = "Revoked"
if ($endEvent.Properties.Content.ContainsKey("responseBody")) {
$messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"]
}
}
if ($messageBody) {
# Process principal details
$out.PrincipalId = $messageBody.properties.principalId
if ($out.PrincipalId -ne $null) {
# Get principal details by querying Graph. Cache principal details and read from cache if present
$principalId = $out.PrincipalId
if($principalDetailsCache.ContainsKey($principalId)) {
# Found in cache
$principalDetails = $principalDetailsCache[$principalId]
} else { # not in cache
$principalDetails = "" | select Name, Type
$user = Get-AzureRmADUser -ObjectId $principalId
if ($user) {
$principalDetails.Name = $user.DisplayName
$principalDetails.Type = "User"
} else {
$group = Get-AzureRmADGroup -ObjectId $principalId
if ($group) {
$principalDetails.Name = $group.DisplayName
$principalDetails.Type = "Group"
} else {
$servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId
if ($servicePrincipal) {
$principalDetails.Name = $servicePrincipal.DisplayName
$principalDetails.Type = "Service Principal"
}
}
}
# add principal details to cache
$principalDetailsCache.Add($principalId, $principalDetails);
}
$out.PrincipalName = $principalDetails.Name
$out.PrincipalType = $principalDetails.Type
}
# Process scope details
if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope }
if ($out.Scope -ne $null) {
# Remove the authorization provider details from the scope, if present
if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) {
$index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization")
$out.Scope = $out.Scope.Substring(0, $index)
}
$scope = $out.Scope
$resourceDetails = "" | select Name, Type
$scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries)
$len = $scopeParts.Length
if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) {
$resourceDetails.Type = "Subscription"
$resourceDetails.Name = $scopeParts[1]
} elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) {
$resourceDetails.Type = "Resource Group"
$resourceDetails.Name = $scopeParts[3]
} elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) {
$resourceDetails.Type = "Resource"
$resourceDetails.Name = $scopeParts[$len -1]
}
$out.ScopeName = $resourceDetails.Name
$out.ScopeType = $resourceDetails.Type
}
# Process Role definition details
$out.RoleDefinitionId = $messageBody.properties.roleDefinitionId
if ($out.RoleDefinitionId -ne $null) {
#Extract roleDefinitionId Guid value from the fully qualified id string.
$roleDefinitionIdGuid= $out.RoleDefinitionId.Substring($out.RoleDefinitionId.LastIndexOf("/")+1)
if ($azureRoleDefinitionCache[$roleDefinitionIdGuid]) {
$out.RoleName = $azureRoleDefinitionCache[$roleDefinitionIdGuid].Name
} else {
$out.RoleName = ""
}
}
}
$output += $out
} # start event processing complete
# Filter classic admins events
$offlineEvents | % {
if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) {
$out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName
$out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u
$out.Caller = "Subscription Admin"
if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){
$out.Action = "Granted"
}
elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){
$out.Action = "Revoked"
}
$out.RoleDefinitionId = $null
$out.PrincipalId = $null
$out.PrincipalType = "User"
$out.Scope = "/subscriptions/" + $_.SubscriptionId
$out.ScopeType = "Subscription"
$out.ScopeName = $_.SubscriptionId
if($_.Properties -ne $null){
$out.PrincipalName = $_.Properties.Content["adminEmail"]
$out.RoleName = "Classic " + $_.Properties.Content["adminType"]
}
$output += $out
}
} # end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qbVc0D5rs5Z8go1I
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/AzureRM.Sql/2.8.0/SqlStartup.ps1
|
SqlStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
@{
# Sql aliases
"Get-AzureRmSqlDatabaseServerAuditingPolicy" = "Get-AzureRmSqlServerAuditingPolicy";
"Remove-AzureRmSqlDatabaseServerAuditing" = "Remove-AzureRmSqlServerAuditing";
"Set-AzureRmSqlDatabaseServerAuditingPolicy" = "Set-AzureRmSqlServerAuditingPolicy";
"Use-AzureRmSqlDatabaseServerAuditingPolicy" = "Use-AzureRmSqlServerAuditingPolicy";
}.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias"
# SIG # Begin signature block
# MIIkFwYJKoZIhvcNAQcCoIIkCDCCJAQCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC1Cb+d9hFpqiVW
# EzcV8SUmDXnMIbZUOih5VNUTdvSnJaCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR
# pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29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QQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv
# bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0
# aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAxMAITMwAA
# ALRDOhz+trpSiQAAAAAAtDAWBBQFTh0ly8mTkwWSF0VPt41Rk5T5aTANBgkqhkiG
# 9w0BAQsFAASCAQDGDues6w+uUKwhzl8sEM6wY5g0jq9hYmagC6YZb+xyLz/hnZj7
# FeUwL9ynNPYOfjc6/oYekNPXy+ppDKU5x5mpfhCfgc4Y3SZ3CjO4MAQrYLzaGv4W
# REBRlGFougy51Gls+XO+CWnePPIZZFrfOGlfGVB1h9yPYMFhWB2ieLVYkTOAO2Yk
# ClWuaQ2N+BnXVdpLP8ObjDQsAjYR0aVMeqbw1D6zAZuZbvWD+wzr9NkB3PojUo5D
# OWN+XsitWhF7ruMUH5DdXgRu3u4cV8f1PRt5xGsxCBhuv2jQfJKBu1lWMhPUBt8d
# iXx/dmlW7tdueVFC6a5el1f5A0bARl4yeOQ/
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/AzureRM.Sql/2.8.0/ResourceManagerStartup.ps1
|
ResourceManagerStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
# Authorization script commandlet that builds on top of existing Insights comandlets.
# This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet
function Get-AzureRmAuthorizationChangeLog {
<#
.SYNOPSIS
Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators).
Maximum duration that can be queried is 15 days (going back up to past 90 days).
.DESCRIPTION
The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range.
The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days).
.PARAMETER StartTime
Start time of the query. Optional.
.PARAMETER EndTime
End time of the query. Optional
.EXAMPLE
Get-AzureRmAuthorizationChangeLog
Gets the access change logs for the past hour.
.EXAMPLE
Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00"
Gets all access change logs between the specified dates
Timestamp : 2015-09-23 21:52:41Z
Caller : admin@rbacCliTest.onmicrosoft.com
Action : Revoked
PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c
PrincipalName : testUser
PrincipalType : User
Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource
ScopeName : testresource
ScopeType : Resource
RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c
RoleName : Contributor
.EXAMPLE
Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType
Gets access change logs for the past 5 days and format the output
Caller Action RoleName PrincipalName ScopeType
------ ------ -------- ------------- ---------
admin@contoso.com Revoked Contributor User1 Subscription
admin@contoso.com Granted Reader User1 Resource Group
admin@contoso.com Revoked Contributor Group1 Resource
.LINK
New-AzureRmRoleAssignment
.LINK
Get-AzureRmRoleAssignment
.LINK
Remove-AzureRmRoleAssignment
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional
If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")]
[DateTime] $StartTime,
[parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional.
If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")]
[DateTime] $EndTime
)
PROCESS {
# Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet
$events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime
$startEvents = @{}
$endEvents = @{}
$offlineEvents = @()
# StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted.
# i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination
$startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" }
$events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ }
# This filters non-RBAC events like classic administrator write or delete
$events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ }
$output = @()
# Get all role definitions once from the service and cache to use for all 'startevents'
$azureRoleDefinitionCache = @{}
Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ }
$principalDetailsCache = @{}
# Process StartEvents
# Find matching EndEvents that succeeded and relating to role assignments only
$startEvents | ? { $endEvents.ContainsKey($_.OperationId) `
-and $endEvents[$_.OperationId] -ne $null `
-and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) `
-and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % {
$endEvent = $endEvents[$_.OperationId];
# Create the output structure
$out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName
$out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u
$out.Caller = $_.Caller
if ($_.HttpRequest.Method -ieq "PUT") {
$out.Action = "Granted"
if ($_.Properties.Content.ContainsKey("requestbody")) {
$messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"]
}
$out.Scope = $_.Authorization.Scope
}
elseif ($_.HttpRequest.Method -ieq "DELETE") {
$out.Action = "Revoked"
if ($endEvent.Properties.Content.ContainsKey("responseBody")) {
$messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"]
}
}
if ($messageBody) {
# Process principal details
$out.PrincipalId = $messageBody.properties.principalId
if ($out.PrincipalId -ne $null) {
# Get principal details by querying Graph. Cache principal details and read from cache if present
$principalId = $out.PrincipalId
if($principalDetailsCache.ContainsKey($principalId)) {
# Found in cache
$principalDetails = $principalDetailsCache[$principalId]
} else { # not in cache
$principalDetails = "" | select Name, Type
$user = Get-AzureRmADUser -ObjectId $principalId
if ($user) {
$principalDetails.Name = $user.DisplayName
$principalDetails.Type = "User"
} else {
$group = Get-AzureRmADGroup -ObjectId $principalId
if ($group) {
$principalDetails.Name = $group.DisplayName
$principalDetails.Type = "Group"
} else {
$servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId
if ($servicePrincipal) {
$principalDetails.Name = $servicePrincipal.DisplayName
$principalDetails.Type = "Service Principal"
}
}
}
# add principal details to cache
$principalDetailsCache.Add($principalId, $principalDetails);
}
$out.PrincipalName = $principalDetails.Name
$out.PrincipalType = $principalDetails.Type
}
# Process scope details
if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope }
if ($out.Scope -ne $null) {
# Remove the authorization provider details from the scope, if present
if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) {
$index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization")
$out.Scope = $out.Scope.Substring(0, $index)
}
$scope = $out.Scope
$resourceDetails = "" | select Name, Type
$scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries)
$len = $scopeParts.Length
if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) {
$resourceDetails.Type = "Subscription"
$resourceDetails.Name = $scopeParts[1]
} elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) {
$resourceDetails.Type = "Resource Group"
$resourceDetails.Name = $scopeParts[3]
} elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) {
$resourceDetails.Type = "Resource"
$resourceDetails.Name = $scopeParts[$len -1]
}
$out.ScopeName = $resourceDetails.Name
$out.ScopeType = $resourceDetails.Type
}
# Process Role definition details
$out.RoleDefinitionId = $messageBody.properties.roleDefinitionId
if ($out.RoleDefinitionId -ne $null) {
#Extract roleDefinitionId Guid value from the fully qualified id string.
$roleDefinitionIdGuid= $out.RoleDefinitionId.Substring($out.RoleDefinitionId.LastIndexOf("/")+1)
if ($azureRoleDefinitionCache[$roleDefinitionIdGuid]) {
$out.RoleName = $azureRoleDefinitionCache[$roleDefinitionIdGuid].Name
} else {
$out.RoleName = ""
}
}
}
$output += $out
} # start event processing complete
# Filter classic admins events
$offlineEvents | % {
if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) {
$out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName
$out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u
$out.Caller = "Subscription Admin"
if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){
$out.Action = "Granted"
}
elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){
$out.Action = "Revoked"
}
$out.RoleDefinitionId = $null
$out.PrincipalId = $null
$out.PrincipalType = "User"
$out.Scope = "/subscriptions/" + $_.SubscriptionId
$out.ScopeType = "Subscription"
$out.ScopeName = $_.SubscriptionId
if($_.Properties -ne $null){
$out.PrincipalName = $_.Properties.Content["adminEmail"]
$out.RoleName = "Classic " + $_.Properties.Content["adminType"]
}
$output += $out
}
} # end offline events
$output | Sort Timestamp
}
} # End commandlet
# SIG # Begin signature block
# MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCD1aIG6oFrw5Hw0
# KihOeY9wUbQ9YuZoQAqgPB6b76kKyqCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR
# pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL
# MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v
# bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UECxMETU9Q
# UjEeMBwGA1UEAxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkqhkiG9w0B
# AQEFAAOCAQ8AMIIBCgKCAQEA0IfUQit+ndnGetSiw+MVktJTnZUXyVI2+lS/qxCv
# 6cnnzCZTw8Jzv23WAOUA3OlqZzQw9hYXtAGllXyLuaQs5os7efYjDHmP81LfQAEc
# wsYDnetZz3Pp2HE5m/DOJVkt0slbCu9+1jIOXXQSBOyeBFOmawJn+E1Zi3fgKyHg
# 78CkRRL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xQwP2wjU2fRN+
# F2YDcYIbdTIUWL8i4VvOzeJJ8d8NEk4ew42McBBmZQAO++27Tx3oLt5/yc3xGN6N
# h2W60ihPazeXgToBvejE53wyJRqKKyRrE+EXsrN7gA==
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Misc/VHDResourceGenerator.ps1
|
VHDResourceGenerator.ps1
|
$name = New-DscResourceProperty -Name Name -Type String -Attribute Key -Description "Name of the VHD File"
$path = New-DscResourceProperty -Name Path -Type String -Attribute Key -Description "Folder where the VHD will be created"
$parentPath = New-DscResourceProperty -Name ParentPath -Type String -Attribute Write -Description "Parent VHD file path, for differencing disk"
$generation = New-DscResourceProperty -Name Generation -Type String -Attribute Write -ValidateSet "Vhd","Vhdx" -Description "Virtual disk format - Vhd or Vhdx"
$ensure = New-DscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet "Present","Absent" -Description "Should the VHD be created or deleted"
$MaximumSizeBytes = New-DscResourceProperty -Name MaximumSizeBytes -Type Uint32 -Attribute Write -Description "Maximum size of Vhd to be created"
$id = New-DscResourceProperty -Name ID -Type String -Attribute Read -Description "Virtual Disk Identifier"
$type = New-DscResourceProperty -Name Type -Type String -Attribute Read -Description "Type of Vhd - Dynamic, Fixed, Differencing"
$FileSizeBytes = New-DscResourceProperty -Name FileSizeBytes -Type Uint32 -Attribute Read -Description "Current size of the VHD"
$IsAttached = New-DscResourceProperty -Name IsAttached -Type Boolean -Attribute Read -Description "Is the VHD attached to a VM or not"
New-DscResource -Name MSFT_xVHD -Properties $name,$path,$parentPath,$generation,$ensure,$id,$type,$MaximumSizeBytes,$FileSizeBytes,$IsAttached -Path . -ClassVersion 1.0.0 -FriendlyName xVHD
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Misc/VMResourceGenerator.ps1
|
VMResourceGenerator.ps1
|
$name = New-xDscResourceProperty -Name Name -Type String -Attribute Key -Description "Name of the VM"
$vhdPath = New-xDscResourceProperty -Name VhdPath -Type String -Attribute Required -Description "VHD associated with the VM"
$switchName = New-xDscResourceProperty -Name SwitchName -Type String -Attribute Write -Description "Virtual switch associated with the VM"
$path = New-xDscResourceProperty -Name Path -Type String -Attribute Write -Description "Folder where the VM data will be stored"
$generation = New-xDscResourceProperty -Name Generation -Type String -Attribute Write -ValidateSet "Vhd","Vhdx" -Description "Associated Virtual disk format - Vhd or Vhdx"
$ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet "Present","Absent" -Description "Should the VM be created or deleted"
$startupMem = New-xDscResourceProperty -Name StartupMemory -Type Uint64 -Attribute Write -Description "Startup RAM for the VM."
$minMem = New-xDscResourceProperty -Name MinimumMemory -Type Uint64 -Attribute Write -Description "Minimum RAM for the VM. This enables dynamic memory."
$maxMem = New-xDscResourceProperty -Name MaximumMemory -Type Uint64 -Attribute Write -Description "Maximum RAM for the VM. This enable dynamic memory."
$macAddress = New-xDscResourceProperty -Name MACAddress -Type String -Attribute Write -Description "MAC address of the VM."
$waitForIP = New-xDscResourceProperty -Name WaitForIP -Type Boolean -Attribute Write -Description "Waits for VM to get valid IP address."
$state = New-xDscResourceProperty -Name State -Type String -Attribute Write -ValidateSet "Running","Paused","Off" -Description "State of the VM."
$notes = New-xDscResourceProperty -Name Notes -Type String -Attribute Write -Description "Notes about the VM."
$procCount = New-xDscResourceProperty -Name ProcessorCount -Type Uint32 -Attribute Write -Description "Processor count for the VM"
$restartIfNeeded = New-xDscResourceProperty -Name RestartIfNeeded -Type Boolean -Attribute Write -Description "If specified, shutsdown and restarts the VM if needed for resource change"
$id = New-xDscResourceProperty -Name ID -Type String -Attribute Read -Description "VM unique ID"
$status = New-xDscResourceProperty -Name Status -Type String -Attribute Read -Description "Status of the VM"
$CPUUsage = New-xDscResourceProperty -Name CPUUsage -Type Uint32 -Attribute Read -Description "CPU Usage of the VM"
$memAssigned = New-xDscResourceProperty -Name MemoryAssigned -Type Uint64 -Attribute Read -Description "Memory assigned to the VM"
$uptime = New-xDscResourceProperty -Name Uptime -Type String -Attribute Read -Description "Uptime of the VM"
$creationTime = New-xDscResourceProperty -Name CreationTime -Type DateTime -Attribute Read -Description "Creation time of the VM"
$hasDynamicMemory = New-xDscResourceProperty -Name HasDynamicMemory -Type Boolean -Attribute Read -Description "Does VM has dynamic memory enabled"
$networkAdapters = New-xDscResourceProperty -Name NetworkAdapters -Type String[] -Attribute Read -Description "Network adapters of the VM"
New-xDscResource -Name MSFT_xVMHyperV -Property @($name,$vhdPath,$switchName,$state,$path,$generation,$startupMem,$minMem,$maxMem,$macAddress,$procCount,$waitForIP,$restartIfNeeded,$ensure, $notes,$id,$status,$CPUUsage,$memAssigned,$uptime,$creationTime,$hasDynamicMemory,$networkAdapters) -Path . -ClassVersion 1.0.0 -FriendlyName xVMHyperV
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Misc/VMSwitchGenerator.ps1
|
VMSwitchGenerator.ps1
|
$name = New-DscResourceProperty -Name Name -Type String -Attribute Key -Description "Name of the VM Switch"
$type = New-DscResourceProperty -Name Type -Type String -Attribute Key -ValidateSet "Internal","Private" -Description "Type of switch"
$netAdapter = New-DscResourceProperty -Name NetAdapterName -Type String -Attribute Write -Description "Network adapter name for external switch type"
$allowManagementOS = New-DscResourceProperty -Name AllowManagementOS -Type Boolean -Attribute Write -Description "Specify is the VM host has access to the physical NIC"
$ensure = New-DscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet "Present","Absent" -Description "Whether switch should be present or absent"
$id = New-DscResourceProperty -Name Id -Type String -Attribute Read -Description "Unique ID for the switch"
$netDescription = New-DscResourceProperty -Name NetAdapterInterfaceDescription -Type String -Attribute Read -Description "Description of the network interface"
New-DscResource -Name MSFT_xVMSwitch -Path . -Properties $name,$type,$netAdapter,$allowManagementOS,$ensure,$id,$netDescription -ClassVersion 1.0.0.0 -FriendlyName xVMSwitch
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMNetworkAdapter_MultipleVMMACAddress.ps1
|
Sample_xVMNetworkAdapter_MultipleVMMACAddress.ps1
|
Configuration VMAdapter
{
Import-DscResource -ModuleName xHyper-V -Name xVMNetworkAdapter
Import-DscResource -ModuleName PSDesiredStateConfiguration
xVMNetworkAdapter MyVM01NIC {
Id = 'MyVM01-NIC'
Name = 'MyVM01-NIC'
SwitchName = 'SETSwitch'
MacAddress = '001523be0c'
VMName = 'MyVM01'
Ensure = 'Present'
}
xVMNetworkAdapter MyVM02NIC {
Id = 'MyVM02-NIC'
Name = 'MyVM02-NIC'
SwitchName = 'SETSwitch'
MacAddress = '001523be0d'
VMName = 'MyVM02'
Ensure = 'Present'
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVhdFileExamples.ps1
|
Sample_xVhdFileExamples.ps1
|
# sample values used for testing.
$vhdPath = "C:\test_vhds\RenameComputer.Vhd"
# sample text file that you want to copy in the VHD.
$sampletxt = "C:\sample.txt"
# This path is the relative path to mounted drive letter.
$sampleVhdDestinationPath = "xvhdFileExample\CopiedFile"
# A local folder that you want to copy in to the VHD.
$samplefolder = "c:\SampleFolder"
Configuration xVhdD_CopyFileOrFolder
{
Param(
[Parameter(Mandatory=$true, Position=0)]
[validatescript({Test-Path $_})]
$vhdPath,
[Parameter(Mandatory=$true)]
[validatescript({Test-Path $_})]
$itemToCopy,
[Parameter(Mandatory=$true)]
$relativeDestinationPath
)
Import-DscResource -moduleName xHyper-V
xVhdFile FileCopy
{
VhdPath = $vhdPath
FileDirectory = MSFT_xFileDirectory {
SourcePath = $itemToCopy
DestinationPath = $relativeDestinationPath
}
}
}
# Copy File/Folder example
xVhdD_CopyFileOrFolder -vhdPath $vhdPath -itemToCopy $sampletxt -relativeDestinationPath $sampleVhdDestinationPath
Start-DscConfiguration -ComputerName localhost -Path $pwd\xVhdD_CopyFileOrFolder\ -Wait -Verbose
xVhdD_CopyFileOrFolder -vhdPath $vhdPath -itemToCopy $samplefolder -relativeDestinationPath $sampleVhdDestinationPath
Start-DscConfiguration -ComputerName localhost -Path $pwd\xVhdD_CopyFileOrFolder\ -Wait -Verbose
Configuration RemoveFileOrFolderFromVHD
{
param(
[Parameter(Mandatory=$true, Position=0)]
[validatescript({Test-Path $_})]
$vhdPath,
[Parameter(Mandatory=$true)]
$relativeDestinationPath,
$Ensure = 'Absent'
)
Import-DscResource -moduleName xHyper-V
xVhdFile RemoveFile
{
VhdPath = $vhdPath
FileDirectory = MSFT_xFileDirectory {
DestinationPath = $relativeDestinationPath
Ensure = $Ensure
}
}
}
RemoveFileOrFolderFromVHD -vhdPath $vhdPath -relativeDestinationPath $sampleVhdDestinationPath
Start-DscConfiguration -ComputerName localhost -Path $pwd\RemoveFileOrFolderFromVHD\ -Wait -Verbose
Configuration ChangeAttribute
{
param(
[Parameter(Mandatory=$true, Position=0)]
[validatescript({Test-Path $_})]
$vhdPath,
[Parameter(Mandatory=$true)]
$relativeDestinationPath,
[ValidateSet ("Archive", "Hidden", "ReadOnly", "System" )] $attribute
)
Import-DscResource -moduleName xHyper-V
xVhdFile Change-Attribute
{
VhdPath = $vhdPath
FileDirectory = MSFT_xFileDirectory {
DestinationPath = $relativeDestinationPath
Attributes = $attribute
}
}
}
ChangeAttribute -vhdPath $vhdPath -relativeDestinationPath $sampleVhdDestinationPath -attribute 'ReadOnly'
Start-DscConfiguration -ComputerName localhost -Path $pwd\RemoveFileOrFolderFromVHD\ -Wait -Verbose
# End to end sample for x-Hyper-v
Configuration Sample_EndToEndXHyperV_RunningVM
{
param
(
[Parameter(Mandatory)]
$baseVhdPath,
[Parameter(Mandatory)]
$name,
[Parameter(Mandatory)]
[validatescript({Test-Path $_})]
$unattendedFilePathToCopy
)
Import-DscResource -module xHyper-V
# Create a switch to be used by the VM
xVMSwitch switch
{
Name = "Test-Switch"
Ensure = "Present"
Type = "Internal"
}
# Create new VHD file.
xVHD NewVHD1
{
Ensure = "Present"
Name = $name
Path = (Split-Path $baseVhdPath)
Generation = "vhd"
ParentPath = $baseVhdPath
}
# Customize VHD by copying a folders/files to the VHD before a VM can be created
# Example below shows copying unattended.xml before a VM can be created
xVhdFile CopyUnattendxml
{
VhdPath = $vhdPath
FileDirectory = MSFT_xFileDirectory {
SourcePath = $unattendedFilePathToCopy
DestinationPath = "unattended.xml"
}
}
# create the testVM out of the vhd.
xVMHyperV testvm
{
Name = "$($name)_vm"
SwitchName = "Test-Switch"
VhdPath = Join-path (Split-Path $baseVhdPath) "$name.vhd"
ProcessorCount = 2
MaximumMemory = 1GB
MinimumMemory = 512MB
RestartIfNeeded = "TRUE"
DependsOn = "[xVHD]NewVHD1","[xVMSwitch]switch","[xVhdFile]CopyUnattendxml"
State = "Running"
}
}
# Create a mof file.
Sample_EndToEndXHyperV_RunningVM -baseVhdPath "C:\test_vhds\testvhd.vhd" -name TestMachine -unattendedFilePathToCopy C:\temp\unattended.xml
# Run the configuration on localhost.
Start-DscConfiguration -Path $pwd\Sample_EndToEndXHyperV_RunningVM -ComputerName localhost -Verbose -Wait
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVHD_AdditionalPropertyVHD.ps1
|
Sample_xVHD_AdditionalPropertyVHD.ps1
|
configuration Sample_xVHD_AdditionalPropertyVHD
{
param
(
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[string]$ParentPath,
[Parameter(Mandatory)]
[string]$MaximumSizeBytes,
[ValidateSet("Vhd","Vhdx")]
[string]$Generation = "Vhd",
[ValidateSet("Present","Absent")]
[string]$Ensure = "Present"
)
Import-DscResource -Module xHyper-V
Node localhost
{
xVHD WrongVHD
{
Ensure = $Ensure
Name = $Name
Path = $Path
ParentPath = $ParentPath
MaximumSizeBytes = $MaximumSizeBytes
Generation = $Generation
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMNetworkAdapter_ManagementOS.ps1
|
Sample_xVMNetworkAdapter_ManagementOS.ps1
|
Configuration HostOSAdapter
{
Import-DscResource -ModuleName xHyper-V -Name xVMNetworkAdapter
Import-DscResource -ModuleName PSDesiredStateConfiguration
xVMNetworkAdapter HostOSAdapter {
Id = 'Management-NIC'
Name = 'Management-NIC'
SwitchName = 'SETSwitch'
VMName = 'ManagementOS'
Ensure = 'Present'
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMSwitch_Internal.ps1
|
Sample_xVMSwitch_Internal.ps1
|
configuration Sample_xVMSwitch_Internal
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$SwitchName
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with default settings
xVMSwitch InternalSwitch
{
Ensure = 'Present'
Name = $SwitchName
Type = 'Internal'
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMSwitch_External.ps1
|
Sample_xVMSwitch_External.ps1
|
configuration Sample_xVMSwitch_External
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$SwitchName,
[Parameter(Mandatory)]
[string]$NetAdapterName
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with default settings
xVMSwitch ExternalSwitch
{
Ensure = 'Present'
Name = $SwitchName
Type = 'External'
NetAdapterName = $NetAdapterName
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMNetworkAdapter_MultipleVM.ps1
|
Sample_xVMNetworkAdapter_MultipleVM.ps1
|
Configuration VMAdapter
{
Import-DscResource -ModuleName xHyper-V -Name xVMNetworkAdapter
Import-DscResource -ModuleName PSDesiredStateConfiguration
xVMNetworkAdapter MyVM01NIC {
Id = 'MyVM01-NIC'
Name = 'MyVM01-NIC'
SwitchName = 'SETSwitch'
VMName = 'MyVM01'
Ensure = 'Present'
}
xVMNetworkAdapter MyVM02NIC {
Id = 'MyVM02-NIC'
Name = 'NetAdapter'
SwitchName = 'SETSwitch'
VMName = 'MyVM02'
Ensure = 'Present'
}
xVMNetworkAdapter MyVM03NIC {
Id = 'MyVM03-NIC'
Name = 'NetAdapter'
SwitchName = 'SETSwitch'
VMName = 'MyVM03'
Ensure = 'Present'
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMHyperV_DynamicMemory.ps1
|
Sample_xVMHyperV_DynamicMemory.ps1
|
configuration Sample_xVMHyperV_DynamicMemory
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$VMName,
[Parameter(Mandatory)]
[string]$VhdPath,
[Parameter(Mandatory)]
[Uint64]$StartupMemory,
[Parameter(Mandatory)]
[Uint64]$MinimumMemory,
[Parameter(Mandatory)]
[Uint64]$MaximumMemory
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with dynamic memory
xVMHyperV NewVM
{
Ensure = 'Present'
Name = $VMName
VhdPath = $VhdPath
Generation = 2
StartupMemory = $StartupMemory
MinimumMemory = $MinimumMemory
MaximumMemory = $MaximumMemory
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMNetworkAdapter_MultipleManagementOS.ps1
|
Sample_xVMNetworkAdapter_MultipleManagementOS.ps1
|
Configuration HostOSAdapter
{
Import-DscResource -ModuleName xHyper-V -Name xVMNetworkAdapter
Import-DscResource -ModuleName PSDesiredStateConfiguration
xVMNetworkAdapter ManagementAdapter {
Id = 'Management-NIC'
Name = 'Management-NIC'
SwitchName = 'SETSwitch'
VMName = 'ManagementOS'
Ensure = 'Present'
}
xVMNetworkAdapter ClusterAdapter {
Id = 'Cluster-NIC'
Name = 'Cluster-NIC'
SwitchName = 'SETSwitch'
VMName = 'ManagementOS'
Ensure = 'Present'
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMHyperV_Simple.ps1
|
Sample_xVMHyperV_Simple.ps1
|
configuration Sample_xVMHyperV_Simple
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$VMName,
[Parameter(Mandatory)]
[string]$VhdPath
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with default settings
xVMHyperV NewVM
{
Ensure = 'Present'
Name = $VMName
VhdPath = $VhdPath
Generation = 2
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVHD_DiffVHD.ps1
|
Sample_xVHD_DiffVHD.ps1
|
configuration Sample_xVhd_DiffVhd
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[string]$ParentPath,
[ValidateSet("Vhd","Vhdx")]
[string]$Generation = "Vhd",
[ValidateSet("Present","Absent")]
[string]$Ensure = "Present"
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
xVhd DiffVhd
{
Ensure = $Ensure
Name = $Name
Path = $Path
ParentPath = $ParentPath
Generation = $Generation
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVHD_MissingPropertyVHD.ps1
|
Sample_xVHD_MissingPropertyVHD.ps1
|
configuration Sample_xVHD_MissingPropertyVHD
{
param
(
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[string]$Path,
[ValidateSet("Vhd","Vhdx")]
[string]$Generation = "Vhd",
[ValidateSet("Present","Absent")]
[string]$Ensure = "Present"
)
Import-DscResource -module xHyper-V
Node localhost
{
xVHD WrongVHD
{
Ensure = $Ensure
Name = $Name
Path = $Path
Generation = $Generation
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVHD_NewVHD.ps1
|
Sample_xVHD_NewVHD.ps1
|
configuration Sample_xVHD_NewVhd
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[Uint64]$MaximumSizeBytes,
[ValidateSet("Vhd","Vhdx")]
[string]$Generation = "Vhd",
[ValidateSet("Present","Absent")]
[string]$Ensure = "Present"
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
xVhd NewVhd
{
Ensure = $Ensure
Name = $Name
Path = $Path
Generation = $Generation
MaximumSizeBytes = $MaximumSizeBytes
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMHyperV_Complete.ps1
|
Sample_xVMHyperV_Complete.ps1
|
configuration Sample_xVMHyperV_Complete
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$VMName,
[Parameter(Mandatory)]
[string]$VhdPath,
[Parameter(Mandatory)]
[Uint64]$StartupMemory,
[Parameter(Mandatory)]
[Uint64]$MinimumMemory,
[Parameter(Mandatory)]
[Uint64]$MaximumMemory,
[Parameter(Mandatory)]
[String]$SwitchName,
[Parameter(Mandatory)]
[String]$Path,
[Parameter(Mandatory)]
[Uint32]$ProcessorCount,
[ValidateSet('Off','Paused','Running')]
[String]$State = 'Off',
[Switch]$WaitForIP
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with all the properties
xVMHyperV NewVM
{
Ensure = 'Present'
Name = $VMName
VhdPath = $VhdPath
SwitchName = $SwitchName
State = $State
Path = $Path
Generation = 2
StartupMemory = $StartupMemory
MinimumMemory = $MinimumMemory
MaximumMemory = $MaximumMemory
ProcessorCount = $ProcessorCount
MACAddress = $MACAddress
RestartIfNeeded = $true
WaitForIP = $WaitForIP
DependsOn = '[WindowsFeature]HyperV'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Examples/Sample_xVMHyperV_SimpleWithDVDDrive.ps1
|
Sample_xVMHyperV_SimpleWithDVDDrive.ps1
|
configuration Sample_xVMHyperV_SimpleWithDvdDrive
{
param
(
[string[]]$NodeName = 'localhost',
[Parameter(Mandatory)]
[string]$VMName,
[Parameter(Mandatory)]
[string]$VhdPath,
[string]$ISOPath
)
Import-DscResource -module xHyper-V
Node $NodeName
{
# Install HyperV feature, if not installed - Server SKU only
WindowsFeature HyperV
{
Ensure = 'Present'
Name = 'Hyper-V'
}
# Ensures a VM with default settings
xVMHyperV NewVM
{
Ensure = 'Present'
Name = $VMName
VhdPath = $VhdPath
Generation = $VhdPath.Split('.')[-1]
DependsOn = '[WindowsFeature]HyperV'
}
# Adds DVD Drive with ISO
xVMDvdDrive NewVMDvdDriveISO
{
Ensure = 'Present'
Name = $VMName
ControllerNumber = 0
ControllerLocation = 0
Path = $ISOPath
DependsOn = '[xVMHyperV]NewVM'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/MSFT_xVMNetworkAdapter/MSFT_xVMNetworkAdapter.Tests.ps1
|
MSFT_xVMNetworkAdapter.Tests.ps1
|
$Global:DSCModuleName = 'xHyper-V'
$Global:DSCResourceName = 'MSFT_xVMNetworkAdapter'
#region HEADER
if ( (-not (Test-Path -Path '.\DSCResource.Tests\')) -or `
(-not (Test-Path -Path '.\DSCResource.Tests\TestHelper.psm1')) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git')
}
else
{
& git @('-C',(Join-Path -Path (Get-Location) -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module .\DSCResource.Tests\TestHelper.psm1 -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
# Create the Mock Objects that will be used for running tests
$MockHostAdapter = [PSCustomObject] @{
Id = 'HostManagement1'
Name = 'Management'
SwitchName = 'HostSwitch'
VMName = 'ManagementOS'
}
$TestAdapter = [PSObject]@{
Id = $MockHostAdapter.Id
Name = $MockHostAdapter.Name
SwitchName = $MockHostAdapter.SwitchName
VMName = $MockHostAdapter.VMName
}
$MockAdapter = [PSObject]@{
Name = $TestAdapter.Name
SwitchName = $MockHostAdapter.SwitchName
IsManagementOs = $True
MacAddress = '14FEB5C6CE98'
}
Describe "$($Global:DSCResourceName)\Get-TargetResource" {
#Function placeholders
function Get-VMNetworkAdapter { }
function Set-VMNetworkAdapter { }
function Remove-VMNetworkAdapter { }
function Add-VMNetworkAdapter { }
Context 'NetAdapter does not exist' {
Mock Get-VMNetworkAdapter
It 'should return ensure as absent' {
$Result = Get-TargetResource `
@TestAdapter
$Result.Ensure | Should Be 'Absent'
}
It 'should call the expected mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
Context 'NetAdapter exists' {
Mock -CommandName Get-VMNetworkAdapter -MockWith {
$MockAdapter
}
It 'should return adapter properties' {
$Result = Get-TargetResource @TestAdapter
$Result.Ensure | Should Be 'Present'
$Result.Name | Should Be $TestAdapter.Name
$Result.SwitchName | Should Be $TestAdapter.SwitchName
$Result.VMName | Should Be 'ManagementOS'
$Result.Id | Should Be $TestAdapter.Id
}
It 'should call the expected mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
}
Describe "$($Global:DSCResourceName)\Set-TargetResource" {
#Function placeholders
function Get-VMNetworkAdapter { }
function Set-VMNetworkAdapter { }
function Remove-VMNetworkAdapter { }
function Add-VMNetworkAdapter { }
$newAdapter = [PSObject]@{
Id = 'UniqueString'
Name = $TestAdapter.Name
SwitchName = $TestAdapter.SwitchName
VMName = 'ManagementOS'
Ensure = 'Present'
}
Context 'Adapter does not exist but should' {
Mock Get-VMNetworkAdapter
Mock Add-VMNetworkAdapter
Mock Remove-VMNetworkAdapter
It 'should not throw error' {
{
Set-TargetResource @newAdapter
} | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
Assert-MockCalled -commandName Add-VMNetworkAdapter -Exactly 1
Assert-MockCalled -commandName Remove-VMNetworkAdapter -Exactly 0
}
}
Context 'Adapter exists but should not exist' {
Mock Get-VMNetworkAdapter
Mock Add-VMNetworkAdapter
Mock Remove-VMNetworkAdapter
It 'should not throw error' {
{
$updateAdapter = $newAdapter.Clone()
$updateAdapter.Ensure = 'Absent'
Set-TargetResource @updateAdapter
} | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
Assert-MockCalled -commandName Add-VMNetworkAdapter -Exactly 0
Assert-MockCalled -commandName Remove-VMNetworkAdapter -Exactly 1
}
}
}
Describe "$($Global:DSCResourceName)\Test-TargetResource" {
#Function placeholders
function Get-VMNetworkAdapter { }
function Set-VMNetworkAdapter { }
function Remove-VMNetworkAdapter { }
function Add-VMNetworkAdapter { }
$newAdapter = [PSObject]@{
Id = 'UniqueString'
Name = $TestAdapter.Name
SwitchName = $TestAdapter.SwitchName
VMName = 'ManagementOS'
Ensure = 'Present'
}
Context 'Adapter does not exist but should' {
Mock Get-VMNetworkAdapter
It 'should return false' {
Test-TargetResource @newAdapter | Should be $false
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
Context 'Adapter exists but should not exist' {
Mock Get-VMNetworkAdapter -MockWith { $MockAdapter }
It 'should return $false' {
$updateAdapter = $newAdapter.Clone()
$updateAdapter.Ensure = 'Absent'
Test-TargetResource @updateAdapter | Should Be $false
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
Context 'Adapter exists and no action needed' {
Mock Get-VMNetworkAdapter -MockWith { $MockAdapter }
It 'should return true' {
$updateAdapter = $newAdapter.Clone()
Test-TargetResource @updateAdapter | Should Be $true
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
Context 'Adapter does not exist and no action needed' {
Mock Get-VMNetworkAdapter
It 'should return true' {
$updateAdapter = $newAdapter.Clone()
$updateAdapter.Ensure = 'Absent'
Test-TargetResource @updateAdapter | Should Be $true
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-VMNetworkAdapter -Exactly 1
}
}
}
}
#endregion
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Unit/HyperVCommon.tests.ps1
|
HyperVCommon.tests.ps1
|
$script:DSCModuleName = 'xHyper-V'
$script:DSCResourceName = 'HyperVCommon'
#region HEADER
# Unit Test Template Version: 1.1.0
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-TestType Unit
#endregion HEADER
# Begin Testing
try
{
#region Pester Tests
$LocalizedData = InModuleScope $script:DSCResourceName {
$LocalizedData
}
function Get-InvalidOperationError
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorId,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorMessage
)
$exception = New-Object -TypeName System.InvalidOperationException `
-ArgumentList $ErrorMessage
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation
$errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord `
-ArgumentList $exception, $ErrorId, $errorCategory, $null
return $errorRecord
} # end function Get-InvalidOperationError
function Get-InvalidArgumentError
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorId,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorMessage
)
$exception = New-Object -TypeName System.ArgumentException `
-ArgumentList $ErrorMessage
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument
$errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord `
-ArgumentList $exception, $ErrorId, $errorCategory, $null
return $errorRecord
} # end function Get-InvalidArgumentError
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Unit/MSFT_xVMHyperV.Tests.ps1
|
MSFT_xVMHyperV.Tests.ps1
|
[CmdletBinding()]
param()
if (!$PSScriptRoot) # $PSScriptRoot is not defined in 2.0
{
$PSScriptRoot = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
}
$ErrorActionPreference = 'stop'
Set-StrictMode -Version latest
$RepoRoot = (Resolve-Path $PSScriptRoot\..\..).Path
$ModuleName = 'MSFT_xVMHyperV'
Import-Module (Join-Path $RepoRoot "DSCResources\$ModuleName\$ModuleName.psm1") -Force;
Describe 'xVMHyper-V' {
InModuleScope $ModuleName {
## Create empty functions to be able to mock the missing Hyper-V cmdlets
## CmdletBinding required on Get-VM to support $ErrorActionPreference
function Get-VM { [CmdletBinding()] param( [Parameter(ValueFromRemainingArguments)] $Name) }
## Generation parameter is required for the mocking -ParameterFilter to work
function New-VM { param ( $Generation) }
function Set-VM { }
function Stop-VM { }
function Remove-VM { }
function Get-VMNetworkAdapter { }
function Set-VMNetworkAdapter { }
function Add-VMNetworkAdapter { }
function Connect-VMNetworkAdapter { param ( $SwitchName ) }
function Get-VMFirmware { }
function Set-VMFirmware { }
function Get-VMIntegrationService { param ([Parameter(ValueFromPipeline)] $VM, $Name)}
function Enable-VMIntegrationService { param ([Parameter(ValueFromPipeline)] $VM, $Name)}
function Disable-VMIntegrationService { param ([Parameter(ValueFromPipeline)] $VM, $name)}
function Get-VHD { param ( $Path ) }
$stubVhdxDisk = New-Item -Path 'TestDrive:\TestVM.vhdx' -ItemType File;
$studVhdxDiskSnapshot = New-Item -Path "TestDrive:\TestVM_D0145678-1576-4435-AB18-9F000C1C17D0.avhdx" -ItemType File;
$stubVhdDisk = New-Item -Path 'TestDrive:\TestVM.vhd' -ItemType File;
$StubVMConfig = New-Item -Path 'TestDrive:\TestVM.xml' -ItemType File;
$stubNIC1 = @{ SwitchName = 'Test Switch 1'; MacAddress = 'AA-BB-CC-DD-EE-FF'; IpAddresses = @('192.168.0.1','10.0.0.1'); };
$stubNIC2 = @{ SwitchName = 'Test Switch 2'; MacAddress = 'AA-BB-CC-DD-EE-FE'; IpAddresses = @('192.168.1.1'); };
$stubVM = @{
HardDrives = @(
@{ Path = $stubVhdxDisk.FullName; }
@{ Path = $stubVhdDisk.FullName; }
);
#State = 'Running';
Path = $StubVMConfig.FullPath;
Generation = 1;
SecureBoot = $true;
MemoryStartup = 512MB;
MinimumMemory = 128MB;
MaximumMemory = 4096MB;
ProcessorCount = 1;
ID = [System.Guid]::NewGuid().ToString();
CPUUsage = 10;
MemoryAssigned = 512MB;
Uptime = New-TimeSpan -Hours 12;
CreationTime = (Get-Date).AddHours(-12);
DynamicMemoryEnabled = $true;
NetworkAdapters = @($stubNIC1,$stubNIC2);
Notes = '';
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'RunningVM' } -MockWith {
$runningVM = $stubVM.Clone();
$runningVM['State'] = 'Running';
return [PSCustomObject] $runningVM;
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'StoppedVM' } -MockWith {
$stoppedVM = $stubVM.Clone();
$stoppedVM['State'] = 'Off';
return [PSCustomObject] $stoppedVM;
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'PausedVM' } -MockWith {
$pausedVM = $stubVM.Clone();
$pausedVM['State'] = 'Paused';
return [PSCustomObject] $pausedVM;
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'NonexistentVM' } -MockWith {
Write-Error 'VM not found.';
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'DuplicateVM' } -MockWith {
return @([PSCustomObject] $stubVM, [PSCustomObject] $stubVM);
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'Generation1Vhd' } -MockWith {
$vhdVM = $stubVM.Clone();
$vhdVM['HardDrives'] = @( @{ Path = $stubVhdDisk.FullName } );
return [PSCustomObject] $vhdVM;
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'Generation2VM' } -MockWith {
$gen2VM = $stubVM.Clone();
$gen2VM['Generation'] = 2;
return [PSCustomObject] $gen2VM;
}
Mock -CommandName Get-VMIntegrationService -MockWith {return [pscustomobject]@{Enabled=$false}}
Mock -CommandName Get-Module -ParameterFilter { ($Name -eq 'Hyper-V') -and ($ListAvailable -eq $true) } -MockWith { return $true; }
Mock -CommandName Get-VhdHierarchy -ParameterFilter { $VhdPath.EndsWith('.vhd') } -MockWith {
## Return single Vhd chain for .vhds
return @($stubVhdDisk.FullName);
}
Mock -CommandName Get-VhdHierarchy -ParameterFilter { $VhdPath.EndsWith('.vhdx') } -MockWith {
## Return snapshot hierarchy for .vhdxs
return @($stubVhdxDiskSnapshot.FullName, $stubVhdxDisk.FullName);
}
Context 'Validates Get-TargetResource Method' {
It 'Returns a hashtable' {
$targetResource = Get-TargetResource -Name 'RunningVM' -VhdPath $stubVhdxDisk.FullName;
$targetResource -is [System.Collections.Hashtable] | Should Be $true;
}
It 'Throws when multiple VMs are present' {
{ Get-TargetResource -Name 'DuplicateVM' -VhdPath $stubVhdxDisk.FullName } | Should Throw;
}
It 'Does not call Get-VMFirmware if a generation 1 VM' {
Mock -CommandName Get-VMFirmware -MockWith { throw; }
$targetResource = Get-TargetResource -Name 'RunningVM' -VhdPath $stubVhdxDisk.FullName;
Assert-MockCalled -CommandName Get-VMFirmware -Scope It -Exactly 0;
}
It 'Calls Get-VMFirmware if a generation 2 VM' {
Mock -CommandName Get-VMFirmware -MockWith { return $true; }
$targetResource = Get-TargetResource -Name 'Generation2VM' -VhdPath $stubVhdxDisk.FullName;
Assert-MockCalled -CommandName Get-VMFirmware -Scope It -Exactly 1;
}
It 'Hash table contains key EnableGuestService' {
$targetResource = Get-TargetResource -Name 'RunningVM' -VhdPath $stubVhdxDisk.FullName;
$targetResource.ContainsKey('EnableGuestService') | Should Be $true;
}
} #end context Validates Get-TargetResource Method
Context 'Validates Test-TargetResource Method' {
$testParams = @{
VhdPath = $stubVhdxDisk.FullName;
}
It 'Returns a boolean' {
$targetResource = Test-TargetResource -Name 'RunningVM' @testParams;
$targetResource -is [System.Boolean] | Should Be $true;
}
It 'Returns $true when VM is present and "Ensure" = "Present"' {
Test-TargetResource -Name 'RunningVM' @testParams | Should Be $true;
}
It 'Returns $false when VM is not present and "Ensure" = "Present"' {
Test-TargetResource -Name 'NonexistentVM' @testParams | Should Be $false;
}
It 'Returns $true when VM is not present and "Ensure" = "Absent"' {
Test-TargetResource -Name 'NonexistentVM' -Ensure Absent @testParams | Should Be $true;
}
It 'Returns $false when VM is present and "Ensure" = "Absent"' {
Test-TargetResource -Name 'RunningVM' -Ensure Absent @testParams | Should Be $false;
}
It 'Returns $true when VM is in the "Running" state and no state is explicitly specified' {
Test-TargetResource -Name 'RunningVM' @testParams | Should Be $true;
}
It 'Returns $true when VM is in the "Stopped" state and no state is explicitly specified' {
Test-TargetResource -Name 'StoppedVM' @testParams | Should Be $true;
}
It 'Returns $true when VM is in the "Paused" state and no state is explicitly specified' {
Test-TargetResource -Name 'PausedVM' @testParams | Should Be $true;
}
It 'Returns $true when VM is in the "Running" state and requested "State" = "Running"' {
Test-TargetResource -Name 'RunningVM' @testParams | Should Be $true;
}
It 'Returns $true when VM is in the "Off" state and requested "State" = "Off"' {
Test-TargetResource -Name 'StoppedVM' -State Off @testParams | Should Be $true;
}
It 'Returns $true when VM is in the "Paused" state and requested "State" = Paused"' {
Test-TargetResource -Name 'PausedVM' -State Paused @testParams | Should Be $true;
}
It 'Returns $false when VM is in the "Running" state and requested "State" = "Off"' {
Test-TargetResource -Name 'RunningVM' -State Off @testParams | Should Be $false;
}
It 'Returns $false when VM is in the "Off" state and requested "State" = "Runnning"' {
Test-TargetResource -Name 'StoppedVM' -State Running @testParams | Should Be $false;
}
It 'Returns $true when VM .vhd file is specified with a generation 1 VM' {
Test-TargetResource -Name 'Generation1Vhd' -VhdPath $stubVhdDisk -Generation 1 -Verbose | Should Be $true;
}
It 'Returns $true when VM .vhdx file is specified with a generation 1 VM' {
Test-TargetResource -Name 'StoppedVM' -VhdPath $stubVhdxDisk -Generation 1 | Should Be $true;
}
It 'Returns $true when VM .vhdx file is specified with a generation 2 VM' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Test-TargetResource -Name 'Generation2VM' -Generation 2 @testParams | Should Be $true;
}
It 'Throws when a VM .vhd file is specified with a generation 2 VM' {
{ Test-TargetResource -Name 'Gen2VM' -VhdPath $stubVhdDisk -Generation 2 } | Should Throw;
}
It 'Returns $true when multiple NICs are assigned in the correct order' {
Test-TargetResource -Name 'RunningVM' @testParams -SwitchName @($stubNIC1.SwitchName,$stubNIC2.SwitchName) | Should Be $true;
}
It 'Returns $false when multiple NICs are not assigned/assigned in the wrong order' {
Test-TargetResource -Name 'RunningVM' @testParams -SwitchName @($stubNIC2.SwitchName,$stubNIC1.SwitchName) | Should Be $false;
}
It 'Returns $true when multiple MAC addresses are assigned in the correct order' {
Test-TargetResource -Name 'RunningVM' @testParams -MACAddress @($stubNIC1.MACAddress,$stubNIC2.MACAddress) | Should Be $true;
}
It 'Returns $false when multiple MAC addresses not assigned/assigned in the wrong order' {
Test-TargetResource -Name 'RunningVM' @testParams -MACAddress @($stubNIC1.MACAddress,$stubNIC2.MACAddress) | Should Be $true;
}
It 'Returns $true regardless of "SecureBoot" setting on a generation 1 VM' {
Test-TargetResource -Name 'RunningVM' -SecureBoot $true @testParams | Should Be $true;
Test-TargetResource -Name 'RunningVM' -SecureBoot $false @testParams | Should Be $true;
}
It 'Returns $true when SecureBoot is On and requested "SecureBoot" = "$true"' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Test-TargetResource -Name 'Generation2VM' -Generation 2 @testParams | Should Be $true;
}
It 'Returns $false when SecureBoot is On and requested "SecureBoot" = "$false"' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Test-TargetResource -Name 'Generation2VM' -SecureBoot $false -Generation 2 @testParams | Should be $false;
}
It 'Returns $true when VM has snapshot chain' {
Mock -CommandName Get-VhdHierarchy -MockWith { Write-Host $VhdPath; return @($studVhdxDiskSnapshot, $stubVhdxDisk); }
Test-TargetResource -Name 'Generation2VM' -VhdPath $stubVhdxDisk -Verbose | Should Be $true;
}
It 'Returns $false when EnableGuestService is off and requested "EnableGuestService" = "$true"' {
Test-TargetResource -Name 'RunningVM' -EnableGuestService $true @testParams | Should be $false;
}
It 'Returns $true when EnableGuestService is off and "EnableGuestService" is not requested"' {
Test-TargetResource -Name 'RunningVM' @testParams | Should be $true;
}
It 'Returns $true when EnableGuestService is on and requested "EnableGuestService" = "$true"' {
Mock -CommandName Get-VMIntegrationService -MockWith {return [pscustomobject]@{Enabled=$true}}
Test-TargetResource -Name 'RunningVM' -EnableGuestService $true @testParams | Should be $true;
}
It 'Throws when Hyper-V Tools are not installed' {
## This test needs to be the last in the Context otherwise all subsequent Get-Module checks will fail
Mock -CommandName Get-Module -ParameterFilter { ($Name -eq 'Hyper-V') -and ($ListAvailable -eq $true) } -MockWith { }
{ Test-TargetResource -Name 'RunningVM' @testParams } | Should Throw;
}
} #end context Validates Test-TargetResource Method
Context 'Validates Set-TargetResource Method' {
$testParams = @{
VhdPath = $stubVhdxDisk.FullName;
}
Mock -CommandName Get-VM -ParameterFilter { $Name -eq 'NewVM' } -MockWith { }
Mock -CommandName New-VM -MockWith {
$newVM = $stubVM.Clone();
$newVM['State'] = 'Off';
$newVM['Generation'] = $Generation;
return $newVM;
}
Mock -CommandName Set-VM -MockWith { return $true; }
Mock -CommandName Stop-VM -MockWith { return $true; } # requires output to be able to pipe something into Remove-VM
Mock -CommandName Remove-VM -MockWith { return $true; }
Mock -CommandName Set-VMNetworkAdapter -MockWith { return $true; }
Mock -CommandName Get-VMNetworkAdapter -MockWith { return $stubVM.NetworkAdapters.IpAddresses; }
Mock -CommandName Set-VMState -MockWith { return $true; }
It 'Removes an existing VM when "Ensure" = "Absent"' {
Set-TargetResource -Name 'RunningVM' -Ensure Absent @testParams;
Assert-MockCalled -CommandName Remove-VM -Scope It;
}
It 'Creates and does not start a VM that does not exist when "Ensure" = "Present"' {
Set-TargetResource -Name 'NewVM' @testParams;
Assert-MockCalled -CommandName New-VM -Exactly -Times 1 -Scope It;
Assert-MockCalled -CommandName Set-VM -Exactly -Times 1 -Scope It;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 0 -Scope It;
}
It 'Creates and starts a VM that does not exist when "Ensure" = "Present" and "State" = "Running"' {
Set-TargetResource -Name 'NewVM' -State Running @testParams;
Assert-MockCalled -CommandName New-VM -Exactly -Times 1 -Scope It;
Assert-MockCalled -CommandName Set-VM -Exactly -Times 1 -Scope It;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 1 -Scope It;
}
It 'Does not change VM state when VM "State" = "Running" and requested "State" = "Running"' {
Set-TargetResource -Name 'RunningVM' -State Running @testParams;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 0 -Scope It;
}
It 'Does not change VM state when VM "State" = "Off" and requested "State" = "Off"' {
Set-TargetResource -Name 'StoppedVM' -State Off @testParams;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 0 -Scope It;
}
It 'Changes VM state when existing VM "State" = "Off" and requested "State" = "Running"' {
Set-TargetResource -Name 'StoppedVM' -State Running @testParams;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 1 -Scope It;
}
It 'Changes VM state when existing VM "State" = "Running" and requested "State" = "Off"' {
Set-TargetResource -Name 'RunningVM' -State Off @testParams;
Assert-MockCalled -CommandName Set-VMState -Exactly -Times 1 -Scope It;
}
It 'Creates a generation 1 VM by default/when not explicitly specified' {
Set-TargetResource -Name 'NewVM' @testParams;
Assert-MockCalled -CommandName New-VM -ParameterFilter { $Generation -eq 1 } -Scope It;
}
It 'Creates a generation 1 VM when explicitly specified' {
Set-TargetResource -Name 'NewVM' -Generation 1 @testParams;
Assert-MockCalled -CommandName New-VM -ParameterFilter { $Generation -eq 1 } -Scope It;
}
It 'Creates a generation 2 VM when explicitly specified' {
Set-TargetResource -Name 'NewVM' -Generation 2 @testParams;
Assert-MockCalled -CommandName New-VM -ParameterFilter { $Generation -eq 2 } -Scope It;
}
It 'Calls "Add-VMNetworkAdapter" for each NIC when creating a new VM' {
Mock -CommandName Add-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'NewVM' @testParams -SwitchName 'Switch1','Switch2';
## The first NIC is assigned during the VM creation
Assert-MockCalled -CommandName Add-VMNetworkAdapter -Exactly 1 -Scope It;
}
It 'Calls "Connect-VMNetworkAdapter" for each existing NIC when updating an existing VM' {
Mock -CommandName Connect-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams -SwitchName 'Switch1','Switch2';
## The first NIC is assigned during the VM creation
Assert-MockCalled -CommandName Connect-VMNetworkAdapter -Exactly 2 -Scope It;
}
It 'Calls "Add-VMNetworkAdapter" for each missing NIC when updating an existing VM' {
Mock -CommandName Connect-VMNetworkAdapter -MockWith { }
Mock -CommandName Add-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams -SwitchName 'Switch1','Switch2','Switch3';
## The first NIC is assigned during the VM creation
Assert-MockCalled -CommandName Connect-VMNetworkAdapter -Exactly 2 -Scope It;
Assert-MockCalled -CommandName Add-VMNetworkAdapter -Exactly 1 -Scope It;
}
It 'Does not change switch assignments if no switch assignments are specified' {
Mock -CommandName Connect-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams;
Assert-MockCalled -CommandName Connect-VMNetworkAdapter -Exactly 0 -Scope It;
}
It 'Does not change NIC assignments if the switch assisgnments are correct' {
Mock -CommandName Set-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams -SwitchName $stubNIC1.SwitchName,$stubNIC2.SwitchName;
Assert-MockCalled -CommandName Set-VMNetworkAdapter -Exactly 0 -Scope It;
}
It 'Errors when updating MAC addresses on a running VM and "RestartIfNeeded" = "$false"' {
{ Set-TargetResource -Name 'RunningVM' @testParams -MACAddress 'AABBCCDDEEFE','AABBCCDDEEFF' -ErrorAction Stop } | Should Throw;
}
It 'Does not change MAC addresses if no MAC addresses assignments are specified' {
Mock -CommandName Set-VMNetworkAdapter -ParameterFilter { $StaticMacAddress -ne $null } -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams;
Assert-MockCalled -CommandName Set-VMNetworkAdapter -ParameterFilter { $StaticMacAddress -ne $null } -Exactly 0 -Scope It;
}
It 'Calls "Set-VMNetworkAdapter" for each MAC address on a stopped VM' {
Mock -CommandName Set-VMNetworkAdapter -MockWith { }
Set-TargetResource -Name 'StoppedVM' @testParams -MACAddress 'AABBCCDDEEFE','AABBCCDDEEFF';
## The first NIC is assigned during the VM creation
Assert-MockCalled -CommandName Set-VMNetworkAdapter -Exactly 2 -Scope It;
}
It 'Does not change Secure Boot call "Change-VMSecureBoot" when creating a generation 1 VM' {
Mock -CommandName Change-VMSecureBoot -MockWith { return $true; }
Set-TargetResource -Name 'RunningVM' @testParams;
Assert-MockCalled -CommandName Change-VMSecureBoot -Exactly 0 -Scope It;
}
It 'Does call "Change-VMSecureBoot" when creating a generation 2 VM' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Mock -CommandName Change-VMSecureBoot -MockWith { }
Set-TargetResource -Name 'RunningVM' -Generation 2 -SecureBoot $false @testParams;
Assert-MockCalled -CommandName Change-VMSecureBoot -Exactly 1 -Scope It;
}
It 'Does not change Secure Boot for generation 1 VM' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Mock -CommandName Change-VMSecureBoot -MockWith { }
Set-TargetResource -Name 'StoppedVM' -SecureBoot $true @testParams;
Set-TargetResource -Name 'StoppedVM' -SecureBoot $false @testParams;
Assert-MockCalled -CommandName Change-VMSecureBoot -Exactly -Times 0 -Scope It;
}
It 'Does not change Secure Boot for generation 2 VM with VM "SecureBoot" match' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $true; }
Mock -CommandName Change-VMSecureBoot -MockWith { }
Set-TargetResource -Name 'StoppedVM' -SecureBoot $true -Generation 2 @testParams;
Assert-MockCalled -CommandName Change-VMSecureBoot -Exactly -Times 0 -Scope It;
}
It 'Does change Secure Boot for generation 2 VM with VM "SecureBoot" mismatch' {
Mock -CommandName Test-VMSecureBoot -MockWith { return $false; }
Mock -CommandName Change-VMSecureBoot -MockWith { }
Set-TargetResource -Name 'StoppedVM' -SecureBoot $true -Generation 2 @testParams;
Assert-MockCalled -CommandName Change-VMSecureBoot -Exactly -Times 1 -Scope It;
}
It 'Does call "Enable-VMIntegrationService" when "EnableGuestService" = "$true"' {
Mock -CommandName Enable-VMIntegrationService -MockWith { }
Set-TargetResource -Name 'RunningVM' -EnableGuestService $true @testParams
Assert-MockCalled -CommandName Enable-VMIntegrationService -Exactly -Times 1 -Scope It
}
It 'Does call "Disable-VMIntegrationService" when "Guest Service Interface" = "Enabled" and "EnableGuestService" = "$false" specified' {
Mock -CommandName Disable-VMIntegrationService -MockWith { }
Mock -CommandName Get-VMIntegrationService -MockWith {return [pscustomobject]@{Enabled=$true}}
Set-TargetResource -Name 'RunningVM' -EnableGuestService $false @testParams
Assert-MockCalled -CommandName Disable-VMIntegrationService -Exactly -Times 1 -Scope It
}
It 'Throws when Hyper-V Tools are not installed' {
Mock -CommandName Get-Module -ParameterFilter { ($Name -eq 'Hyper-V') -and ($ListAvailable -eq $true) } -MockWith { }
{ Set-TargetResource -Name 'RunningVM' @testParams } | Should Throw;
}
} #end context Validates Set-TargetResource Method
Context 'Validates Test-VMSecureBoot Method' {
It 'Returns $true when "SecureBoot" = "On"' {
Mock -CommandName Get-VM -MockWith { }
Mock -CommandName Get-VMFirmware -MockWith { return [PSCustomObject] @{ SecureBoot = 'On' }; }
Test-VMSecureBoot -Name 'TestVM' | Should Be $true;
}
It 'Returns $false when "SecureBoot" = "Off"' {
Mock -CommandName Get-VM -MockWith { }
Mock -CommandName Get-VMFirmware -MockWith { return [PSCustomObject] @{ SecureBoot = 'Off' }; }
Test-VMSecureBoot -Name 'TestVM' | Should Be $false;
}
} #end context Validates Test-VMSecureBoot Method
Context 'Validates Change-VMSecureBoot Method' {
It 'Throws if "State" = "Running" and "RestartIfNeeded" = "$false"' {
{ Change-VMSecureBoot -Name 'RunningVM' -SecureBoot $true -RestartIfNeeded $false -ErrorAction Stop } | Should Throw;
}
It 'Calls Set-VMFirmware when "State" = "Off" and "RestartIfNeeded" = "$false"' {
Mock -CommandName Set-VMFirmware -MockWith { }
Change-VMSecureBoot -Name 'StoppedVM' -SecureBoot $true -RestartIfNeeded $false;
Assert-MockCalled -CommandName Set-VMFirmware -Exactly 1 -Scope It;
}
It 'Calls Set-VMFirmware when "State" = "Running" and "RestartIfNeeded" = "$true"' {
Mock -CommandName Set-VMState -MockWith { }
Mock -CommandName Set-VMFirmware -MockWith { }
Change-VMSecureBoot -Name 'RunningVM' -SecureBoot $true -RestartIfNeeded $true;
Assert-MockCalled -CommandName Set-VMFirmware -Scope It;
}
} #end context Validates Change-VMSecureBoot Method
Context 'Validates Get-VhdHierarchy Method' {
It 'Does not throw with null parent path (#52)' {
## Must use a different file extension to ensure existing mocks Get-VhdHierarchy or not called
$fakeVhdPath = 'BaseVhd.avhdx';
Mock -CommandName Get-VHD -ParameterFilter { $Path -eq $fakeVhdPath } -MockWith {
return [PSCustomObject] @{
Path = $fakeVhdPath;
ParentPath = $null;
}
}
{ Get-VhdHierarchy -VhdPath $fakeVhdPath } | Should Not Throw;
}
} #end context validates Get-VhdHierarchy
} #end inmodulescope
} #end describe xVMHyper-V
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Unit/MSFT_xVMSwitch_BandwidthReservationMode.Tests.ps1
|
MSFT_xVMSwitch_BandwidthReservationMode.Tests.ps1
|
[CmdletBinding()]
Param (
)
if (!$PSScriptRoot) # $PSScriptRoot is not defined in 2.0
{
$PSScriptRoot = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
}
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version latest
$RepoRoot = (Resolve-Path $PSScriptRoot\..\..).Path
$ModuleName = 'MSFT_xVMSwitch'
Import-Module (Join-Path $RepoRoot "DSCResources\$ModuleName\$ModuleName.psm1") -Force;
Describe 'xVMSwitch' {
InModuleScope $ModuleName {
# Defines a variable that contains all the possible Bandwidth Reservation Modes which will be used
# for foreach loops later on
New-Variable -Name 'BANDWIDTH_RESERVATION_MODES' -Option 'Constant' -Value @('Default','Weight','Absolute','None')
# A helper function to mock a VMSwitch
function New-MockedVMSwitch {
Param (
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$true)]
[ValidateSet('Default','Weight','Absolute','None','NA')]
[string]$BandwidthReservationMode,
[bool]$AllowManagementOS = $false
)
$mockedVMSwitch = @{
Name = $Name
SwitchType = 'External'
AllowManagementOS = $AllowManagementOS
NetAdapterInterfaceDescription = 'Microsoft Network Adapter Multiplexor Driver'
}
if ($BandwidthReservationMode -ne 'NA') {
$mockedVMSwitch['BandwidthReservationMode'] = $BandwidthReservationMode
}
return [PsObject]$mockedVMSwitch
}
# Create an empty function to be able to mock the missing Hyper-V cmdlet
function Get-VMSwitch {
[CmdletBinding()]
Param(
[string]$Name,
[string]$SwitchType
)
}
# Create an empty function to be able to mock the missing Hyper-V cmdlet
function New-VMSwitch {
[CmdletBinding()]
Param(
[string]$Name,
[string]$MinimumBandwidthMode,
[string]$NetAdapterName,
[bool]$AllowManagementOS = $false
)
}
# Create an empty function to be able to mock the missing Hyper-V cmdlet
function Remove-VMSwitch {
}
# Create an empty function to be able to mock the missing Hyper-V cmdlet
function Set-VMSwitch {
[CmdletBinding()]
Param (
[bool]$AllowManagementOS
)
}
# Mocks Get-VMSwitch and will return $global:mockedVMSwitch which is
# a variable that is created during most It statements to mock a VMSwitch
Mock -CommandName Get-VMSwitch -MockWith {
Param (
[string]$ErrorAction
)
if ($ErrorAction -eq 'Stop' -and $global:mockedVMSwitch -eq $null) {
throw [System.Management.Automation.ActionPreferenceStopException]'No switch can be found by given criteria.'
}
return $global:mockedVMSwitch
}
# Mocks New-VMSwitch and will assign a mocked switch to $global:mockedVMSwitch. This returns $global:mockedVMSwitch
# which is a variable that is created during most It statements to mock a VMSwitch
Mock -CommandName New-VMSwitch -MockWith {
Param (
[string]$Name,
[string]$NetAdapterName,
[string]$MinimumBandwidthMode,
[bool]$AllowManagementOS
)
$global:mockedVMSwitch = New-MockedVMSwitch -Name $Name -BandwidthReservationMode $MinimumBandwidthMode -AllowManagementOS $AllowManagementOS
return $global:mockedVMSwitch
}
# Mocks Set-VMSwitch and will modify $global:mockedVMSwitch which is
# a variable that is created during most It statements to mock a VMSwitch
Mock -CommandName Set-VMSwitch -MockWith {
Param (
[bool]$AllowManagementOS
)
if ($AllowManagementOS) {
$global:mockedVMSwitch['AllowManagementOS'] = $AllowManagementOS
}
}
# Mocks Remove-VMSwitch and will remove the variable $global:mockedVMSwitch which is
# a variable that is created during most It statements to mock a VMSwitch
Mock -CommandName Remove-VMSwitch -MockWith {
$global:mockedVMSwitch = $null
}
# Mocks Get-NetAdapter which returns a simplified network adapter
Mock -CommandName Get-NetAdapter -MockWith {
return [PSCustomObject]@{
Name = 'SomeNIC'
InterfaceDescription = 'Microsoft Network Adapter Multiplexor Driver'
}
}
# Mocks "Get-Module -Name Hyper-V" so that the DSC resource thinks the Hyper-V module is on the test system
Mock -CommandName Get-Module -ParameterFilter { ($Name -eq 'Hyper-V') -and ($ListAvailable -eq $true) } -MockWith {
return $true
}
# Mock "Get-WmiObject -Class -eq 'Win32_OperatingSystem'" to output a valid Windows version that supports BandwidthReservationMode
Mock -CommandName Get-WmiObject -ParameterFilter { $Class -eq 'Win32_OperatingSystem' } -MockWith {
return [PSCustomObject]@{
Version = '6.3.9600'
}
}
# Create all the test cases for Get-TargetResource
$getTestCases = @()
foreach ($brmMode in $BANDWIDTH_RESERVATION_MODES) {
$getTestCases += @{
CurrentName = $brmMode + 'BRM'
CurrentBandwidthReservationMode = $brmMode
}
}
Context 'Validates Get-TargetResource Function' {
# Test Get-TargetResource with the test cases created above
It 'Current switch''s BandwidthReservationMode is set to <CurrentBandwidthReservationMode>' -TestCases $getTestCases {
Param (
[string]$CurrentName,
[string]$CurrentBandwidthReservationMode
)
# Set the mocked VMSwitch to be returned from Get-VMSwitch based on the input from $getTestCases
$global:mockedVMSwitch = New-MockedVMSwitch -Name $CurrentName -BandwidthReservationMode $CurrentBandwidthReservationMode
$targetResource = Get-TargetResource -Name $CurrentName -Type 'External'
$targetResource -is [System.Collections.Hashtable] | Should Be $true
$targetResource['BandwidthReservationMode'] | Should Be $CurrentBandwidthReservationMode
Remove-Variable -Scope 'Global' -Name 'mockedVMSwitch' -ErrorAction 'SilentlyContinue'
}
# Test Get-TargetResource when the VMSwitch's BandwidthReservationMode member variable is not
# set which simulates older versions of Windows that don't support it
It 'BandwidthReservationMode is set to null' {
# Set the mocked VMSwitch to be returned from Get-VMSwitch
$global:mockedVMSwitch = New-MockedVMSwitch -Name 'NaBRM' -BandwidthReservationMode 'NA'
$targetResource = Get-TargetResource -Name 'NaBRM' -Type 'External'
$targetResource -is [System.Collections.Hashtable] | Should Be $true
$targetResource['BandwidthReservationMode'] | Should Be $null
Remove-Variable -Scope 'Global' -Name 'mockedVMSwitch' -ErrorAction 'SilentlyContinue'
}
}
# Create all the test cases for Test-TargetResource and Set-TargetResource when the switch already exists
$testSetTestCases = @()
foreach ($currentBrmMode in $BANDWIDTH_RESERVATION_MODES) {
foreach ($desiredBrmMode in $BANDWIDTH_RESERVATION_MODES) {
foreach ($ensureOption in @('Present', 'Absent')) {
$case = @{
CurrentName = $currentBrmMode + 'BRM'
CurrentBandwidthReservationMode = $currentBrmMode
DesiredName = $desiredBrmMode + 'BRM'
DesiredBandwidthReservationMode = $desiredBrmMode
Ensure = $ensureOption
ExpectedResult = $ensureOption -eq 'Present' -and $currentBrmMode -eq $desiredBrmMode
}
$testSetTestCases += $case
}
}
}
# Create all the test cases for Test-TargetResource and Set-TargetResource when the switch does not exists
foreach ($desiredBrmMode in $BANDWIDTH_RESERVATION_MODES) {
foreach ($ensureOption in @('Present', 'Absent')) {
$case = @{
CurrentName = $null
CurrentBandwidthReservationMode = $null
DesiredName = $desiredBrmMode + 'BRM'
DesiredBandwidthReservationMode = $desiredBrmMode
Ensure = $ensureOption
ExpectedResult = $ensureOption -eq 'Absent'
}
$testSetTestCases += $case
}
}
Context 'Validates Test-TargetResource Function' {
# Test Test-TargetResource with the test cases created above
It 'Current Name "<CurrentName>" | Current BandwidthReservationMode set to "<CurrentBandwidthReservationMode>" | Desired BandwidthReservationMode set to "<DesiredBandwidthReservationMode>" | Ensure "<Ensure>"' -TestCases $testSetTestCases {
Param (
[string]$CurrentName,
[string]$CurrentBandwidthReservationMode,
[string]$DesiredName,
[string]$DesiredBandwidthReservationMode,
[string]$Ensure,
[bool]$ExpectedResult
)
# Set the mocked VMSwitch to be returned from Get-VMSwitch if the switch exists
if ($CurrentName) {
$global:mockedVMSwitch = New-MockedVMSwitch -Name $CurrentName -BandwidthReservationMode $CurrentBandwidthReservationMode -AllowManagementOS $true
}
$targetResource = Test-TargetResource -Name $DesiredName -BandwidthReservationMode $DesiredBandwidthReservationMode -Type 'External' -NetAdapterName 'SomeNIC' -Ensure $Ensure -AllowManagementOS $true
$targetResource | Should Be $ExpectedResult
Remove-Variable -Scope 'Global' -Name 'mockedVMSwitch' -ErrorAction 'SilentlyContinue'
}
# Mock "Get-WmiObject -Class -eq 'Win32_OperatingSystem'" to output an Windows version that does not support BandwidthReservationMode
Mock -CommandName Get-WmiObject -ParameterFilter { $Class -eq 'Win32_OperatingSystem' } -MockWith {
return [PSCustomObject]@{
Version = '6.1.7601'
}
}
# Test Test-TargetResource when the version of Windows doesn't support BandwidthReservationMode
It 'Invalid Operating System Exception' {
{Test-TargetResource -Name 'WeightBRM' -Type 'External' -NetAdapterName 'SomeNIC' -AllowManagementOS $true -BandwidthReservationMode 'Weight' -Ensure 'Present'} | Should Throw 'The BandwidthReservationMode cannot be set on a Hyper-V version lower than 2012'
}
# Test Test-TargetResource when the version of Windows doesn't support BandwidthReservationMode and specifies NA for BandwidthReservationMode
It 'Simulates Windows Server 2008 R2 | Desired BandwidthReservationMode set to "NA" | Ensure Present | Expected Result is True' {
$global:mockedVMSwitch = New-MockedVMSwitch -Name 'SomeSwitch' -BandwidthReservationMode 'NA' -AllowManagementOS $true
$targetResource = Test-TargetResource -Name 'SomeSwitch' -BandwidthReservationMode 'NA' -Type 'External' -NetAdapterName 'SomeNIC' -Ensure 'Present' -AllowManagementOS $true
$targetResource | Should Be $true
}
It 'Passes when "BandwidthReservationMode" does not match but is not specified (#48)' {
$global:mockedVMSwitch = New-MockedVMSwitch -Name 'SomeSwitch' -BandwidthReservationMode 'Absolute'
$targetResource = Test-TargetResource -Name 'SomeSwitch' -Type 'Internal' -Ensure 'Present'
$targetResource | Should Be $true
}
}
Context 'Validates Set-TargetResource Function' {
It 'Current Name "<CurrentName>" | Current BandwidthReservationMode set to "<CurrentBandwidthReservationMode>" | Desired BandwidthReservationMode set to "<DesiredBandwidthReservationMode>" | Ensure "<Ensure>"' -TestCases $testSetTestCases {
Param (
[string]$CurrentName,
[string]$CurrentBandwidthReservationMode,
[string]$DesiredName,
[string]$DesiredBandwidthReservationMode,
[string]$Ensure,
[bool]$ExpectedResult
)
# Set the mocked VMSwitch to be returned from Get-VMSwitch if the switch exists
if ($CurrentName) {
$global:mockedVMSwitch = New-MockedVMSwitch -Name $CurrentName -BandwidthReservationMode $CurrentBandwidthReservationMode -AllowManagementOS $true
}
$targetResource = Set-TargetResource -Name $DesiredName -BandwidthReservationMode $DesiredBandwidthReservationMode -Type 'External' -NetAdapterName 'SomeNIC' -Ensure $Ensure -AllowManagementOS $true
$targetResource | Should Be $null
if ($CurrentName -and $Ensure -eq 'Present') {
if ($DesiredBandwidthReservationMode -ne $CurrentBandwidthReservationMode) {
Assert-MockCalled -CommandName Get-VMSwitch -Times 2 -Scope 'It'
Assert-MockCalled -CommandName Remove-VMSwitch -Times 1 -Scope 'It'
Assert-MockCalled -CommandName New-VMSwitch -Times 1 -Scope 'It'
Assert-MockCalled -CommandName Set-VMSwitch -Times 0 -Scope 'It'
}
else {
Assert-MockCalled -CommandName Get-VMSwitch -Times 1 -Scope 'It'
}
}
elseif ($Ensure -eq 'Present') {
Assert-MockCalled -CommandName Get-VMSwitch -Times 1 -Scope 'It'
Assert-MockCalled -CommandName New-VMSwitch -Times 1 -Scope 'It'
}
else {
Assert-MockCalled -CommandName Get-VMSwitch -Times 1 -Scope 'It'
Assert-MockCalled -CommandName Remove-VMSwitch -Times 1 -Scope 'It'
}
Remove-Variable -Scope 'Global' -Name 'mockedVMSwitch' -ErrorAction 'SilentlyContinue'
}
# Test Set-TargetResource when the version of Windows doesn't support BandwidthReservationMode
It 'Invalid Operating System Exception' {
Mock -CommandName Get-WmiObject -ParameterFilter { $Class -eq 'Win32_OperatingSystem' } -MockWith {
return [PSCustomObject]@{
Version = '6.1.7601'
}
}
{Set-TargetResource -Name 'WeightBRM' -Type 'External' -NetAdapterName 'SomeNIC' -AllowManagementOS $true -BandwidthReservationMode 'Weight' -Ensure 'Present'} | Should Throw 'The BandwidthReservationMode cannot be set on a Hyper-V version lower than 2012'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Unit/MSFT_xVMDvdDrive.tests.ps1
|
MSFT_xVMDvdDrive.tests.ps1
|
$script:DSCModuleName = 'xHyper-V'
$script:DSCResourceName = 'MSFT_xVMDvdDrive'
#region HEADER
# Unit Test Template Version: 1.1.0
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-TestType Unit
#endregion HEADER
# Begin Testing
try
{
#region Pester Tests
InModuleScope $script:DSCResourceName {
# Function to create a exception object for testing output exceptions
function Get-InvalidArguementError
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorId,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorMessage
)
$exception = New-Object -TypeName System.ArgumentException `
-ArgumentList $ErrorMessage
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument
$errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord `
-ArgumentList $exception, $ErrorId, $errorCategory, $null
return $errorRecord
} # end function Get-InvalidArguementError
#region Pester Test Initialization
$script:VMName = 'HyperVUnitTestsVM'
$script:TestISOPath = 'd:\test\test.iso'
$script:splatGetDvdDrive = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Verbose = $True
}
$script:splatAddDvdDriveNoPath = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Path = ''
Ensure = 'Present'
Verbose = $True
}
$script:splatAddDvdDrive = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Path = $script:TestISOPath
Ensure = 'Present'
Verbose = $True
}
$script:splatRemoveDvdDrive = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Ensure = 'Absent'
Verbose = $True
}
$script:mockGetModule = [pscustomobject] @{
Name = 'Hyper-V'
}
$script:mockGetVM = [pscustomobject] @{
Name = $VMName
}
$script:mockGetVMScsiController = [pscustomobject] @{
VMName = $VMName
}
$script:mockGetVMHardDiskDrive = [pscustomobject] @{
VMName = $VMName
}
$script:mockNoDvdDrive = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Ensure = 'Absent'
}
$script:mockDvdDriveWithPath = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Path = $script:TestISOPath
Ensure = 'Present'
}
$script:mockDvdDriveWithDiffPath = @{
VMName = $script:VMName
ControllerNumber = 0
ControllerLocation = 1
Path = 'd:\diff\diff.iso'
Ensure = 'Present'
}
#endregion
#region Function Get-TargetResource
Describe 'MSFT_xVMDvdDrive\Get-TargetResource' {
#region VM Functions
function Get-VM {
Param
(
[String]
$Name
)
}
function Get-VMScsiController {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber
)
}
function Get-VMIdeController {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber
)
}
function Get-VMHardDiskDrive {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber,
[Uint32]
$ControllerLocation
)
}
function Get-VMDvdDrive {
Param
(
[String]
$VMName
)
}
#endregion
Context 'DVD Drive does not exist' {
# Verifiable (should be called) mocks
Mock `
-CommandName Test-ParameterValid `
-Verifiable
Mock `
-CommandName Get-VMDvdDrive `
-MockWith {} `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName } `
-Verifiable
It 'should not throw exception' {
{
$script:resource = Get-TargetResource @script:splatGetDvdDrive
} | Should Not Throw
}
It 'should return expected values' {
$script:resource.VMName | Should Be $script:splatGetDvdDrive.VMName
$script:resource.ControllerNumber | Should Be $script:splatGetDvdDrive.ControllerNumber
$script:resource.ControllerLocation | Should Be $script:splatGetDvdDrive.ControllerLocation
$script:resource.Path | Should BeNullOrEmpty
$script:resource.Ensure | Should Be 'Absent'
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Test-ParameterValid -Exactly 1
Assert-MockCalled -CommandName Get-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName }
}
}
Context 'DVD Drive exists, but has empty path' {
# Verifiable (should be called) mocks
Mock `
-CommandName Test-ParameterValid `
-Verifiable
Mock `
-CommandName Get-VMDvdDrive `
-MockWith { $script:splatAddDvdDriveNoPath } `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName } `
-Verifiable
It 'should not throw exception' {
{
$script:resource = Get-TargetResource @script:splatGetDvdDrive
} | Should Not Throw
}
It 'should return expected values' {
$script:resource.VMName | Should Be $script:splatGetDvdDrive.VMName
$script:resource.ControllerNumber | Should Be $script:splatGetDvdDrive.ControllerNumber
$script:resource.ControllerLocation | Should Be $script:splatGetDvdDrive.ControllerLocation
$script:resource.Path | Should BeNullOrEmpty
$script:resource.Ensure | Should Be 'Present'
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Test-ParameterValid -Exactly 1
Assert-MockCalled -CommandName Get-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName }
}
}
Context 'DVD Drive exists, and has a test ISO path' {
# Verifiable (should be called) mocks
Mock `
-CommandName Test-ParameterValid `
-Verifiable
Mock `
-CommandName Get-VMDvdDrive `
-MockWith { $script:splatAddDvdDrive } `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName } `
-Verifiable
It 'should not throw exception' {
{
$script:resource = Get-TargetResource @script:splatGetDvdDrive
} | Should Not Throw
}
It 'should return expected values' {
$script:resource.VMName | Should Be $script:splatGetDvdDrive.VMName
$script:resource.ControllerNumber | Should Be $script:splatGetDvdDrive.ControllerNumber
$script:resource.ControllerLocation | Should Be $script:splatGetDvdDrive.ControllerLocation
$script:resource.Path | Should Be $script:TestISOPath
$script:resource.Ensure | Should Be 'Present'
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Test-ParameterValid -Exactly 1
Assert-MockCalled -CommandName Get-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatGetDvdDrive.VMName }
}
}
}
#endregion
#region Function Set-TargetResource
Describe 'MSFT_xVMDvdDrive\Set-TargetResource' {
#region VM Functions
function Add-VMDvdDrive {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber,
[Uint32]
$ControllerLocation,
[String]
$Path
)
}
function Set-VMDvdDrive {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber,
[Uint32]
$ControllerLocation,
[String]
$Path
)
}
function Remove-VMDvdDrive {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber,
[Uint32]
$ControllerLocation
)
}
#endregion
Context 'DVD Drive does not exist but should' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockNoDvdDrive } `
-Verifiable
Mock `
-CommandName Add-VMDvdDrive `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Set-VMDvdDrive
Mock -CommandName Remove-VMDvdDrive
It 'should not throw exception' {
{ Set-TargetResource @script:splatAddDvdDriveNoPath } | Should Not Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
Assert-MockCalled -CommandName Add-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
Assert-MockCalled -CommandName Set-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Remove-VMDvdDrive -Exactly 0
}
}
Context 'DVD Drive does exist and should, path matches' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithPath } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Add-VMDvdDrive
Mock -CommandName Set-VMDvdDrive
Mock -CommandName Remove-VMDvdDrive
It 'should not throw exception' {
{ Set-TargetResource @script:splatAddDvdDrive } | Should Not Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
Assert-MockCalled -CommandName Add-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Set-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Remove-VMDvdDrive -Exactly 0
}
}
Context 'DVD Drive does exist and should, path does not match' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithDiffPath } `
-Verifiable
Mock `
-CommandName Set-VMDvdDrive `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Add-VMDvdDrive
Mock -CommandName Remove-VMDvdDrive
It 'should not throw exception' {
{ Set-TargetResource @script:splatAddDvdDrive } | Should Not Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
Assert-MockCalled -CommandName Add-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Set-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Remove-VMDvdDrive -Exactly 0
}
}
Context 'DVD Drive exists and should not' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithPath } `
-Verifiable
Mock `
-CommandName Remove-VMDvdDrive `
-ParameterFilter { $VMName -eq $script:splatRemoveDvdDrive.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Add-VMDvdDrive
Mock -CommandName Set-VMDvdDrive
It 'should not throw exception' {
{ Set-TargetResource @script:splatRemoveDvdDrive } | Should Not Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
Assert-MockCalled -CommandName Add-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Set-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Remove-VMDvdDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatRemoveDvdDrive.VMName }
}
}
Context 'DVD Drive does not exist and should not' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockNoDvdDrive } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Add-VMDvdDrive
Mock -CommandName Set-VMDvdDrive
Mock -CommandName Remove-VMDvdDrive
It 'should not throw exception' {
{ Set-TargetResource @script:splatRemoveDvdDrive } | Should Not Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
Assert-MockCalled -CommandName Add-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Set-VMDvdDrive -Exactly 0
Assert-MockCalled -CommandName Remove-VMDvdDrive -Exactly 0
}
}
}
#endregion
#region Function Test-TargetResource
Describe 'MSFT_xVMDvdDrive\Test-TargetResource' {
Context 'DVD Drive does not exist but should' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockNoDvdDrive } `
-Verifiable
It 'should return false' {
Test-TargetResource @script:splatAddDvdDriveNoPath | Should Be $False
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
Context 'DVD Drive does exist and should, path matches' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithPath } `
-Verifiable
It 'should return true' {
Test-TargetResource @script:splatAddDvdDrive | Should Be $True
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
Context 'DVD Drive does exist and should, path does not match' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithDiffPath } `
-Verifiable
It 'should return false' {
Test-TargetResource @script:splatAddDvdDrive | Should Be $False
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
Context 'DVD Drive exists and should not' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockDvdDriveWithPath } `
-Verifiable
It 'should return false' {
Test-TargetResource @script:splatRemoveDvdDrive | Should Be $False
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
Context 'DVD Drive does not exist and should not' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-TargetResource `
-MockWith { $script:mockNoDvdDrive } `
-Verifiable
It 'should return true' {
Test-TargetResource @script:splatRemoveDvdDrive | Should Be $True
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-TargetResource -Exactly 1
}
}
}
#endregion
#region Function Test-ParameterValid
Describe 'MSFT_xVMDvdDrive\Test-ParameterValid' {
#region VM Functions
function Get-VM {
Param
(
[String]
$Name
)
}
function Get-VMScsiController {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber
)
}
function Get-VMIdeController {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber
)
}
function Get-VMHardDiskDrive {
Param
(
[String]
$VMName,
[Uint32]
$ControllerNumber,
[Uint32]
$ControllerLocation
)
}
function Get-VMDvdDrive {
Param
(
[String]
$VMName
)
}
#endregion
Context 'Hyper-V Module is not available' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VM
Mock -CommandName Get-VMScsiController
Mock -CommandName Get-VMIdeController
Mock -CommandName Get-VMHardDiskDrive
It 'should throw exception' {
$errorRecord = Get-InvalidArguementError `
-ErrorId 'RoleMissingError' `
-ErrorMessage ($LocalizedData.RoleMissingError -f `
'Hyper-V')
{ Test-ParameterValid @script:splatAddDvdDriveNoPath } | Should Throw $errorRecord
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
}
}
Context 'VM does not exist' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-MockWith { $script:mockGetModule } `
-Verifiable
Mock `
-CommandName Get-VM `
-MockWith { Throw } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VMScsiController
Mock -CommandName Get-VMIdeController
Mock -CommandName Get-VMHardDiskDrive
It 'should throw exception' {
{ Test-ParameterValid @script:splatAddDvdDriveNoPath } | Should Throw
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
Assert-MockCalled -CommandName Get-VM -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
}
}
Context 'VM exists, controller does not exist' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-MockWith { $script:mockGetModule } `
-Verifiable
Mock `
-CommandName Get-VM `
-MockWith { $script:mockGetVM } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
Mock `
-CommandName Get-VMScsiController `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
Mock `
-CommandName Get-VMIdeController `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VMHardDiskDrive
It 'should throw exception' {
$errorRecord = Get-InvalidArguementError `
-ErrorId 'VMControllerDoesNotExistError' `
-ErrorMessage ($LocalizedData.VMControllerDoesNotExistError -f `
$script:VMName,0)
{ Test-ParameterValid @script:splatAddDvdDriveNoPath } | Should Throw $errorRecord
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
Assert-MockCalled -CommandName Get-VM -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
Assert-MockCalled -CommandName Get-VMScsiController -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
Assert-MockCalled -CommandName Get-VMIdeController -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
}
}
Context 'VM exists, SCSI contrller exists, HD assigned' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-MockWith { $script:mockGetModule } `
-Verifiable
Mock `
-CommandName Get-VM `
-MockWith { $script:mockGetVM } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
Mock `
-CommandName Get-VMScsiController `
-MockWith { $script:mockGetVMScsiController } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
Mock `
-CommandName Get-VMHardDiskDrive `
-MockWith { $script:mockGetVMHardDiskDrive } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VMIdeController
It 'should throw exception' {
$errorRecord = Get-InvalidArguementError `
-ErrorId 'ControllerConflictError' `
-ErrorMessage ($LocalizedData.ControllerConflictError -f `
$script:VMName,0,1)
{ Test-ParameterValid @script:splatAddDvdDriveNoPath } | Should Throw $errorRecord
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
Assert-MockCalled -CommandName Get-VM -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
Assert-MockCalled -CommandName Get-VMScsiController -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
Assert-MockCalled -CommandName Get-VMHardDiskDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDriveNoPath.VMName }
}
}
Context 'VM exists, SCSI contrller exists, HD not assigned, Path invalid' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-MockWith { $script:mockGetModule } `
-Verifiable
Mock `
-CommandName Get-VM `
-MockWith { $script:mockGetVM } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Get-VMScsiController `
-MockWith { $script:mockGetVMScsiController } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Get-VMHardDiskDrive `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Test-Path `
-MockWith { $False } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VMIdeController
It 'should throw exception' {
$errorRecord = Get-InvalidArguementError `
-ErrorId 'PathDoesNotExistError' `
-ErrorMessage ($LocalizedData.PathDoesNotExistError -f `
$script:TestISOPath)
{ Test-ParameterValid @script:splatAddDvdDrive } | Should Throw $errorRecord
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
Assert-MockCalled -CommandName Get-VM -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Get-VMScsiController -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Get-VMHardDiskDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Test-Path -Exactly 1
}
}
Context 'VM exists, SCSI contrller exists, HD not assigned, Path Valid' {
# Verifiable (should be called) mocks
Mock `
-CommandName Get-Module `
-MockWith { $script:mockGetModule } `
-Verifiable
Mock `
-CommandName Get-VM `
-MockWith { $script:mockGetVM } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Get-VMScsiController `
-MockWith { $script:mockGetVMScsiController } `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Get-VMHardDiskDrive `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName } `
-Verifiable
Mock `
-CommandName Test-Path `
-MockWith { $True } `
-Verifiable
# Mocks that should not be called
Mock -CommandName Get-VMIdeController
It 'should not throw exception' {
Test-ParameterValid @script:splatAddDvdDrive | Should Be $True
}
It 'all the get mocks should be called' {
Assert-VerifiableMocks
Assert-MockCalled -CommandName Get-Module -Exactly 1
Assert-MockCalled -CommandName Get-VM -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Get-VMScsiController -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Get-VMHardDiskDrive -Exactly 1 `
-ParameterFilter { $VMName -eq $script:splatAddDvdDrive.VMName }
Assert-MockCalled -CommandName Test-Path -Exactly 1
}
}
}
#endregion
}
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Integration/MSFT_xVMDvdDrive_remove.config.ps1
|
MSFT_xVMDvdDrive_remove.config.ps1
|
configuration MSFT_xVMDvdDrive_Remove_Config {
Import-DscResource -ModuleName xHyper-V
node localhost {
xVMDvdDrive Integration_Test {
VMName = $Node.VMName
ControllerNumber = $Node.ControllerNumber
ControllerLocation = $Node.ControllerLocation
Path = $Node.Path
Ensure = 'Absent'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Integration/MSFT_xVMDvdDrive_add.config.ps1
|
MSFT_xVMDvdDrive_add.config.ps1
|
configuration MSFT_xVMDvdDrive_Add_Config {
Import-DscResource -ModuleName xHyper-V
node localhost {
xVMDvdDrive Integration_Test {
VMName = $Node.VMName
ControllerNumber = $Node.ControllerNumber
ControllerLocation = $Node.ControllerLocation
Path = $Node.Path
Ensure = 'Present'
}
}
}
|
PowerShellCorpus/PowerShellGallery/xHyper-V/3.8.0.0/Tests/Integration/MSFT_xVMDvdDrive.Integration.Tests.ps1
|
MSFT_xVMDvdDrive.Integration.Tests.ps1
|
$script:DSCModuleName = 'xHyper-V'
$script:DSCResourceName = 'MSFT_xVMDvdDrive'
#region HEADER
# Integration Test Template Version: 1.1.1
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-TestType Integration
#endregion
# Import the common integration test functions
Import-Module -Name ( Join-Path `
-Path $PSScriptRoot `
-ChildPath 'IntegrationTestsCommon.psm1' )
# Ensure that the tests can be performed on this computer
if (-not (Test-HyperVInstalled))
{
Return
} # if
# Using try/finally to always cleanup even if something awful happens.
try
{
$VMName = 'HyperVIntTestsVM'
$VMPath = Join-Path -Path $TestDrive `
-ChildPath $VMName
# Make sure test VM does not exist
if (Get-VM -Name $VMName -ErrorAction SilentlyContinue)
{
$null = Remove-VM -Name $VMName -Force
} # if
# Create the VM that will be used to test with
$null = New-VM -Name $VMName -NoVHD -Path $VMPath
# Create a config data object to pass to the DSC Configs
$ConfigData = @{
AllNodes = @(
@{
NodeName = 'localhost'
VMName = $VMName
ControllerNumber = 0
ControllerLocation = 0
Path = ''
}
)
}
# Add DVD Drive
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName)_add.config.ps1"
. $ConfigFile -Verbose -ErrorAction Stop
Describe "$($script:DSCResourceName)_Add_Integration" {
Context 'Add a DVD Drive to a VM' {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
& "$($script:DSCResourceName)_Add_Config" `
-OutputPath $TestDrive `
-ConfigurationData $ConfigData
Start-DscConfiguration -Path $TestDrive `
-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' {
$current = Get-DscConfiguration | Where-Object {
$_.ConfigurationName -eq "$($script:DSCResourceName)_Add_Config"
}
$current.VMName | Should Be $VMName
$current.ControllerNumber | Should Be 0
$current.ControllerLocation | Should Be 0
$current.Path | Should BeNullOrEmpty
$current.Ensure | Should Be 'Present'
}
}
}
# Dismount ISO
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName)_remove.config.ps1"
. $ConfigFile -Verbose -ErrorAction Stop
Describe "$($script:DSCResourceName)_Remove_Integration" {
Context 'Remove a DVD Drive from a VM' {
#region DEFAULT TESTS
It 'Should compile without throwing' {
{
& "$($script:DSCResourceName)_Remove_Config" `
-OutputPath $TestDrive `
-ConfigurationData $ConfigData
Start-DscConfiguration -Path $TestDrive `
-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' {
$current = Get-DscConfiguration | Where-Object {
$_.ConfigurationName -eq "$($script:DSCResourceName)_Remove_Config"
}
$current.VMName | Should Be $VMName
$current.ControllerNumber | Should Be 0
$current.ControllerLocation | Should Be 0
$current.Path | Should BeNullOrEmpty
$current.Ensure | Should Be 'Absent'
}
}
}
}
finally
{
#region FOOTER
# Make sure the test VM has been removed
if (Get-VM -Name $VMName -ErrorAction SilentlyContinue)
{
$null = Remove-VM -Name $VMName -Force
} # if
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/cLocalFileShare/1.0.1/Examples/Sample_cLocalFileShare.ps1
|
Sample_cLocalFileShare.ps1
|
configuration Sample_cLocalFileShare
{
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName cLocalFileShare
File TestDirectory
{
Ensure = 'Present'
DestinationPath = 'C:\TestDirectory'
Type = 'Directory'
}
cLocalFileShare Share1
{
Ensure = 'Present'
Name = 'Share-1'
Path = 'C:\TestDirectory'
Description = 'Created by the cLocalFileShare DSC resource'
ConcurrentUserLimit = 10
FullAccess = 'NT AUTHORITY\SYSTEM'
ChangeAccess = 'BUILTIN\Administrators'
ReadAccess = 'NT AUTHORITY\Authenticated Users'
NoAccess = 'BUILTIN\Guests'
DependsOn = '[File]TestDirectory'
}
cLocalFileShare Share2
{
Ensure = 'Present'
Name = 'Share-2'
Path = 'C:\TestDirectory'
ConcurrentUserLimit = 0
Description = 'Created by the cLocalFileShare DSC resource'
ReadAccess = 'Everyone'
DependsOn = '[File]TestDirectory'
}
}
Sample_cLocalFileShare -OutputPath "$Env:SystemDrive\Sample_cLocalFileShare"
Start-DscConfiguration -Path "$Env:SystemDrive\Sample_cLocalFileShare" -Force -Verbose -Wait
Get-DscConfiguration
|
PowerShellCorpus/PowerShellGallery/cLocalFileShare/1.0.1/ResourceDesignerScripts/GenerateCLocalFileShareSchema.ps1
|
GenerateCLocalFileShareSchema.ps1
|
#requires -Version 4.0 -Modules xDSCResourceDesigner
$ModuleName = 'cLocalFileShare'
$ResourceName = 'cLocalFileShare'
$DscResourceProperties = @(
(New-xDscResourceProperty -Type String -Attribute Write -Name Ensure -ValidateSet 'Absent', 'Present' -Description 'Indicates if the share exists. Set this property to Absent to ensure that the share does not exist. Setting it to Present (the default value) ensures that the share exists.')
(New-xDscResourceProperty -Type String -Attribute Key -Name Name -Description 'Indicates the name of the share.'),
(New-xDscResourceProperty -Type String -Attribute Key -Name Path -Description 'Indicates the path to the location of the folder to share.'),
(New-xDscResourceProperty -Type UInt32 -Attribute Write -Name ConcurrentUserLimit -Description 'Indicates the number of users allowed to concurrently use the share. To set the limit at the maximum number, set this property to zero.'),
(New-xDscResourceProperty -Type String -Attribute Write -Name Description -Description 'Indicates an optional description for the share.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name FullAccess -Description 'Indicates which accounts are granted Full Control permission to access the share.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name ChangeAccess -Description 'Indicates which accounts are granted Change permission to access the share.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name ReadAccess -Description 'Indicates which accounts are granted Read permission to access the share.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name NoAccess -Description 'Indicates which accounts are denied access to the share.')
)
New-xDscResource -Name $ResourceName -ModuleName $ModuleName -Property $DscResourceProperties -Verbose
|
PowerShellCorpus/PowerShellGallery/cLocalFileShare/1.0.1/Tests/ResourceDesignerTests.ps1
|
ResourceDesignerTests.ps1
|
#requires -Version 4.0 -Modules xDSCResourceDesigner
Split-Path -Path $PSScriptRoot -Parent |
Join-Path -ChildPath 'DSCResources' |
Get-ChildItem -Directory |
Test-xDscResource -Name {$_.FullName} -Verbose
|
PowerShellCorpus/PowerShellGallery/PinnedItem/0.2.0.0/Scripts/Remove-PinnedItem.ps1
|
Remove-PinnedItem.ps1
|
Function Remove-PinnedItem {
<#
.SYNOPSIS
Remove pinned items from StartMenu/Taskbar
.DESCRIPTION
Remove pinned items from StartMenu/Taskbar
.PARAMETER InputObject
Full path of pinned items that will be removed.
Acceptable values:
StartMenu
Taskbar
.NOTES
Name: Remove-PinnedItem
Author: Boe Prox
Version History
1.0 //Boe Prox - 03 June 2015
- Initial Build
.EXAMPLE
Get-PinnedItem -Type TaskBar | Remove-PinnedItem
Description
-----------
Removes all pinned items from the TaskBar
.EXAMPLE
Get-PinnedItem -Type StartMenu | Where {$_.Name -eq 'Snipping Tool'} | Remove-PinnedItem
Description
-----------
Removes Snipping Tool from the StartMenu as a pinned item.
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[System.File.PSItem.PinnedItem[]]$InputObject
)
Begin {
Write-Verbose "Creating Shell ComObject"
$Shell = New-Object -ComObject Shell.Application
}
Process {
ForEach ($Item in $InputObject) {
Write-Verbose "Item: $($Item.fullname)"
Write-Verbose "Type: $($Item.Type)"
If ($Item.fullname -match '^(?<Path>.*\\)(?<File>.*)$') {
$Path = $Matches.Path
$File = $Matches.File
$NameSpace = $Shell.NameSpace($Path)
$NameSpaceFile = $NameSpace.ParseName($File)
Switch ($Item.Type) {
'Taskbar' {
$_Verb = ConvertToVerb -Action UnpinfromTaskbar
$Verb = $NameSpaceFile.Verbs() | Where {
$_.Name -eq $_Verb
}
}
'StartMenu' {
$_Verb = ConvertToVerb -Action UnpinfromStartMenu
$Verb = $NameSpaceFile.Verbs() | Where {
$_.Name -eq $_Verb
}
}
Default {
Write-Warning "No Type found!"
Continue
}
}
If ($Verb) {
If ($PSCmdlet.ShouldProcess($Item.Fullname, "Unpin From $($Type)")) {
$Verb.DoIt()
}
} Else {
Try {
Remove-Item -Path $Item.Fullname -Erroraction Stop
} Catch {
Write-Warning "Unable to delete file: $($Item.Fullname)"
}
}
} Else {
Write-Warning "Unable to parse File and Path from provided Fullname: $($Item.Fullname)!"
}
}
}
End {
Write-Verbose 'Cleanup ComObject'
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Shell)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable Shell -ErrorAction SilentlyContinue -WhatIf:$False
}
}
|
PowerShellCorpus/PowerShellGallery/PinnedItem/0.2.0.0/Scripts/New-PinnedItem.ps1
|
New-PinnedItem.ps1
|
Function New-PinnedItem {
<#
.SYNOPSIS
Adds a pinned item to the StartMenu/Taskbar
.DESCRIPTION
Adds a pinned item to the StartMenu/Taskbar
.PARAMETER TargetPath
Full path to the item that will be pinned
.PARAMETER Type
Determine where item will be pinned to.
Acceptable values:
StartMenu
Taskbar
.PARAMETER Argument
Additional arguments that will be supplied to create shortcut that will
be used to pin to Taskbar or StartMenu
.PARAMETER IconLocation
Location to icon file path.
.PARAMETER ShortCutPath
Name and place where shortcut will be created prior to pinning it to
Taskbar or StartMenu.
.PARAMETER WorkingDirectory
The directory to start the process in.
.NOTES
Name: New-PinnedItem
Author: Boe Prox
Version History
1.0 //Boe Prox - 03 June 2015
- Initial Build
.EXAMPLE
New-PinnedItem -Type StartMenu -TargetPath "C:\windbg.exe"
Description
-----------
Pins Windbg to the StartMenu
.EXAMPLE
New-PinnedItem -TargetPath "C:\Program Files (x86)\Internet Explorer\iexplore.exe" -Type TaskBar
Description
-----------
Pins Internet Explorer to the TaskBar
.EXAMPLE
$TargetPath = 'PowerShell.exe'
$ShortCutPath = 'WinDbg.lnk'
$Argument = "-ExecutionPolicy Bypass -NoProfile -NoLogo -Command `"& 'C:\users\proxb\desktop\Windbg.exe'`""
$Icon = 'C:\users\proxb\desktop\Windbg.exe'
New-PinnedItem -TargetPath $TargetPath -ShortCutPath $ShortcutPath -Argument $Argument -Type TaskBar -IconLocation $Icon
Description
-----------
Pins an application that normally couldn't be pinned to the Taskbar by defining a custom
shortcut that is then pinned to the Taskbar.
#>
[cmdletbinding(
DefaultParameterSetName='__DefaultParameterSet'
)]
Param (
[parameter(Position=0,ParameterSetName='AltShortcut')]
[parameter(Position=0,ParameterSetName='__DefaultParameterSet')]
[string]$TargetPath,
[PinnedType]$Type,
[parameter(ParameterSetName='AltShortcut')]
[string]$Argument,
[parameter(ParameterSetName='AltShortcut')]
[string]$IconLocation,
[parameter(ParameterSetName='AltShortcut')]
[ValidateScript({
If ($_ -match '\.lnk|\.url') {
$True
} Else {
Throw "The extension must end in .lnk or .url!"
}
})]
[string]$ShortcutPath,
[parameter(ParameterSetName='AltShortcut')]
[string]$WorkingDirectory
)
Write-Verbose "Creating Shell ComObject"
$Shell = New-Object -ComObject Shell.Application
If ($PSCmdlet.ParameterSetName -eq 'AltShortcut') {
$File = $TargetPath -replace '.*\\(.*)','$1'
$WShell = New-Object -ComObject WScript.Shell
If ($PSBoundParameters.ContainsKey('ShortcutPath')) {
Try {
$ShortcutPath = Convert-Path $ShortcutPath -ErrorAction Stop
} Catch {
$ShortcutPath = Join-Path $PWD $ShortcutPath
}
$Shortcut = $WShell.CreateShortcut($ShortcutPath)
} Else {
$Link = $File -replace '^(.*)?\..*','$1.lnk'
$Shortcut = $WShell.CreateShortcut("$($PWD)\$Link")
}
Write-Verbose "ShortcutPath: $($Shortcut.fullname)"
If ($PSBoundParameters.ContainsKey('IconLocation')) {
$Shortcut.IconLocation = $IconLocation
}
If ($PSBoundParameters.ContainsKey('Argument')) {
$Shortcut.Arguments = $Argument
}
If ($PSBoundParameters.ContainsKey('WorkingDirectory')) {
$Shortcut.WorkingDirectory = $WorkingDirectory
}
$Shortcut.TargetPath = $TargetPath
$Shortcut.Save()
$TargetPath = $Shortcut.Fullname
}
If ($TargetPath -match '^(?<Path>.*\\)(?<File>.*)$') {
$Path = $Matches.Path
$File = $Matches.File
Write-Verbose "Path: $($Path) -- File: $($File)"
$NameSpace = $Shell.NameSpace($Path)
$NameSpaceFile = $NameSpace.ParseName($File)
Switch ($Type) {
'Taskbar' {
$_Verb = ConvertToVerb -Action PintoTaskbar
$Verb = $NameSpaceFile.Verbs() | Where {
$_.Name -eq $_Verb
}
}
'StartMenu' {
$_Verb = ConvertToVerb -Action PintoStartMenu
$Verb = $NameSpaceFile.Verbs() | Where {
$_.Name -eq $_Verb
}
}
}
If ($Verb) {
$Verb.DoIt()
} Else {
Write-Warning "Unable to perform action: Pin $($File) to $($Type)!"
}
} Else {
Write-Warning "Unable to parse File and Path from provided Fullname: $($TargetPath)!"
}
Write-Verbose 'Cleanup ComObject'
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Shell)
If ($PSCmdlet.ParameterSetName -eq 'AltShortcut') {
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$WShell)
}
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable Shell -ErrorAction SilentlyContinue
Remove-Variable WShell -ErrorAction SilentlyContinue
}
|
PowerShellCorpus/PowerShellGallery/PinnedItem/0.2.0.0/Scripts/Get-PinnedItem.ps1
|
Get-PinnedItem.ps1
|
Function Get-PinnedItem {
<#
.SYNOPSIS
Gets pinned items on StartMenu and/or Taskbar
.DESCRIPTION
Gets pinned items on StartMenu and/or Taskbar
.PARAMETER Type
Determine what types of pinned items will be returned.
Acceptable values:
StartMenu
Taskbar
Default is that all items will be returned.
.NOTES
Name: Get-PinnedItem
Author: Boe Prox
Version History
1.0 //Boe Prox - 03 June 2015
- Initial Build
.EXAMPLE
Get-PinnedItem
Description
-----------
Returns all pinned items (StartMenu and Taskbar).
.EXAMPLE
Get-PinnedItem -Type StartMenu
Description
-----------
Returns all pinned StartMenu items.
#>
[cmdletbinding()]
Param(
[parameter()]
[PinnedType[]]$Type
)
$WShell = New-Object -ComObject WScript.Shell
$TypeList = New-Object System.Collections.ArrayList
If (-NOT $PSBoundParameters.ContainsKey('Type')) {
$Type = 'TaskBar','StartMenu'
}
If ($Type -contains "TaskBar") {
Write-Verbose "Pulling pinned Taskbar items"
$Taskbar = "$($Env:AppData)\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"
Try {
Get-ChildItem $TaskBar -Include '*.lnk','*.url' -Recurse -ErrorAction Stop | ForEach {
$Object = New-Object System.File.PSItem.PinnedItem
$Object.Name = $_.fullname -replace '.*\\(.*)\..*','$1'
$Object.FullName = $_.Fullname
$Object.Destination = $wshell.CreateShortcut($_.Fullname).TargetPath
$Object.Type = 'TaskBar'
$Object
}
} Catch {
Write-Warning $_
}
}
If ($Type -contains "StartMenu") {
Write-Verbose "Pulling pinned StartMenu items"
$StartMenu = "$($Env:AppData)\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu"
Try {
Get-ChildItem $StartMenu -Include '*.lnk','*.url' -Recurse -ErrorAction Stop | ForEach {
$Object = New-Object System.File.PSItem.PinnedItem
$Object.Name = $_.fullname -replace '.*\\(.*)\..*','$1'
$Object.FullName = $_.Fullname
$Object.Destination = $wshell.CreateShortcut($_.Fullname).TargetPath
$Object.Type = 'StartMenu'
$Object
}
} Catch {
Write-Warning $_
}
}
Write-Verbose 'Cleanup ComObject'
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$WShell)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable WShell -ErrorAction SilentlyContinue
}
|
PowerShellCorpus/PowerShellGallery/Rivet/0.8.1/Import-Rivet.ps1
|
Import-Rivet.ps1
|
<#
.SYNOPSIS
Imports the Rivet module.
.DESCRIPTION
When writing migrations, it can be helpful to get intellisense. In order to do so, you'll need to import Rivet.
.EXAMPLE
Import-Rivet.ps1
Demonstrates how to import the Rivet module.
#>
[CmdletBinding()]
param(
)
#Requires -Version 4
Set-StrictMode -Version Latest
if( (Get-Module Rivet) )
{
Remove-Module Rivet -Verbose:$false -Confirm:$false -WhatIf:$false
}
Import-Module (Join-Path -Path $PSScriptRoot -ChildPath Rivet.psd1 -Resolve) -Verbose:$false
|
PowerShellCorpus/PowerShellGallery/Rivet/0.8.1/rivet.ps1
|
rivet.ps1
|
<#
.SYNOPSIS
A database migration tool for PowerShell.
.DESCRIPTION
Rivet is a database migration tool for SQL Server. Finally!
This script is the entry point for Rivet. It is used to create a new migration, and apply/revert migrations against a database.
Called without any arguments, Rivet will shows this help topic.
.LINK
about_Rivet
.LINK
about_Rivet_Configuration
.LINK
about_Rivet_Migrations
.EXAMPLE
rivet.ps1 -New 'CreateTableStarships'
Creates a new `CreateTableStarships` migration in all databases.
.EXAMPLE
rivet.ps1 -Push
Applies all migrations.
.EXAMPLE
rivet.ps1 -Push 'CreateTableStarships'
Demonstrates how to apply a named migration. Don't include the timestamp. Wildcards are permitted.
*Be careful with this syntax!* If the named migration(s) depend on other migrations that haven't been run, the migration will fail.
.EXAMPLE
rivet.ps1 -Pop
Reverts the last migration script.
.EXAMPLE
rivet.ps1 -Pop 5
Demonstrates how to revert multiple migrations. The last `-Count` migrations will be popped.
.EXAMPLE
rivet.ps1 -Pop 'AddTable'
Demonstrates how to pop a specific migration. Wildcards supported. Will match either the migration's name or ID.
.EXAMPLE
rivet.ps1 -Redo
Reverts the last migration script, then reapplies its. Equivalent to
rivet.ps1 -Pop
rivet.ps1 -Push
.EXAMPLE
rivet.ps1 -Push -Environment Production
Demonstrates how to migrate databases in a different environment. The `Production` environment should be specified in the `rivet.json` configuration file.
#>
#Requires -Version 3
[CmdletBinding(DefaultParameterSetName='ShowHelp', SupportsShouldProcess=$True)]
param(
[Parameter(Mandatory=$true,ParameterSetName='New')]
[Switch]
# Creates a new migration.
$New,
[Parameter(Mandatory=$true,ParameterSetName='Push')]
[Switch]
# Applies migrations.
$Push,
[Parameter(Mandatory=$true,ParameterSetName='Pop')]
[Parameter(Mandatory=$true,ParameterSetName='PopByCount')]
[Parameter(Mandatory=$true,ParameterSetName='PopByName')]
[Parameter(Mandatory=$true,ParameterSetName='PopAll')]
[Switch]
# Reverts migrations.
$Pop,
[Parameter(Mandatory=$true,ParameterSetName='Redo')]
[Switch]
# Reverts a migration, then re-applies it.
$Redo,
[Parameter(Mandatory=$true,ParameterSetName='New',Position=1)]
[Parameter(ParameterSetName='Push',Position=1)]
[Parameter(Mandatory=$true,ParameterSetName='PopByName',Position=1)]
[ValidateLength(1,241)]
[string[]]
# The name of the migrations to create, push, or pop. Matches against the migration's ID, Name, or file name (without extension). Wildcards permitted.
$Name,
[Parameter(Mandatory=$true,ParameterSetName='PopByCount',Position=1)]
[UInt32]
# The number of migrations to pop. Default is 1.
$Count = 1,
[Parameter(Mandatory=$true,ParameterSetName='PopAll')]
[Switch]
# Pop all migrations
$All,
[Parameter(ParameterSetName='Pop')]
[Parameter(ParameterSetName='PopByCount')]
[Parameter(ParameterSetName='PopByName')]
[Parameter(ParameterSetName='PopAll')]
[Switch]
# Force popping a migration you didn't apply or that is old.
$Force,
[Parameter(ParameterSetName='New',Position=2)]
[Parameter(ParameterSetName='Push')]
[Parameter(ParameterSetName='Pop')]
[Parameter(ParameterSetName='PopByCount')]
[Parameter(ParameterSetName='PopByName')]
[Parameter(ParameterSetName='PopAll')]
[Parameter(ParameterSetName='Redo')]
[string[]]
# The database(s) to migrate. Optional. Will operate on all databases otherwise.
$Database,
[Parameter(ParameterSetName='New')]
[Parameter(ParameterSetName='Push')]
[Parameter(ParameterSetName='Pop')]
[Parameter(ParameterSetName='PopByCount')]
[Parameter(ParameterSetName='PopByName')]
[Parameter(ParameterSetName='PopAll')]
[Parameter(ParameterSetName='Redo')]
[string]
# The environment you're working in. Controls which settings Rivet loads from the `rivet.json` configuration file.
$Environment,
[Parameter(ParameterSetName='New')]
[Parameter(ParameterSetName='Push')]
[Parameter(ParameterSetName='Pop')]
[Parameter(ParameterSetName='PopByCount')]
[Parameter(ParameterSetName='PopByName')]
[Parameter(ParameterSetName='PopAll')]
[Parameter(ParameterSetName='Redo')]
[string]
# The path to the Rivet configuration file. Default behavior is to look in the current directory for a `rivet.json` file. See `about_Rivet_Configuration` for more information.
$ConfigFilePath
)
Set-StrictMode -Version Latest
if( $PSCmdlet.ParameterSetName -eq 'ShowHelp' )
{
Get-Help $PSCommandPath
return
}
& (Join-Path -Path $PSScriptRoot -ChildPath Import-Rivet.ps1 -Resolve)
Invoke-Rivet @PSBoundParameters
exit $error.Count
|
PowerShellCorpus/PowerShellGallery/Rivet/0.8.1/Migrations/00000000000002_RivetIncreaseMigrationName.ps1
|
00000000000002_RivetIncreaseMigrationName.ps1
|
function Push-Migration
{
Update-Table -SchemaName 'rivet' -Name 'Migrations' -UpdateColumn {
nvarchar 'Name' 241 -NotNull
}
Update-Table -SchemaName 'rivet' -Name 'Activity' -UpdateColumn {
nvarchar 'Name' 241 -NotNull
}
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
}
function Pop-Migration
{
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name varchar(50),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name varchar(50),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-Table -SchemaName 'rivet' -Name 'Migrations' -UpdateColumn {
nvarchar 'Name' 50 -NotNull
}
}
|
PowerShellCorpus/PowerShellGallery/Rivet/0.8.1/Migrations/00000000000003_RivetChangeStoredProcedureVarcharParametersToNVarchar.ps1
|
00000000000003_RivetChangeStoredProcedureVarcharParametersToNVarchar.ps1
|
function Push-Migration
{
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name nvarchar(241),
@Who nvarchar(50),
@ComputerName nvarchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name nvarchar(241),
@Who nvarchar(50),
@ComputerName nvarchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
}
function Pop-Migration
{
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.