Search is not available for this dataset
filename
stringlengths 5
114
| module_name
stringlengths 8
67
| content
stringlengths 0
282M
|
---|---|---|
Export-CT365ProdUserToExcel.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
Exports Office 365 production user data to an Excel file.
.DESCRIPTION
The Export-CT365ProdUserToExcel function connects to Microsoft Graph, retrieves user data based on specified filters, and exports the data to an Excel file. It supports filtering by department, limiting the number of users, and an option to exclude license information.
.PARAMETER FilePath
Specifies the path to the Excel file (.xlsx) where the user data will be exported. The directory must exist, and the file must have a .xlsx extension.
.PARAMETER DepartmentFilter
Filters users by their department. If not specified, users from all departments are retrieved.
.PARAMETER UserLimit
Limits the number of users to retrieve. If set to 0 (default), there is no limit.
.PARAMETER NoLicense
If specified, the exported data will not include license information for the users.
.EXAMPLE
Export-CT365ProdUserToExcel -FilePath "C:\Users\Export\Users.xlsx"
Exports all Office 365 production users to the specified Excel file.
.EXAMPLE
Export-CT365ProdUserToExcel -FilePath "C:\Users\Export\DeptUsers.xlsx" -DepartmentFilter "IT"
Exports Office 365 production users from the IT department to the specified Excel file.
.EXAMPLE
Export-CT365ProdUserToExcel -FilePath "C:\Users\Export\Users.xlsx" -UserLimit 100
Exports the first 100 Office 365 production users to the specified Excel file.
.NOTES
Requires the Microsoft.Graph.Authentication, Microsoft.Graph.Users, ImportExcel, and PSFramework modules.
The user executing this script must have permissions to access user data via Microsoft Graph.
.LINK
https://docs.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0
#>
function Export-CT365ProdUserToExcel {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
$extension = [System.IO.Path]::GetExtension($_)
$directory = [System.IO.Path]::GetDirectoryName($_)
if ($extension -ne '.xlsx') {
throw "The file $_ is not an Excel file (.xlsx). Please specify a file with the .xlsx extension."
}
if (-not (Test-Path -Path $directory -PathType Container)) {
throw "The directory $directory does not exist. Please specify a valid directory."
}
return $true
})]
[string]$FilePath,
[Parameter()]
[string]$DepartmentFilter,
[Parameter()]
[int]$UserLimit = 0,
[Parameter()]
[switch]$NoLicense
)
begin {
# Import Required Modules
$ModulesToImport = "Microsoft.Graph.Authentication", "Microsoft.Graph.Users", "ImportExcel", "PSFramework"
Import-Module $ModulesToImport
Write-PSFMessage -Level Output -Message "Creating or Merging workbook at $FilePath"
}
process {
# Authenticate to Microsoft Graph
$Scopes = @("User.Read.All")
$Context = Get-MgContext
if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) {
Connect-MGGraph -Scopes $Scopes
}
# Build the user retrieval command
$getMgUserSplat = @{
Property = 'GivenName', 'SurName', 'UserPrincipalName',
'DisplayName', 'MailNickname', 'JobTitle',
'Department', 'StreetAddress', 'City',
'State', 'PostalCode', 'Country',
'BusinessPhones', 'MobilePhone', 'FaxNumber', 'UsageLocation',
'CompanyName', 'EmployeeHireDate', 'EmployeeId', 'EmployeeType'
}
if (-not [string]::IsNullOrEmpty($DepartmentFilter)) {
$getMgUserSplat['Filter'] = "Department eq '$DepartmentFilter'"
}
if ($UserLimit -gt 0) {
$getMgUserSplat['Top'] = $UserLimit
}
else {
$getMgUserSplat['All'] = $true
}
$selectProperties = @{
Property = @(
@{Name = 'FirstName'; Expression = { $_.GivenName } },
@{Name = 'LastName'; Expression = { $_.SurName } },
@{Name = 'UserName'; Expression = { $_.UserPrincipalName -replace '@.*' } },
@{Name = 'Title'; Expression = { $_.JobTitle } },
'Department', 'StreetAddress', 'City', 'State', 'PostalCode', 'Country',
@{Name = 'PhoneNumber'; Expression = { $_.BusinessPhones } },
'MobilePhone', 'FaxNumber', 'UsageLocation', 'CompanyName',
'EmployeeHireDate', 'EmployeeId', 'EmployeeType',
@{Name = 'License'; Expression = { if ($NoLicense) { "" } else { "DEVELOPERPACK_E5" } } }
)
}
$userCommand = Get-MgUser @getMgUserSplat | Select-Object @selectProperties
# Fetch and export users to Excel
$userCommand | Export-Excel -Path $FilePath -WorksheetName "Users" -AutoSize
# Disconnect from Microsoft Graph
if (-not [string]::IsNullOrEmpty($(Get-MgContext))) {
Disconnect-MgGraph
}
}
end {
Write-PSFMessage -Level Output -Message "Export completed. Check the file at $FilePath for the user details."
}
}
|
New-CT365User.Tests.ps1 | 365AutomatedLab-2.11.0 | BeforeAll {
# Call Cmdlet
$commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\New-CT365User.ps1'
. $commandScriptPath
}
Describe 'New-CT365User Function' {
Context 'When provided invalid parameters' {
It 'Should throw an error for invalid domain format' {
$filePath = $commandScriptPath
$domain = "invalid_domain"
{ New-CT365User -FilePath $filePath -Domain $domain } | Should -Throw
}
It 'Should throw an error for invalid file path' {
$filePath = "C:\Invalid\Path\file.xlsx"
$domain = "contoso.com"
{ New-CT365User -FilePath $filePath -Domain $domain } | Should -Throw
}
}
} |
Copy-WorksheetName.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
This function copies the names of all the worksheets in an Excel file and exports them into a CSV file.
.DESCRIPTION
The function Copy-WorksheetName takes two parameters, the file path of the Excel file and the output path of the CSV file. It reads the Excel file, extracts the names of all worksheets, and exports these names into a CSV file.
.PARAMETER FilePath
The path to the Excel file. This is a mandatory parameter and it accepts pipeline input.
.PARAMETER outputCsvPath
The path where the CSV file will be created. This is a mandatory parameter and it accepts pipeline input.
.EXAMPLE
Copy-WorksheetName -FilePath "C:\path\to\your\excel\file.xlsx" -outputCsvPath "C:\path\to\your\output\file.csv"
This will read the Excel file located at "C:\path\to\your\excel\file.xlsx", get the names of all worksheets, and export these names to a CSV file at "C:\path\to\your\output\file.csv".
.NOTES
This function requires the ImportExcel module to be installed. If not already installed, you can install it by running Install-Module -Name ImportExcel.
.INPUTS
System.String. You can pipe a string that contains the file path to this cmdlet.
.OUTPUTS
System.String. This cmdlet outputs a CSV file containing the names of all worksheets in the Excel file.
.LINK
https://github.com/dfinke/ImportExcel
#>
function Copy-WorksheetName {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]$FilePath,
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]$outputCsvPath
)
if (!(Test-Path $FilePath)) {
Write-PSFMessage -Level Error -Message "Excel file not found at the specified path: $FilePath" -Target $FilePath
return
}
Import-Module ImportExcel
Import-Module PSFramework
# Import Excel file
$excel = Import-excel -ExcelPackage $FilePath
'"'+((Get-ExcelFileSummary $excel).WorksheetName -join '","')+'"' | Export-Csv -Path $outputCsvPath
} |
New-CT365Group.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
This function creates Office 365 Groups, Distribution Groups, Mail-Enabled Security Groups, and Security Groups based on the data provided in an Excel file.
.DESCRIPTION
The function New-CT365Group takes the path of an Excel file, User Principal Name and a Domain as input. It creates Office 365 Groups, Distribution Groups, Mail-Enabled Security Groups, and Security Groups based on the data found in the Excel file. If a group already exists, the function will output a message and skip the creation of that group.
.PARAMETER FilePath
The full path to the Excel file(.xlsx) containing the data for the groups to be created. The Excel file should have a worksheet named "Groups". Each row in this worksheet should represent a group to be created. The columns in the worksheet should include the DisplayName, Type (365Group, 365Distribution, 365MailEnabledSecurity, 365Security), PrimarySMTP (without domain), and Description of the group.
.PARAMETER UserPrincipalName
The User Principal Name (UPN) used to connect to Exchange Online.
.PARAMETER Domain
The domain to be appended to the PrimarySMTP of each group to form the email address of the group.
.EXAMPLE
New-CT365Group -FilePath "C:\Path\to\file.xlsx" -UserPrincialName "[email protected]" -Domain "domain.com"
This will read the Excel file "file.xlsx" located at "C:\Path\to\", use "[email protected]" to connect to Exchange Online, and append "@domain.com" to the PrimarySMTP of each group to form the email address of the group.
.INPUTS
System.String
.OUTPUTS
System.String
The function outputs strings informing about the creation of the groups or if the groups already exist.
.NOTES
The function uses the ExchangeOnlineManagement and Microsoft.Graph.Groups modules to interact with Office 365. Make sure these modules are installed before running the function.
.LINK
Get-UnifiedGroup
.LINK
New-UnifiedGroup
.LINK
Get-DistributionGroup
.LINK
New-DistributionGroup
.LINK
Get-MgGroup
.LINK
New-MgGroup
#>
function New-CT365Group {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# First, check if the file has a valid Excel extension (.xlsx)
if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) {
throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again."
}
# Then, check if the file exists
if (-not([System.IO.File]::Exists($psitem))) {
throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)."
}
# Return true if both conditions are met
$true
})]
[string]$FilePath,
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]$UserPrincipalName,
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# Check if the domain fits the pattern
switch ($psitem) {
{ $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } {
throw "The provided domain is not in the correct format."
}
Default {
$true
}
}
})]
[string]$Domain
)
# Import the required modules
$ModulesToImport = "ImportExcel", "Microsoft.Graph.Groups", "PSFramework", "ExchangeOnlineManagement"
Import-Module $ModulesToImport
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName -ShowProgress $true
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Group.ReadWrite.All", "User.Read.All"
# Import data from Excel
$groups = Import-Excel -Path $FilePath -WorksheetName Groups
foreach ($group in $groups) {
# Append the domain to the PrimarySMTP
$group.PrimarySMTP += "@$Domain"
if (-not [string]::IsNullOrEmpty($group.ManagedBy)) {
$group.ManagedBy += "@$Domain"
}
switch -Regex ($group.Type) {
"^365Group$" {
try {
Write-PSFMessage -Level Output -Message "Creating 365 Group: $($group.DisplayName)" -Target $Group.DisplayName
Get-UnifiedGroup -Identity $group.DisplayName -ErrorAction Stop
Write-PSFMessage -Level Warning -Message "365 Group: $($group.DisplayName) already exists" -Target $Group.DisplayName
}
catch {
$ManagedBy = $group.ManagedBy
if ([string]::IsNullOrEmpty($ManagedBy)) {
$ManagedBy = $UserPrincipalName
}
New-UnifiedGroup -DisplayName $group.DisplayName -PrimarySMTPAddress $group.PrimarySMTP -AccessType Private -Notes $group.Description -RequireSenderAuthenticationEnabled $False -Owner $ManagedBy
Write-PSFMessage -Level Output -Message "Created 365 Group: $($Group.DisplayName) successfully" -Target $Group.DisplayName
}
}
"^365Distribution$" {
try {
Write-PSFMessage -Level Output -Message "Creating 365 Distribution Group: $($group.DisplayName)" -Target $Group.DisplayName
Get-DistributionGroup -Identity $group.DisplayName -ErrorAction Stop
Write-PSFMessage -Level Warning -Message "365 Distribution Group $($group.DisplayName) already exists" -Target $Group.DisplayName
}
catch {
$ManagedBy = $group.ManagedBy
if ([string]::IsNullOrEmpty($ManagedBy)) {
$ManagedBy = $UserPrincipalName
}
New-DistributionGroup -Name $group.DisplayName -DisplayName $($group.DisplayName) -PrimarySMTPAddress $group.PrimarySMTP -Description $group.Description -ManagedBy $ManagedBy -RequireSenderAuthenticationEnabled $False
Write-PSFMessage -Level Output -Message "Created 365 Distribution Group: $($group.DisplayName)" -Target $Group.DisplayName
}
}
"^365MailEnabledSecurity$" {
try {
Write-PSFMessage -Level Output -Message "Creating 365 Mail-Enabled Security Group: $($group.DisplayName)" -Target $Group.DisplayName
Get-DistributionGroup -Identity $group.DisplayName -ErrorAction Stop
Write-PSFMessage -Level Warning -Message "365 Mail-Enabled Security Group: $($group.DisplayName) already exists" -Target $Group.DisplayName
}
catch {
$ManagedBy = $group.ManagedBy
if ([string]::IsNullOrEmpty($ManagedBy)) {
$ManagedBy = $UserPrincipalName
}
New-DistributionGroup -Name $group.DisplayName -PrimarySMTPAddress $group.PrimarySMTP -Type "Security" -Description $group.Description -ManagedBy $ManagedBy -RequireSenderAuthenticationEnabled $False
Write-PSFMessage -Level Output -Message "Created 365 Mail-Enabled Security Group: $($group.DisplayName)" -Target $Group.DisplayName
}
}
"^365Security$" {
Write-PSFMessage -Level Output -Message "Creating 365 Security Group: $($group.DisplayName)" -Target $Group.DisplayName
$ExistingGroup = Get-MgGroup -Filter "DisplayName eq '$($group.DisplayName)'"
if ($ExistingGroup) {
Write-PSFMessage -Level Warning -Message "365 Security Group: $($group.DisplayName) already exists" -Target $Group.DisplayName
continue
}
$ManagedBy = $group.ManagedBy
if ([string]::IsNullOrEmpty($ManagedBy)) {
$ManagedBy = $UserPrincipalName
}
$GroupOwner = Get-MgUser -Filter "UserPrincipalName eq '$ManagedBy'"
if ($null -eq $GroupOwner) {
Write-PSFMessage -Level Error -Message "User with UserPrincipalName '$ManagedBy' not found"
continue
}
$mailNickname = $group.PrimarySMTP.Split('@')[0]
New-MgGroup -DisplayName $group.DisplayName -Description $group.Description -MailNickName $mailNickname -SecurityEnabled:$true -MailEnabled:$false
$365group = Get-MgGroup -Filter "DisplayName eq '$($group.DisplayName)'"
New-MgGroupOwner -GroupId $365group.Id -DirectoryObjectId $GroupOwner.Id
Write-PSFMessage -Level Output -Message "Created 365 Security Group: $($group.DisplayName)" -Target $Group.DisplayName
}
default {
Write-PSFMessage -Level Error -Message "Invalid group type for $($group.DisplayName)" -Target $Group.DisplayName
}
}
}
# Disconnect Exchange Online and Microsoft Graph sessions
Disconnect-ExchangeOnline -Confirm:$false
Disconnect-MgGraph
} |
Remove-CT365GroupByUserRole.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
Removes a user from Office 365 groups as specified in an Excel file.
.DESCRIPTION
This function removes a user from different types of Office 365 groups as specified in an Excel file.
The function uses the ExchangeOnlineManagement, ImportExcel, Microsoft.Graph.Groups, and Microsoft.Graph.Users modules.
The function first connects to Exchange Online and Microsoft Graph using the UserPrincipalName provided.
It then imports data from an Excel file and iterates through each row. For each row, it removes the user from the group based on the group type.
.PARAMETER FilePath
This mandatory parameter specifies the path to the Excel file which contains information about the groups from which the user should be removed.
.PARAMETER UserEmail
This mandatory parameter specifies the email of the user who should be removed from the groups.
.PARAMETER Domain
This mandatory parameter specifies the domain of the user. The domain is used to construct the group name.
.PARAMETER UserRole
This mandatory parameter specifies the user's role. It should be either "NY-IT" or "NY-HR". This parameter is used to identify the worksheet in the Excel file to import.
.EXAMPLE
Remove-CT365GroupByUserRole -FilePath "C:\Path\to\file.xlsx" -UserEmail "[email protected]" -Domain "example.com" -UserRole "NY-IT"
This example removes the user "[email protected]" from the groups specified in the "NY-IT" worksheet of the Excel file at "C:\Path\to\file.xlsx".
.NOTES
The Excel file should have columns for PrimarySMTP, GroupType, and DisplayName. These columns are used to get information about the groups from which the user should be removed.
The function supports the following group types: 365Group, 365Distribution, 365MailEnabledSecurity, and 365Security. For each group type, it uses a different cmdlet to remove the user from the group.
Connect-MgGraph -Scopes "Group.ReadWrite.All","Directory.AccessAsUser.All" - is needed to connect with correct scopes
.LINK
https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.groups/?view=graph-powershell-1.0
.LINK
https://www.powershellgallery.com/packages/ImportExcel
#>
function Remove-CT365GroupByUserRole {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# First, check if the file has a valid Excel extension (.xlsx)
if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) {
throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again."
}
# Then, check if the file exists
if (-not([System.IO.File]::Exists($psitem))) {
throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)."
}
# Return true if both conditions are met
$true
})]
[string]$FilePath,
[Parameter(Mandatory)]
[ValidateScript({
# Check if the email fits the pattern
switch ($psitem) {
{ $psitem -notmatch "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" } {
throw "The provided email is not in the correct format."
}
Default {
$true
}
}
})]
[string]$UserEmail,
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# Check if the domain fits the pattern
switch ($psitem) {
{ $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } {
throw "The provided domain is not in the correct format."
}
Default {
$true
}
}
})]
[string]$Domain,
[Parameter(Mandatory)]
[string]$UserRole
)
# Import Required Modules
$ModulesToImport = "ImportExcel", "Microsoft.Graph.Groups", "Microsoft.Graph.Users", "PSFramework", "ExchangeOnlineManagement"
Import-Module $ModulesToImport
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName -ShowProgress $true
# Connect to Microsoft Graph
$Scopes = @("Group.ReadWrite.All", "Directory.AccessAsUser.All")
$Context = Get-MgContext
if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) {
Connect-MGGraph -Scopes $Scopes
}
$excelData = Import-Excel -Path $FilePath -WorksheetName $UserRole
if ($PSCmdlet.ShouldProcess("Remove user from groups from Excel file")) {
foreach ($row in $excelData) {
$GroupName = $row.PrimarySMTP += "@$domain"
$GroupType = $row.Type
$DisplayName = $row.DisplayName
if ($PSCmdlet.ShouldProcess("Remove user $UserEmail from $GroupType group $GroupName")) {
try {
Write-PSFMessage -Level Output -Message "Removing $UserEmail from $($GroupType):'$GroupName'" -Target $UserEmail
switch -Regex ($GroupType) {
"^365Group$" {
Remove-UnifiedGroupLinks -Identity $GroupName -LinkType "Members" -Links $UserEmail -Confirm:$false
}
"^(365Distribution|365MailEnabledSecurity)$" {
Remove-DistributionGroupMember -Identity $GroupName -Member $UserEmail -Confirm:$false
}
"^365Security$" {
$user = Get-MgUser -Filter "userPrincipalName eq '$UserEmail'"
$ExistingGroup = Get-MgGroup -Filter "DisplayName eq '$($DisplayName)'"
if ($ExistingGroup) {
Remove-MgGroupMemberByRef -GroupId $ExistingGroup.Id -DirectoryObjectId $User.Id
Write-PSFMessage -Level Output -Message "User $UserEmail successfully removed from $GroupType group $GroupName" -Target $UserEmail
}
else {
Write-PSFMessage -Level Warning -Message "No group found with the name: $GroupName" -Target $GroupName
}
}
default {
Write-PSFMessage -Level Warning -Message "Unknown group type: $GroupType" -Target $GroupType
}
}
Write-PSFMessage -Level Output -Message "Removed $UserEmail from $($GroupType):'$GroupName' sucessfully" -Target $UserEmail
}
catch {
Write-PSFMessage -Level Error -Message "$($_.Exception.Message) - Error removing user $UserEmail from $($GroupType):'$GroupName'" -Target $UserEmail
}
}
}
}
# Disconnect Exchange Online and Microsoft Graph sessions
Disconnect-ExchangeOnline -Confirm:$false
if (-not [string]::IsNullOrEmpty($(Get-MgContext))) {
Disconnect-MgGraph
}
} |
Remove-CT365SharePointSite.Tests.ps1 | 365AutomatedLab-2.11.0 | BeforeAll {
# Call Cmdlet
$commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365SharePointSite.ps1'
. $commandScriptPath
}
Describe 'Remove-CT365SharePointSite Function' {
Context 'When provided invalid parameters' {
It 'Should throw an error for invalid domain format' {
$filePath = $commandScriptPath
$domain = "invalid_domain"
{ Remove-CT365SharePointSite -FilePath $filePath -Domain $domain } | Should -Throw
}
It 'Should throw an error for invalid file path' {
$filePath = "C:\Invalid\Path\file.xlsx"
$domain = "contoso.com"
{ Remove-CT365SharePointSite -FilePath $filePath -Domain $domain } | Should -Throw
}
}
} |
New-CT365GroupByUserRole.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
This function adds a user to Microsoft 365 groups based on a provided Excel file.
.DESCRIPTION
The New-CT365GroupByUserRole function uses Microsoft Graph and Exchange Online Management modules to add a user to different types of Microsoft 365 groups. The group details are read from an Excel file. The group's SMTP, type, and display name are extracted from the Excel file and used to add the user to the group.
.PARAMETER FilePath
The path to the Excel file that contains the groups to which the user should be added. The file must contain a worksheet named as per the user role ("NY-IT" or "NY-HR"). The worksheet should contain details about the groups including the primary SMTP, group type, and display name.
.PARAMETER UserEmail
The email of the user to be added to the groups specified in the Excel file.
.PARAMETER Domain
The domain that is appended to the primary SMTP to form the group's email address.
.PARAMETER UserRole
The role of the user, which is also the name of the worksheet in the Excel file that contains the groups to which the user should be added. The possible values are "NY-IT" and "NY-HR".
.EXAMPLE
New-CT365GroupByUserRole -FilePath "C:\Users\Username\Documents\Groups.xlsx" -UserEmail "[email protected]" -Domain "example.com" -UserRole "NY-IT"
This command reads the groups from the "NY-IT" worksheet in the Groups.xlsx file and adds the user "[email protected]" to those groups.
.NOTES
This function requires the ExchangeOnlineManagement, ImportExcel, PSFramwork, and Microsoft.Graph.Groups modules to be installed. It will import these modules at the start of the function. The function connects to Exchange Online and Microsoft Graph, and it will disconnect from them at the end of the function.
#>
function New-CT365GroupByUserRole {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# First, check if the file has a valid Excel extension (.xlsx)
if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) {
throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again."
}
# Then, check if the file exists
if (-not([System.IO.File]::Exists($psitem))) {
throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)."
}
# Return true if both conditions are met
$true
})]
[string]$FilePath,
[Parameter(Mandatory)]
[ValidateScript({
# Check if the email fits the pattern
switch ($psitem) {
{ $psitem -notmatch "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" } {
throw "The provided email is not in the correct format."
}
Default {
$true
}
}
})]
[string]$UserEmail,
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# Check if the domain fits the pattern
switch ($psitem) {
{ $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } {
throw "The provided domain is not in the correct format."
}
Default {
$true
}
}
})]
[string]$Domain,
[Parameter(Mandatory)]
[string]$UserRole
)
# Import Required Modules
$ModulesToImport = "ImportExcel", "Microsoft.Graph.Groups", "PSFramework", "ExchangeOnlineManagement"
Import-Module $ModulesToImport
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName -ShowProgress $true
# Connect to Microsoft Graph
$Scopes = @("Group.ReadWrite.All")
$Context = Get-MgContext
if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) {
Connect-MGGraph -Scopes $Scopes
}
$excelData = Import-Excel -Path $FilePath -WorksheetName $UserRole
if ($PSCmdlet.ShouldProcess("Add user to groups from Excel file")) {
foreach ($row in $excelData) {
$GroupName = $row.PrimarySMTP += "@$domain"
$GroupType = $row.Type
$DisplayName = $row.DisplayName
if ($PSCmdlet.ShouldProcess("Add user $UserEmail to $GroupType group $GroupName")) {
try {
Write-PSFMessage -Level Output -Message "Adding $UserEmail to $($GroupType):'$GroupName'" -Target $UserEmail
switch -Regex ($GroupType) {
"^365Group$" {
Add-UnifiedGroupLinks -Identity $GroupName -LinkType Members -Links $UserEmail -ErrorAction Stop
}
"^(365Distribution|365MailEnabledSecurity)$" {
Add-DistributionGroupMember -Identity $GroupName -Member $UserEmail -Erroraction Stop
}
"^365Security$" {
$user = Get-MgUser -Filter "userPrincipalName eq '$UserEmail'"
$ExistingGroup = Get-MgGroup -Filter "DisplayName eq '$($DisplayName)'"
if ($ExistingGroup) {
New-MgGroupMember -GroupId $ExistingGroup.Id -DirectoryObjectId $User.Id -ErrorAction Stop
Write-PSFMessage -Level Output -Message "User $UserEmail successfully added to $GroupType group $GroupName" -Target $UserEmail
}
else {
Write-PSFMessage -Level Warning -Message "No group found with the name: $GroupName" -Target $GroupName
}
}
default {
Write-PSFMessage -Level Warning -Message "Unknown group type: $GroupType" -Target $GroupType
}
}
Write-PSFMessage -Level Output -Message "Added $UserEmail to $($GroupType):'$GroupName' sucessfully" -Target $UserEmail
}
catch {
Write-PSFMessage -Level Error -Message "$($_.Exception.Message) - Error adding $UserEmail to $($GroupType):'$GroupName'" -Target $UserEmail
}
}
}
}
# Disconnect Exchange Online and Microsoft Graph sessions
Disconnect-ExchangeOnline -Confirm:$false
if (-not [string]::IsNullOrEmpty($(Get-MgContext))) {
Disconnect-MgGraph
}
} |
New-CT365DataEnvironment.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
Creates a new Office 365 data environment template in an Excel workbook.
.DESCRIPTION
The New-CT365DataEnvironment function creates a new Excel workbook with multiple worksheets
for Users, Groups, Teams, Sites, and specified Job Roles. Each worksheet is formatted
with predefined columns relevant to its content.
.PARAMETER FilePath
Specifies the path to the Excel file (.xlsx) where the data environment will be created.
The function checks if the file already exists, if it's a valid .xlsx file, and if the
folder path exists.
.PARAMETER JobRole
An array of job roles to create individual worksheets for each role in the Excel workbook.
Each job role will have a worksheet with predefined columns.
.EXAMPLE
PS> New-CT365DataEnvironment -FilePath "C:\Data\O365Environment.xlsx" -JobRole "HR", "IT"
This command creates an Excel workbook at the specified path with worksheets for Users,
Groups, Teams, Sites, and additional worksheets for 'HR' and 'IT' job roles.
.EXAMPLE
PS> New-CT365DataEnvironment -FilePath "C:\Data\NewEnvironment.xlsx" -JobRole "Finance"
This command creates an Excel workbook at the specified path with a worksheet for the
'Finance' job role, along with the standard Users, Groups, Teams, and Sites worksheets.
.INPUTS
None. You cannot pipe objects to New-CT365DataEnvironment.
.OUTPUTS
None. This function does not generate any output.
.NOTES
Requires the modules ImportExcel and PSFramework to be installed.
.LINK
https://www.powershellgallery.com/packages/ImportExcel
https://www.powershellgallery.com/packages/PSFramework
#>
function New-CT365DataEnvironment {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
if (Test-Path -Path $_ -PathType Leaf) {
throw "File $_ already exists, please provide a new file path"
}
if (-not $_ -match '^.*\.(xlsx)$') {
throw "File path $_ is not a valid .xlsx file, please provide a valid .xlsx file path"
}
if (-not (Test-Path -Path (Split-Path $_) -PathType Container)) {
throw "Folder path for $_ does not exist, please confirm path does exist"
}
return $true
})]
[string]$FilePath,
[Parameter(Mandatory)]
[string[]]$JobRole
)
begin {
# Import Required Modules
$ModulesToImport = "ImportExcel", "PSFramework"
Import-Module $ModulesToImport
Write-PSFMessage -Level Output -Message "Creating workbook at $FilePath"
# Helper function
function New-EmptyCustomObject {
param (
[string[]]$PropertyNames
)
$customObject = [PSCustomObject]@{}
$customObject | Select-Object -Property $PropertyNames
}
}
process {
# Define properties for custom objects
$propertyDefinitions = @{
Users = @(
"FirstName", "LastName", "UserName", "Title", "Department",
"StreetAddress", "City", "State", "PostalCode", "Country",
"PhoneNumber", "MobilePhone", "FaxNumber", "UsageLocation", "CompanyName", "EmployeeHireDate", "EmployeeId", "EmployeeType", "License"
)
Groups = @(
"DisplayName", "PrimarySMTP", "Description", "Type"
)
JobRole = @(
"DisplayName", "PrimarySMTP", "Description", "Type"
)
Teams = @(
"TeamName", "TeamDescription", "TeamType", "Channel1Name", "Channel1Description", "Channel1Type", "Channel2Name", "Channel2Description", "Channel2Type"
)
Sites = @(
"Url", "Template", "TimeZone", "Title", "Alias", "SiteType"
)
}
# Define custom objects for each worksheet
$usersObject = New-EmptyCustomObject -PropertyNames $propertyDefinitions.Users
$groupsObject = New-EmptyCustomObject -PropertyNames $propertyDefinitions.Groups
$teamsObject = New-EmptyCustomObject -PropertyNames $propertyDefinitions.Teams
$sitesObject = New-EmptyCustomObject -PropertyNames $propertyDefinitions.Sites
# Export each worksheet to the workbook
$usersObject | Export-Excel -Path $FilePath -WorksheetName "Users" -ClearSheet -AutoSize
$groupsObject | Export-Excel -Path $FilePath -WorksheetName "Groups" -Append -AutoSize
$teamsObject | Export-Excel -Path $FilePath -WorksheetName "Teams" -Append -AutoSize
$sitesObject | Export-Excel -Path $FilePath -WorksheetName "Sites" -Append -AutoSize
foreach ($JobRoleItem in $JobRole) {
$RoleObject = New-EmptyCustomObject -PropertyNames $propertyDefinitions.JobRole
$RoleObject | Export-Excel -Path $FilePath -WorksheetName $JobRoleItem -Append -AutoSize
}
}
end {
Write-PSFMessage -Level Output -Message "Workbook created successfully at $FilePath"
}
}
|
New-CT365Teams.ps1 | 365AutomatedLab-2.11.0 | <#
.SYNOPSIS
Creates new Microsoft Teams and associated channels based on data from an Excel file.
.DESCRIPTION
The New-CT365Teams function connects to Microsoft Teams via PnP PowerShell, reads team and channel information from an Excel file, and creates new Teams and channels as specified. It supports retry logic for team and channel creation and allows specifying a default owner. The function requires the PnP.PowerShell, ImportExcel, and PSFramework modules.
.PARAMETER FilePath
Specifies the path to the Excel file containing the Teams and channel data. The file must be in .xlsx format.
.PARAMETER AdminUrl
Specifies the SharePoint admin URL for the tenant. The URL must match the format 'tenant.sharepoint.com'.
.PARAMETER DefaultOwnerUPN
Specifies the default owner's User Principal Name (UPN) for the Teams and channels.
.EXAMPLE
PS> New-CT365Teams -FilePath "C:\TeamsData.xlsx" -AdminUrl "contoso.sharepoint.com" -DefaultOwnerUPN "[email protected]"
This example creates Teams and channels based on the data in 'C:\TeamsData.xlsx', using '[email protected]' as the default owner if none is specified in the Excel file.
.NOTES
- Requires the PnP.PowerShell, ImportExcel, and PSFramework modules.
- The Excel file should have a worksheet named 'teams' with appropriate columns for team and channel data.
- The function includes error handling and logging using PSFramework.
#>
function New-CT365Teams {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateScript({
# First, check if the file has a valid Excel extension (.xlsx)
if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) {
throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again."
}
# Then, check if the file exists
if (-not([System.IO.File]::Exists($psitem))) {
throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)."
}
# Return true if both conditions are met
$true
})]
[string]$FilePath,
[Parameter(Mandatory)]
[ValidateScript({
if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') {
$true
}
else {
throw "The URL $_ does not match the required format."
}
})]
[string]$AdminUrl,
[Parameter(Mandatory)]
[string]$DefaultOwnerUPN
)
# Check and import required modules
$requiredModules = @('PnP.PowerShell', 'ImportExcel', 'PSFramework')
foreach ($module in $requiredModules) {
try {
if (-not (Get-Module -ListAvailable -Name $module)) {
throw "Module $module is not installed."
}
Import-Module $module
}
catch {
Write-PSFMessage -Level Warning -Message "[$(Get-Date -Format 'u')] $_.Exception.Message"
return
}
}
try {
$teamsData = Import-Excel -Path $FilePath -WorksheetName "teams"
$existingTeams = Get-PnPTeamsTeam
}
catch {
Write-PSFMessage -Level Error -Message "[$(Get-Date -Format 'u')] Failed to import data from Excel or retrieve existing teams: $($_.Exception.Message)"
return
}
foreach ($teamRow in $teamsData) {
try {
$teamOwnerUPN = if ($teamRow.TeamOwnerUPN) { $teamRow.TeamOwnerUPN } else { $DefaultOwnerUPN }
$existingTeam = $existingTeams | Where-Object { $_.DisplayName -eq $teamRow.TeamName }
if ($existingTeam) {
Write-PSFMessage -Level Host -Message "[$(Get-Date -Format 'u')] Team $($teamRow.TeamName) already exists. Skipping creation."
continue
}
$retryCount = 0
$teamCreationSuccess = $false
do {
try {
$teamId = New-PnPTeamsTeam -DisplayName $teamRow.TeamName -Description $teamRow.TeamDescription -Visibility $teamRow.TeamType -Owners $teamOwnerUPN
if (Verify-CT365TeamsCreation -teamName $teamRow.TeamName) {
Write-PSFMessage -Level Host -Message "[$(Get-Date -Format 'u')] Verified creation of Team: $($teamRow.TeamName)"
$teamCreationSuccess = $true
break
}
else {
Write-PSFMessage -Level Warning -Message "[$(Get-Date -Format 'u')] Team $($teamRow.TeamName) creation reported but not verified. Retrying..."
}
}
catch {
Write-PSFMessage -Level Warning -Message "[$(Get-Date -Format 'u')] Attempt $retryCount to create team $($teamRow.TeamName) failed: $($_.Exception.Message)"
}
$retryCount++
Start-Sleep -Seconds 5
} while ($retryCount -lt 5)
if (-not $teamCreationSuccess) {
Write-PSFMessage -Level Error -Message "[$(Get-Date -Format 'u')] Failed to create and verify Team: $($teamRow.TeamName) after multiple retries."
continue
}
for ($i = 1; $i -le 4; $i++) {
$channelName = $teamRow."Channel${i}Name"
$channelType = $teamRow."Channel${i}Type"
$channelDescription = $teamRow."Channel${i}Description"
$channelOwnerUPN = if ($teamRow."Channel${i}OwnerUPN") { $teamRow."Channel${i}OwnerUPN" } else { $DefaultOwnerUPN }
if ($channelName -and $channelType) {
$retryCount = 1
$channelCreationSuccess = $false
do {
try {
Add-PnPTeamsChannel -Team $teamId -DisplayName $channelName -Description $channelDescription -ChannelType $channelType -OwnerUPN $channelOwnerUPN
Write-PSFMessage -Level Host -Message "[$(Get-Date -Format 'u')] Created Channel: $channelName in Team: $($teamRow.TeamName) with Type: $channelType and Description: $channelDescription"
$channelCreationSuccess = $true
break
}
catch {
Write-PSFMessage -Level Warning -Message "[$(Get-Date -Format 'u')] Attempt $retryCount to create channel $channelName in Team: $($teamRow.TeamName) failed: $($_.Exception.Message)"
$retryCount++
Start-Sleep -Seconds 10
}
} while ($retryCount -lt 5)
if (-not $channelCreationSuccess) {
Write-PSFMessage -Level Error -Message "[$(Get-Date -Format 'u')] Failed to create Channel: $channelName in Team: $($teamRow.TeamName) after multiple retries."
}
}
}
}
catch {
Write-PSFMessage -Level Error -Message "[$(Get-Date -Format 'u')] Error processing team $($teamRow.TeamName): $($_.Exception.Message)"
}
}
try {
Disconnect-PnPOnline
}
catch {
Write-PSFMessage -Level Error -Message "[$(Get-Date -Format 'u')] Error disconnecting PnP Online: $($_.Exception.Message)"
}
}
|
get-msolipranges.ps1 | 365Tools-3.1.0 | function Get-MSOLIPRanges {
<#
.SYNOPSIS
Finds IP range for given O365 Products to create firewall rules.
.DESCRIPTION
Finds IP range for given O365 Products to create firewall rules.
.PARAMETER IPType
Select which IP type you want to find the ranges for.
Possible options are IPv4 and IPv6, default is IPv4.
.EXAMPLE
Get-MSOLIPRanges
#>
[cmdletbinding()]
param(
[Parameter(Position = 0)]
[ValidateSet('IPv4', 'IPv6')]
[string]$IPType = 'IPv4'
)
$Office365IPsXml = New-Object System.Xml.XmlDocument
$Office365IPsXml.Load("https://support.content.office.net/en-us/static/O365IPAddresses.xml")
$updated = $Office365IPsXml.products.updated
Write-Output "Last updated: $updated"
[array]$Products = $Office365IPsXml.products.product | Sort-Object Name | Out-GridView -PassThru -Title 'Select Product(s)'
foreach ($Product in $Products) {
$IPRanges = ($Product | Select-Object -ExpandProperty Addresslist | Where-Object {$_.Type -eq $IPType}) | Where-Object {$_.address -ne $null} | Select-Object -ExpandProperty address
foreach ($Range in $IPRanges) {
$ProductIPRange = New-Object -TypeName PSObject -Property @{
'Product' = $Product.Name;
'IPRange' = $Range;
}
Write-Output $ProductIPRange | Select-Object Product, IPRange
}
}
} |
New-MSOLReport.ps1 | 365Tools-3.1.0 | function New-MSOLReport
{
<#
.SYNOPSIS
Creates a CSV-file with user data from Office 365
.DESCRIPTION
This function creates a CSV-file with user data fetched from Office 365, such as licensing status, mailbox size, etc.
.EXAMPLE
New-MSOLReport -outfile c:\temp\somefile.csv
.EXAMPLE
New-MSOLReport -outfile c:\temp\somefile.csv -Verbose
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true, Position=0)]
[string]
$outfile
)
$outpath = split-path $outfile
if (!(test-path $outpath)) {new-item $outpath -ItemType Directory}
if (!(get-module msonline)) {open-msolconnection}
Write-Progress -Id 1 -Activity "Generating MSOL Report" -Status "Starting Inital Query" -PercentComplete 0
$arrResults = @()
$starttime = (get-date)
$users = get-msoluser
$total = ($users).count
write-verbose "Getting $total mailboxes"
Write-Progress -Id 1 -Status "Getting $total mailboxes" -PercentComplete 10 -Activity "Generating MSOL Report"
$mbx = get-mailbox
Write-Verbose "Getting mailbox statistics for $total mailboxes. This might take some time."
Write-Progress -Id 1 -Status "Getting Statistics for $total mailboxes. This might take some time." -PercentComplete 20 -Activity "Generating MSOL Report"
$statistics = ($mbx | get-mailboxstatistics)
write-verbose "Starting processing of $total individual mailboxes"
Write-Progress -Id 1 -Status "Processing individual users" -PercentComplete 60 -Activity "Generating MSOL Report"
$current = 0
forEach ( $user in $users ) {
$current++
$status = $user.displayname
Write-Progress -Activity "Processing $total mailboxes" -Status "Processing mailbox $status" -PercentComplete ($current / $total*100) -ParentId 1
Write-Verbose "Gathering statistics for $status"
$stats = ($statistics | Where-Object {$_.Displayname -eq $user.DisplayName})
$properties = @{'Name'=$user.DisplayName;
'EmailAddress'=$user.UserPrincipalName;
'Title'=$user.Title;
'Licensed'=$user.IsLicensed;
'MobilePhone'=$user.MobilePhone;
'AlternateEmail'=$user.AlternateEmailAddress;
'AlternatePhone'=$user.AlternateMobilePhones;
'LastLogon'=$stats.LastLogonTime;
'MailboxSize'=$stats.TotalItemSize;
'DeletedItemSize'=$stats.TotalDeletedItemSize}
$objResults = New-Object -TypeName PSObject -Property $properties
$arrResults += $objResults
}
Write-Progress -Id 1 -Status "Writing $outfile" -PercentComplete 95 -Activity "Generating MSOL Report"
$arrResults | Export-CSV -NoTypeInformation -Path $outfile
$stoptime = (get-date)
$time = (new-timespan -start $starttime -end $stoptime)
write-output "Processed $total users in $time, exported to CSV file $outfile."
} |
loader.psm1 | 365Tools-3.1.0 | # DO NOT MODIFY THIS FILE!
# THIS FILE WAS AUTOGENERATED BY ISESTEROIDS AND WILL BE OVERWRITTEN WHEN YOU EXPORT FUNCTIONS TO THIS MODULE.
# USE THIS FILE FOR ADDITIONAL MODULE CODE. THIS FILE WILL NOT BE OVERWRITTEN
# WHEN NEW CONTENT IS PUBLISHED TO THIS MODULE:
. $PSScriptRoot\init.ps1
# LOADING ALL FUNCTION DEFINITIONS:
. $PSScriptRoot\New-MSOLReport.ps1
. $PSScriptRoot\Open-MSOLConnection.ps1
. $PSScriptRoot\get-alternateinfo.ps1
. $PSScriptRoot\get-mailboxauditsettings.ps1
. $PSScriptRoot\get-admininfo.ps1
. $PSSCriptRoot\get-msolipranges.ps1 |
get-alternateinfo.ps1 | 365Tools-3.1.0 | function Get-AlternateInfo
{
<#
.SYNOPSIS
Creates a CSV-file with user data from Office 365 with users that don't have their alternate contact information set up.
.DESCRIPTION
This function creates a CSV-file with user data fetched from Office 365 that includes users that don't have their alternate information filled in. These alternate information should be filled in so that you can contact users to verify anomalous activity or enable MFA.
.EXAMPLE
Get-AlternateInfo -outfile c:\temp\incomplet.csv
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true, Position=0)]
[string]
$outfile
)
$outpath = split-path $outfile
if (!(test-path $outpath)) {new-item $outpath -ItemType Directory}
if (!(get-module msonline)) {open-msolconnection}
$licusers = Get-MsolUser | where {$_.isLicensed -eq $true}
$IncompleteUsers = $licusers | where {($_.AlternateEmailAddress -eq $null) -or ($_.AlternateMobilePhones -eq $null)}
$IncompleteUsers | Select-Object DisplayName, UserPrincipalName, AlternateEmailAddress, AlternateMobilePhones | export-csv $outfile -NoTypeInformation
}
|
365Tools.psd1 | 365Tools-3.1.0 | #
# Module manifest for module 'PSGet_365Tools'
#
# Generated by: Ralph Eckhard
#
# Generated on: 16-2-2017
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'loader.psm1'
# Version number of this module.
ModuleVersion = '3.1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '13de5fa6-fbec-4380-880d-bbcbced069d2'
# Author of this module
Author = 'Ralph Eckhard'
# Company or vendor of this module
CompanyName = '365Dude - www.365dude.nl'
# Copyright statement for this module
Copyright = '(c) 2017 Ralph Eckhard. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Toolset for working with Office365 in Powershell'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'New-MSOLReport', 'Open-MSOLConnection', 'Get-AdminInfo', 'Get-AlternateInfo', 'Get-MailboxAuditSettings', 'Get-MSOLIPRanges'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'Created V3.0, including some new functions.'
# External dependent modules of this module
# ExternalModuleDependencies = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
get-mailboxauditsettings.ps1 | 365Tools-3.1.0 | function Get-MailboxAuditSettings
{
<#
.SYNOPSIS
Display all mailboxes that don't have audit enabled. Gives you the option to enable directly.
.DESCRIPTION
This function generates an overview of all mailboxes that don't have auditing enabled. When specifying the -activate switch, auditing will be enabled for those mailboxes with a maximum log age of 365 days.
.EXAMPLE
get-mailboxauditsettings
get-mailboxauditsettings -update
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$false, Position=0)]
[switch]
$update
)
if (!(get-module msonline)) {open-msolconnection}
#region Set variables
$mbxs = get-mailbox -resultsize unlimited
$AuditDisabled = $mbxs | where-object {$_.AuditEnabled -ne $true}
$DisabledCount = $AuditDisabled.count
#endregion
if ($update) {
write-output "There are $DisabledCount mailboxes that don't have auditing enabled."
write-output "Enabling auditing on the following mailboxes:"
$AuditDisabled
foreach ($mbx in $AuditDisabled) {set-mailbox $mbx.alias -AuditEnabled $true -AuditLogAgeLimit 365 -Verbose}
}
if (!($Update)) {
write-output "There are $DisabledCount mailboxes that don't have auditing enabled."
if ($DisabledCount -eq 0){
write-output "The following mailboxes don't have auditing enabled:"
$AuditDisabled
write-output "You can manually enable auditing on these mailboxes or run get-mailboxauditsettings -update to enable auditing on all mailboxes"
}
}
} |
Open-MSOLConnection.ps1 | 365Tools-3.1.0 | function Open-MSOLConnection
{
<#
.SYNOPSIS
Connects and loads a MSOL PoSH Connection.
.DESCRIPTION
Gets credential for MSOL Session, configures a new session and loads it.
.EXAMPLE
Open-MSOLConnection
#>
$LiveCred = Get-Credential
$Session = New-PSSession -Name MSOL -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-Module (Import-PSSession $Session -AllowClobber) -Global
connect-msolservice -credential $LiveCred
} |
Get-AdminInfo.ps1 | 365Tools-3.1.0 | function Get-AdminInfo
{
<#
.SYNOPSIS
Gets information on the administrative users on your tenant, to make sure you comply with Microsoft best practices.
.DESCRIPTION
.EXAMPLE
Get-AdminInfo
#>
if (!(get-module msonline)) {open-msolconnection}
#region Get data
$AdminRole = Get-MsolRole | where {$_.name -like 'Company Administrator'}
$GlobalAdmins = Get-MsolRoleMember -RoleObjectId $adminrole.ObjectId
$GACount = ($GlobalAdmins).count
#endregion
#region Get number of GA's
if ($GACount -eq 1) {Write-Output 'Only one global admin present. As best practice, you should use at least 2 global admin accounts.'} `
elseif ($GACount -gt 5) {Write-Output "There are $GACount global admin accounts. As best practice, you should not have more than 5 global admin accounts."} `
else {Write-Output "There are $GACount global admin accounts. This complies with best practices."}
#endregion
#region Check MFA
Write-Output "You should check the MFA status of all global admins using the Office 365-portal. This check will be included in this script in the near future."
#endregion
#region Non-global Admins
Write-Output "You should use the portal to check if non-global admin roles are used. As best practice, you should use these roles to minimize risks."
Write-Output "You should check if the users holding non-global admin roles should still be having these priviliges."
Write-Output "These checks will be included in this script in the near future."
#endregion
} |
init.ps1 | 365Tools-3.1.0 |
# use this file to define global variables on module scope
# or perform other initialization procedures.
# this file will not be touched when new functions are exported to
# this module.
|
get-forwardmailbox.ps1 | 365Tools-3.1.0 | function New-MSOLReport
{
<#
.SYNOPSIS
Gets all mailboxes with that forward mail to a different address
.DESCRIPTION
This function outputs all mailboxes that forward mail to a different address. You can use this for compliancy checks.
.EXAMPLE
Get-ForwardMailbox
#>
get-mailbox | where-object {$_.ForwardingSMTPAddress -ne $null} | select-object Name, PrimarySMTPAddress, ForwardingSMTPAddress
}
|
Get-3CXTrunk.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX Trunks
.DESCRIPTION
Retrieve the 3CX Trunks
.EXAMPLE
PS> Get-3CXTrunks
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXTrunk {
[CmdletBinding()]
param(
[Parameter(Mandatory=$False)]
$ID = $null
)
$params = @{
Endpoint = "/xapi/v1/Trunks"
ID = $ID
}
return Get-3CXResult @params
} |
Get-3CXSIPDevice.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX SIP Device
.DESCRIPTION
Retrieve the 3CX SIP Device(s)
.EXAMPLE
PS> Get-3CXSIPDevice
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXSIPDevice {
[CmdletBinding()]
param()
$params = @{
Endpoint = '/xapi/v1/SipDevices'
Paginate = $true
PageExpand = 'DN'
PageFilter = "DN/Type eq 'Extension'"
PageOrderBy = "DN/Number"
}
return Get-3CXResult @params
} |
3CX.psd1 | 3CX-0.0.10 | #
# Module manifest for module '3CX'
#
# Generated by: xasz
#
# Generated on: 01.08.2024
#
@{
# Script module or binary module file associated with this manifest.
RootModule = '.\3CX.psm1'
# Version number of this module.
ModuleVersion = '0.0.10'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'e6702acd-5d3e-438a-9b5f-027712371519'
# Author of this module
Author = 'xasz'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) xasz. All rights reserved.'
# Description of the functionality provided by this module
Description = 'This modules provides a set of cmdlets to interact with 3CX V20 API'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '5.0'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
"Connect-3CX",
"Get-3CXActiveCalls",
"Get-3CXEventLog",
"Get-3CXResult",
"Get-3CXSIPDevice",
"Get-3CXSystemHealth",
"Get-3CXSystemStatus",
"Get-3CXUser",
"Get-3CXVersion",
"Get-3CXSBC",
"Get-3CXTrunk"
)
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('3CX', 'API', 'REST', 'V20')
# A URL to the license for this module.
LicenseUri = 'https://github.com/xasz/3CX/blob/main/LICENSE'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/xasz/3CX'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'Powershell 5'
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
3CX.psm1 | 3CX-0.0.10 | Write-Verbose "Discovering functions"
$Functions = @(Get-ChildItem -Path $PSScriptRoot\public\ -Include *.ps1 -Recurse)
if(Test-Path -Path $PSScriptRoot\private\){
$PrivateFunctions = @(Get-ChildItem -Path $PSScriptRoot\private\ -Include *.ps1 -Recurse)
$Functions = $Functions + $PrivateFunctions
}
foreach ($Function in @($Functions)) {
try {
Write-Verbose "Importing function $($Function.FullName)"
. $Function.FullName
} catch {
Write-Error -Message "Failed to import function $($Function.FullName): $_"
}
}
$script:3CXSession = $null |
Get-3CXSystemStatus.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX System Status
.DESCRIPTION
Retrieve the 3CX System Status which alot of information about the 3CX system
.EXAMPLE
PS> Get-3CXSystemStatus
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXSystemStatus {
[CmdletBinding()]
param()
return Get-3CXResult -Endpoint "/xapi/v1/SystemStatus"
} |
Get-3CXEventLog.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX Event Log
.DESCRIPTION
Retrieve the 3CX Event Log
.EXAMPLE
PS> Get-3CXEventLog
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXEventLog {
[CmdletBinding()]
param()
$params = @{
Endpoint = '/xapi/v1/EventLogs'
Paginate = $true
PageFilter = "Type eq 'Info' or Type eq 'Warning' or Type eq 'Error'"
PageOrderBy = "TimeGenerated desc"
}
return Get-3CXResult @params
} |
Get-3CXResult.ps1 | 3CX-0.0.10 | function Get-3CXResult {
[CmdletBinding(DefaultParameterSetName = "Simple")]
param(
[Parameter(Mandatory=$True, ParameterSetName="Simple")]
[Parameter(Mandatory=$True, ParameterSetName="Paginate")]
[string]$Endpoint,
[Parameter(Mandatory=$False, ParameterSetName="Simple")]
[AllowNull()]
$ID = $null,
[Parameter(Mandatory=$False, ParameterSetName="Simple")]
[object]$Body = @{},
[Parameter(Mandatory=$False, ParameterSetName="Simple")]
[ValidateSet('GET', 'POST', 'PATCH', 'DELETE')]
[string]$Method = 'GET',
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[switch]$Paginate,
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[int]$PageSize = 50,
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[string]$PageFilter = '',
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[string]$PageOrderBy = '',
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[Parameter(Mandatory=$False, ParameterSetName="Simple")]
[string[]]$PageSelect = @(),
[Parameter(Mandatory=$False, ParameterSetName="Paginate")]
[Parameter(Mandatory=$False, ParameterSetName="Simple")]
[string]$PageExpand = ''
)
$PageSelect = $PageSelect | Where-Object {$null -ne $_}
if($null -eq $script:3CXSession){
throw "3CX session not established - Please run Connect-3CX"
}
switch($PSCmdlet.ParameterSetName){
"Simple" {
if($null -ne $ID -or $ID -ge 0){
if($ID -match '^\d+$'){
Write-Debug "ID is a number"
$Endpoint = "{0}({1})" -f $Endpoint, $ID
}else{
$Endpoint = "{0}('{1}')" -f $Endpoint, $ID
}
}
if(($PageSelect | Measure-Object).Count -gt 0){
$Body.'$select' = $PageSelect -join ','
}
$params = @{
Uri = ("https://{0}:{1}{2}" -f $script:3CXSession.APIHost, $script:3CXSession.APIPort, $Endpoint)
Method = $Method
Headers = @{
Authorization = "Bearer $($script:3CXSession.AccessToken)"
}
Body = $Body
UseBasicParsing = $true
}
Write-Debug "Parameter $($params | ConvertTo-Json)"
$result = Invoke-WebRequest @params
Write-Debug "Raw Content Result $($result.Content)"
$obj = $result.Content | ConvertFrom-Json
$arrayFields = @('value','@odata.context')
if($null -eq (Compare-Object -ReferenceObject $arrayFields -DifferenceObject $obj.PSObject.Properties.Name) ){
return $obj.value
}
return $obj | Select-Object -ExcludeProperty '@odata.context'
}
"Paginate" {
$targetCount = -1
$values = New-Object Collections.Generic.List[object]
while($targetCount -lt 0 -or $values.Count -lt $targetCount){
Write-Verbose "Retrieving SIP Devices from Top $PageSize and Skip $($values.Count)"
$newBody = @{
'$top' = $PageSize
'$skip' = $values.Count
'$count' = 'true'
}
if(-not [string]::IsNullOrEmpty($PageFilter)){
$newBody.'$filter' = $PageFilter
}
if(-not [string]::IsNullOrEmpty($PageExpand)){
$newBody.'$expand' = $PageExpand
}
if($PageSelect.Count -gt 0){
$newBody.'$select' = $PageSelect -join ','
}
if(-not [string]::IsNullOrEmpty($PageOrderBy)){
$newBody.'$orderby' = $PageOrderBy
}
$result = Get-3CXResult -Endpoint $Endpoint -Body $newBody
$targetCount = $result.'@odata.count'
$result.value | ForEach-Object {$values.Add($_)}
}
return $values
}
}
} |
Get-3CXActiveCalls.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX Active Calls
.DESCRIPTION
Retrieve the Active Calls
.EXAMPLE
PS> Get-3CXActiveCalls
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXActiveCalls {
[CmdletBinding()]
param()
$params = @{
Endpoint = '/xapi/v1/ActiveCalls'
Paginate = $true
PageOrderBy = 'LastChangeStatus desc'
}
return Get-3CXResult @params
}
|
Get-3CXVersion.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX System Version
.DESCRIPTION
Retrieve the 3CX System Version
.EXAMPLE
PS> Get-3CXVersion
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXVersion {
[CmdletBinding()]
param()
return [version](Get-3CXResult -Endpoint '/xapi/v1/Defs/Pbx.GetSystemParameters()').Version
} |
Get-3CXUser.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX User
.DESCRIPTION
Retrieve the 3CX User
.EXAMPLE
PS> Get-3CXUser
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXUser {
[CmdletBinding()]
param()
$params = @{
Endpoint = '/xapi/v1/Users'
Paginate = $true
PageFilter = "not startsWith(Number,'HD')"
PageOrderBy = "Number"
PageSelect = "IsRegistered,CurrentProfileName,DisplayName,Id,EmailAddress,Number,Tags,Require2FA"
PageExpand = 'Groups($select=GroupId,Name,Rights;$filter=not startsWith(Name,''___FAVORITES___'');$expand=Rights($select=RoleName)),Phones($select=MacAddress,Name,Settings($select=IsSBC,ProvisionType))'
}
return Get-3CXResult @params
}
|
Get-3CXSystemHealth.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX System Health
.DESCRIPTION
Retrieve the 3CX System Health which contains firewall, trunks and phones health
.EXAMPLE
PS> Get-3CXSystemHealth
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXSystemHealth {
[CmdletBinding()]
param()
return Get-3CXResult -Endpoint "/xapi/v1/SystemStatus/Pbx.SystemHealthStatus()"
} |
Get-3CXSBC.ps1 | 3CX-0.0.10 | <#
.SYNOPSIS
Get 3CX SBCs
.DESCRIPTION
Retrieve the 3CX SBCs
.EXAMPLE
PS> Get-3CXSBC
.OUTPUTS
powershell object containing the 3CX response
#>
function Get-3CXSBC {
[CmdletBinding(DefaultParameterSetName = "Default")]
param(
[Parameter(Mandatory=$True, ParameterSetName="Single")]
$Name,
[Parameter(Mandatory=$False, ParameterSetName="Single")]
[Parameter(Mandatory=$False, ParameterSetName="Default")]
[string[]]$PageSelect = @()
)
$params = @{
Endpoint = "/xapi/v1/sbcs"
ID = $Name
PageSelect = $PageSelect
}
return Get-3CXResult @params
} |
Connect-3CX.ps1 | 3CX-0.0.10 |
function Connect-3CX{
[CmdletBinding()]
param(
[Parameter(mandatory=$true, HelpMessage="3CX Credential")]
[pscredential]$Credential,
[Parameter(mandatory=$true, HelpMessage="3CX Server")]
[string]$APIHost,
[Parameter(mandatory=$false, HelpMessage="3CX Server Port")]
[int]$APIPort = 443
)
$params = @{
Uri = "https://{0}:{1}/webclient/api/Login/GetAccessToken" -f $APIHost, $APIPort
Method = 'POST'
Body = @{
Username = $Credential.UserName
SecurityCode = ""
Password = $Credential.GetNetworkCredential().Password
} | ConvertTo-Json
ContentType = 'application/json'
UseBasicParsing = $true
}
$result = Invoke-WebRequest @params
if($result.StatusCode -ne 200){
throw "Failed to get bearer token - status code: $($result.StatusCode)"
}
$obj = $result.Content | ConvertFrom-Json
if($obj.Status -notlike "AuthSuccess"){
throw "Failed to get Bearer - Status is not AuthSuccess"
}
$script:3CXSession = @{
AccessToken = $obj.Token.access_token
ExpiresAt = (Get-Date).AddMinutes($obj.Token.expires_in)
APIHost = $APIHost
APIPort = $APIPort
}
}
|
PublishToPSGallery.ps1 | 3LCourseAZ040-2204.6.0 | # Date: 2022-04-06
cls
$baseFolder = $PSScriptRoot
Write-Verbose "STATUS : BaseFolder = $baseFolder" -v
if ( -not($baseFolder) ) {
$baseFolder = Get-Location
}
if ( $name = ([regex]::match($baseFolder, '.+\\Modules\\(.[^\\]+)')).groups[1].value ) {
Write-Verbose "SUCCESS: Modulename extracted from path: $name" -v
}
else {
Write-Warning "ERROR : Could not extract modulename from $baseFolder"
break
}
# Set $baseFolder to folder where modulefile is to be saved
$baseFolder = ([regex]::match($baseFolder, '.+\\Modules\\(.[^\\]+)')).groups[0].value
Write-Verbose "STATUS : Removing module $name from this computer" -v
Remove-Module $name -ea SilentlyContinue
Uninstall-Module $name -Force -ea SilentlyContinue
Remove-Item $baseFolder\$name.psd1 -Confirm:$false -Force -ea SilentlyContinue
Remove-Item $baseFolder\$name.psm1 -Confirm:$false -Force -ea SilentlyContinue
Remove-Item "$((Get-PSRepository PSGallery).SourceLocation)\$name.$(Get-Date -Format 'yyMM.dd.0' ).nupkg" -ea SilentlyContinue
if ( $name -eq '3LPublishing' ) {
Write-Verbose "STATUS : Loading Publishing functions" -v
(Get-ChildItem $baseFolder\Source\Public\*.ps1) | foreach {
. $_.FullName
}
}
Write-Verbose "STATUS : Modulefile will be created in: $baseFolder" -v
Write-Verbose "STATUS : Calling New-3lModuleFile" -v
new-3lModuleFile -path $baseFolder -Verbose
try {
$splat = @{
'modulePath' = (gci "$baseFolder\$name.psm1");
'version' = (Get-Date -Format 'yyMM.dd.0' );
'repository' = 'PSGallery'
}
if ( [array]$publicFunctions = (Get-ChildItem -Path "$baseFolder\Source\Public" -ErrorAction SilentlyContinue).BaseName ) {
$splat.Add('functionsToExport', $publicFunctions)
}
Write-Verbose "STATUS : Calling Publish-3LScriptOrModule" -v
Publish-3LScriptOrModule @splat -UseSavedSettings -Verbose -ErrorAction Stop
Start-Sleep 5
}
catch {
Write-Error $_
Read-Host 'Press [Enter] to continue'
}
Install-Module $publishModule -Repository 'PSGallery'
|
3LCourseAZ040.psd1 | 3LCourseAZ040-2204.6.0 | #
# Module manifest for module '3LCourseAZ040'
#
# Generated by: F. van Drie (3-link.nl)
#
# Generated on: 4/6/2022
#
@{
# Script module or binary module file associated with this manifest.
RootModule = '3LCourseAZ040'
# Version number of this module.
ModuleVersion = '2204.6.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '92d939b6-d9d3-49bb-a488-0cd94844eae1'
# Author of this module
Author = 'F. van Drie (3-link.nl)'
# Company or vendor of this module
CompanyName = '3-Link Opleidingen'
# Copyright statement for this module
Copyright = 'free to use and distribute without modifications'
# Description of the functionality provided by this module
Description = 'Developed by 3-Link Opleidingen for training purposes only'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Demo-Construct', 'MCT-GetFolderInfo'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Demo-Construct.ps1 | 3LCourseAZ040-2204.6.0 | # Filename: Demo-Construct.ps1
# Author: Frits van Drie (3-Link.nl)
# Date: 2022-04-06
#region: If, ElseIf, Else
<#
If (Condition1) {Action1}
ElseIf (Condition2) {Action2}
ElseIf (Condition3) {Action3}
Else {Action4}
#>
$one = 1
$two = 2
If ($one -eq 0 -or $two -eq 0) {Write-Host "$one or $two is Zero"}
ElseIf ($one -gt $two) {Write-Host "$One > $Two"}
ElseIf ($one -lt $two) {Write-Host "$One < $Two"}
Else {Write-Host "$One = $Two"}
Suspend-Service workstation
Get-Service 'l*' | ForEach-Object {
if ($_.status -eq 'running') {
write-host "$($_.Name) is started" -ForegroundColor Green
}
elseif ($_.status -eq 'stopped') {
write-host "$($_.Name) is stopped" -ForegroundColor Red
}
else {
write-host "$($_.Name) is $($_.status)" -ForegroundColor Yellow
}
}
Resume-Service workstation
#endregion
#region: ForEach (Statement/Construct)
# ForEach ( $x in $y ) {
# <commands>
# }
# PS 7: Parallel processing
# ForEach -Parallel ( $x in $y ) {
# <commands>
# }
$SvcList = Get-service "sp*"
ForEach ( $Svc in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)"
}
# Foreach Construct is not the same as ForEach-Object Cmdlet !!!
$SvcList |ForEach-Object {
Write-Host "$($_.Name) is $($_.Status)"
}
# Wrong
ForEach-Object ( $Svc -in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)" # > ERROR
}
ForEach ( $Svc in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)"
}
#endregion
#region: Break the loop: Continue / Break
$array = @('1','2','3','4')
foreach ($nr in $array) {
if ($nr -lt 3 ) {
Write-Host "$nr < 3"
}
Write-Host "$nr >= 3"
}
###
$array = @('1','2','3','4')
foreach ($nr in $array) {
if ($nr -lt 3 ) {
Write-Host "$nr < 3"
continue
}
Write-Host "$nr >= 3"
}
###
$array | foreach {
if ($_ -lt 3 ) {
Write-Host "$_ < 3"
Break
}
Write-Host "$_ >= 3"
}
#endregion
#region: For () {}
# Repeat code block while condition is true
# For (start; condition; action ) { codeblock }
For ($x = 1; $x -le 10; $x++ ) {
Write-Host "Line $x"
}
1..10 | foreach {Write-Host "Line $_"}
1..10 | Write-Host "Line $_" #> ERROR
1..10 | Write-Host
1..10
help Write-Host -ShowWindow
#endregion
#region: Do .. While .. Until
# Executed at least 1 time
# Repeat while condition is True
# Do {codeblock} While (condition is true)
# Do {...} While (...)
$x = 10
Do {
Write-Host "Line $x"
$x++
}
While ($x -le 10)
#endregion
#region: Do .. Until
# Executed at least 1 time
# Repeat while condition is False
# Do {codeblock} Until (condition is true)
$x =0
Do {$x++; Write-Host "Line $x"} until ($x -gt 5)
$x =6
Do {$x++; Write-Host "Line $x"} until ($x -gt 5)
$x =0
Do {$x++; Write-Host "Line $x"} until ($x -le 5)
$x =6
Do {$x++; Write-Host "Line $x"} until ($x -le 5)
#endregion
#region: While
# Executed at least 0 time
# While (condition is true) {codeblock}
$x =1
While ($x -le 4) {
Write-Host "Line $x"
$x++
}
$x =5
While ($x -le 4) {
Write-Host "Line $x"
$x++
}
# Attention: when condition is already true !!
$Menu = "Make a choice"
Do {$choice = Read-Host $Menu} While ($choice -notin ('1','2','3','4','5'))
While ($choice -notin ('1','2','3','4','5')) {$choice = Read-Host $Menu}
Remove-Variable choice
While ($choice -notin ('1','2','3','4','5')) {$choice = Read-Host $Menu}
<#
:red while (<condition1>) {
:yellow while (<condition2>) {
while (<condition3>) {
if ($a) {break}
if ($b) {break red}
if ($c) {break yellow}
}
Write-Host "After innermost loop"
}
Write-Host "After yellow loop"
}
Write-Host "After red loop"
#>
$red = 0
$yellow = 0
$green = 0
$breakGreen = $true
$breakYellow = $true
$breakRed = $true
:red while ( $red -le 2 ) {
$red++
Write-Host "Red loop $red" -f Red
Start-Sleep 1
:yellow while ( $yellow -le 2 ) {
$yellow++
Write-Host "`tYellow loop $yellow" -f Yellow
Start-Sleep 1
while ( $green -le 2 ) {
$green++
Write-Host "`t`tGreen loop $green" -f Green
Start-Sleep 1
if ($breakGreen) {break}
if ($breakYellow) {break yellow}
if ($breakRed) {break red}
}
Write-Host "`t`tAfter green loop" -f Green
}
Write-Host "`tAfter yellow loop" -f Yellow
}
Write-Host "After red loop" -f Red
#endregion
#region: Switch
<#
Switch (Variable to test) {
1 {command 1} # multiple values can be true
2 {command 2}
Default {action default}
}
#>
$x = 2
Switch ($x) {
1 {Write-Host "Option 1"}
2 {Write-Host "Option 2"}
3 {Write-Host "Option 3"}
Default {Write-Host "Something Else"}
}
$x = 5
Switch ($x) {
1 {Write-Host "Option 1"}
2 {Write-Host "Option 2"}
3 {Write-Host "Option 3"}
Default {Write-Host "Something Else"}
}
#> Option 2
$x = 'Rotterdam'
Switch -Wildcard ($x) {
*dam {Write-Host "Rotterdam or Amsterdam"}
A* {Write-Host "Amsterdam"}
R* {Write-Host "Rotterdam"}
Default {Write-Host "Somewhere else"}
}
#> Rotterdam or Amsterdam
#> Rotterdam
$Size = 465388000000
Switch ($Size) {
DEFAULT { $Unit = 1 ; $Symbol = 'B'}
{$_ -gt 1KB} { $Unit = 1KB ; $Symbol = 'KB'}
{$_ -gt 1MB} { $Unit = 1MB ; $Symbol = 'MB'}
{$_ -gt 1GB} { $Unit = 1GB ; $Symbol = 'GB'}
}
"Total size: {0:N2} $Symbol" -f ($Size/$Unit)
#endregion
#region: Begin..Proces..End
Function Demo-BeginProcessEnd {
PARAM (
$Par1,
[parameter(ValueFromPipeline=$true)]$Par2,
[parameter(ValueFromPipeline=$true)]$Par3
)
Begin{
Write-Host "Start Function: $($MyInvocation.MyCommand)"
Write-Host "Begin:`tExecuted once" -ForegroundColor Green
Write-Host "="
$i = 1
}
Process {
Write-Host "Process Pipeline input: $Par2" -BackgroundColor White -ForegroundColor Blue
foreach ($p in $Par1) {
Write-Host "`t Parameter: $p"
}
}
End{
write-Host "="
Write-Host "End Function: $($MyInvocation.MyCommand)"
Write-Host "End:`tExecuted once" -ForegroundColor Red
}
}
cls
"ABC", "DEF" | Demo-BeginProcessEnd -Par1 "123", "456", "789"
##################
Function Test
{
begin
{
$i = 0
}
process
{
"Iteration: $i"
$i++
"`tInput: $input, $input"
"`tInput: $input"
"`tAccess Again: $input"
$input.Reset()
"`tAfter Reset: $input"
}
}
"one","two" | Test
#endregion
#region: Demo-Menu:
$gsv = 'Get-Service'
$gps = 'Get-Process'
$msg = $null
Function MakeMenu {
$Script:Menu= @"
Menu
---------------------------
`t1.`t$gsv
`t2.`t$gps
`t3.`tGet System Eventlog
`t4.`tCheck Freespace (GB) `t$msg
`t5.`tQuit
`tSelect an option
"@ # @"" = Multi-line string literal with embedded variables.
}
Do {
MakeMenu
$msg = $null
$choice = Read-Host $Menu
Switch ($choice) {
1 {Invoke-Expression $gsv}
2 {Invoke-Expression $gps}
3 {Get-Eventlog -LogName System -Newest 10}
4 {$FreeSpace = '{0:N0}'-f ((Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceId='c:'").FreeSpace/1GB)+" GB"
#{((Get-wmiObject -Class Win32_LogicalDisk -Filter "DeviceId='c:'").FreeSpace/1GB)}
$msg = "Freespace: $FreeSpace"
}
5 {Break}
default {Write-Warning "$choice is not a valid choice"}
}
} While ($choice -ne 5)
#endregion
|
MCT-GetFolderInfo.ps1 | 3LCourseAZ040-2204.6.0 | Function MCT-GetFolderInfo {
<#
.SYNOPSIS
Gets the number of files and total storage for a specified folder.
.DESCRIPTION
Gets the number of files and total storage for a specified folder on the local or remote computer.
If no computer is specified, the local computer is queried
.EXAMPLE
'SVR1', 'SVR2' | GetFolderInfo -path 'C:\Data'
Folder info is retrieved from 2 computers
Names are presented through the pipeline
.EXAMPLE
GetFolderInfo -path 'C:\data' -recurse -computerName 'SVR1', 'SVR2'
Folder info is retrieved from 2 computers as presented via the ComputerName parameter
-Recurse directs the function to process underlying subdirectories
.NOTES
Version 2022-04-06
Author Frits van Drie (3-link.nl)
#>
[CmdletBinding()]
param(
[parameter(mandatory=$false)]
$path = "$env:USERPROFILE\documents",
[parameter(mandatory=$false)]
[switch]$recurse = $false,
[parameter(mandatory=$false,ValueFromPipeline=$true)]
[string[]]$computerName = 'localhost'
)
Begin {
Write-Verbose "Start Function"
if ( $PSBoundParameters.Keys -contains 'Verbose' ) {
$verboseAction = 'Continue'
}
else {
$verboseAction = $VerbosePreference
}
}
Process {
foreach ($deviceName in $computerName) {
Write-Verbose "Connecting to $deviceName"
$objReturn = Invoke-Command -ComputerName $deviceName {
$VerbosePreference = $using:verboseAction
$path = $using:path
$recurse = $using:recurse
Write-Verbose "Connected to $env:COMPUTERNAME"
Write-Verbose "Path : $path"
Write-Verbose "Recurse: $recurse"
if ( -not (Test-Path $path) ) {
Write-Error "$path is not a valid path"
break
}
Write-Verbose "$path exists"
if ( -not ((Get-Item $path).psIsContainer) ){
Write-Warning "$path is not a valid folder"
break
}
Write-Verbose "$path is a container"
# Collect Files
try {
Write-Verbose "Retrieving files in $path"
$fileList = Get-ChildItem -Path $path -Recurse:$recurse -File -ErrorAction stop
Write-Verbose "Success"
Write-Verbose "Found $($fileList.count) files"
Write-Verbose "Measuring files"
$objReturn = $fileList | Measure-Object -Property Length -Sum
}
catch {
Write-Warning "$path is not a valid path"
break
}
return $objReturn
} # end invoke
Write-Output $objReturn
} # end Foreach
} # end Process
End {
Write-Verbose "End Function"
}
}
|
PublishToMyRepo.ps1 | 3LCourseAZ040-2204.6.0 | # Date: 2021-10-25
cls
$baseFolder = $PSScriptRoot
Write-Verbose "STATUS : BaseFolder = $baseFolder" -v
if ( -not($baseFolder) ) {
$baseFolder = Get-Location
}
if ( $name = ([regex]::match($baseFolder, '.+\\Modules\\(.[^\\]+)')).groups[1].value ) {
Write-Verbose "SUCCESS: Modulename extracted from path: $name" -v
}
else {
Write-Warning "ERROR : Could not extract modulename from $baseFolder"
break
}
# Set $baseFolder to folder where modulefile is to be saved
$baseFolder = ([regex]::match($baseFolder, '.+\\Modules\\(.[^\\]+)')).groups[0].value
Write-Verbose "STATUS : Removing module $name from this computer" -v
Remove-Module $name -ea SilentlyContinue
Uninstall-Module $name -Force -ea SilentlyContinue
Remove-Item $baseFolder\$name.psd1 -Confirm:$false -Force -ea SilentlyContinue
Remove-Item $baseFolder\$name.psm1 -Confirm:$false -Force -ea SilentlyContinue
Remove-Item "$((Get-PSRepository MyRepo).SourceLocation)\$name.$(Get-Date -Format 'yyMM.dd.0' ).nupkg" -ea SilentlyContinue
if ( $name -eq '3LPublishing' ) {
Write-Verbose "STATUS : Loading Publishing functions" -v
(Get-ChildItem $baseFolder\Source\Public\*.ps1) | foreach {
. $_.FullName
}
}
Write-Verbose "STATUS : Modulefile will be created in: $baseFolder" -v
Write-Verbose "STATUS : Calling New-3lModuleFile" -v
new-3lModuleFile -path $baseFolder -Verbose
try {
$splat = @{
'modulePath' = (gci "$baseFolder\$name.psm1");
'version' = (Get-Date -Format 'yyMM.dd.0' );
'repository' = 'MyRepo'
}
if ( [array]$publicFunctions = (Get-ChildItem -Path "$baseFolder\Source\Public" -ErrorAction SilentlyContinue).BaseName ) {
$splat.Add('functionsToExport', $publicFunctions)
}
Write-Verbose "STATUS : Calling Publish-3LScriptOrModule" -v
Publish-3LScriptOrModule @splat -UseSavedSettings -Verbose -ErrorAction Stop
Start-Sleep 5
}
catch {
Write-Error $_
Read-Host 'Press [Enter] to continue'
}
Install-Module $publishModule -Repository 'MyRepo'
|
3LCourseAZ040.psm1 | 3LCourseAZ040-2204.6.0 | # Filename: Demo-Construct.ps1
# Author: Frits van Drie (3-Link.nl)
# Date: 2022-04-06
#region: If, ElseIf, Else
<#
If (Condition1) {Action1}
ElseIf (Condition2) {Action2}
ElseIf (Condition3) {Action3}
Else {Action4}
#>
$one = 1
$two = 2
If ($one -eq 0 -or $two -eq 0) {Write-Host "$one or $two is Zero"}
ElseIf ($one -gt $two) {Write-Host "$One > $Two"}
ElseIf ($one -lt $two) {Write-Host "$One < $Two"}
Else {Write-Host "$One = $Two"}
Suspend-Service workstation
Get-Service 'l*' | ForEach-Object {
if ($_.status -eq 'running') {
write-host "$($_.Name) is started" -ForegroundColor Green
}
elseif ($_.status -eq 'stopped') {
write-host "$($_.Name) is stopped" -ForegroundColor Red
}
else {
write-host "$($_.Name) is $($_.status)" -ForegroundColor Yellow
}
}
Resume-Service workstation
#endregion
#region: ForEach (Statement/Construct)
# ForEach ( $x in $y ) {
# <commands>
# }
# PS 7: Parallel processing
# ForEach -Parallel ( $x in $y ) {
# <commands>
# }
$SvcList = Get-service "sp*"
ForEach ( $Svc in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)"
}
# Foreach Construct is not the same as ForEach-Object Cmdlet !!!
$SvcList |ForEach-Object {
Write-Host "$($_.Name) is $($_.Status)"
}
# Wrong
ForEach-Object ( $Svc -in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)" # > ERROR
}
ForEach ( $Svc in $SvcList ) {
Write-Host "$($Svc.Name) is $($Svc.Status)"
}
#endregion
#region: Break the loop: Continue / Break
$array = @('1','2','3','4')
foreach ($nr in $array) {
if ($nr -lt 3 ) {
Write-Host "$nr < 3"
}
Write-Host "$nr >= 3"
}
###
$array = @('1','2','3','4')
foreach ($nr in $array) {
if ($nr -lt 3 ) {
Write-Host "$nr < 3"
continue
}
Write-Host "$nr >= 3"
}
###
$array | foreach {
if ($_ -lt 3 ) {
Write-Host "$_ < 3"
Break
}
Write-Host "$_ >= 3"
}
#endregion
#region: For () {}
# Repeat code block while condition is true
# For (start; condition; action ) { codeblock }
For ($x = 1; $x -le 10; $x++ ) {
Write-Host "Line $x"
}
1..10 | foreach {Write-Host "Line $_"}
1..10 | Write-Host "Line $_" #> ERROR
1..10 | Write-Host
1..10
help Write-Host -ShowWindow
#endregion
#region: Do .. While .. Until
# Executed at least 1 time
# Repeat while condition is True
# Do {codeblock} While (condition is true)
# Do {...} While (...)
$x = 10
Do {
Write-Host "Line $x"
$x++
}
While ($x -le 10)
#endregion
#region: Do .. Until
# Executed at least 1 time
# Repeat while condition is False
# Do {codeblock} Until (condition is true)
$x =0
Do {$x++; Write-Host "Line $x"} until ($x -gt 5)
$x =6
Do {$x++; Write-Host "Line $x"} until ($x -gt 5)
$x =0
Do {$x++; Write-Host "Line $x"} until ($x -le 5)
$x =6
Do {$x++; Write-Host "Line $x"} until ($x -le 5)
#endregion
#region: While
# Executed at least 0 time
# While (condition is true) {codeblock}
$x =1
While ($x -le 4) {
Write-Host "Line $x"
$x++
}
$x =5
While ($x -le 4) {
Write-Host "Line $x"
$x++
}
# Attention: when condition is already true !!
$Menu = "Make a choice"
Do {$choice = Read-Host $Menu} While ($choice -notin ('1','2','3','4','5'))
While ($choice -notin ('1','2','3','4','5')) {$choice = Read-Host $Menu}
Remove-Variable choice
While ($choice -notin ('1','2','3','4','5')) {$choice = Read-Host $Menu}
<#
:red while (<condition1>) {
:yellow while (<condition2>) {
while (<condition3>) {
if ($a) {break}
if ($b) {break red}
if ($c) {break yellow}
}
Write-Host "After innermost loop"
}
Write-Host "After yellow loop"
}
Write-Host "After red loop"
#>
$red = 0
$yellow = 0
$green = 0
$breakGreen = $true
$breakYellow = $true
$breakRed = $true
:red while ( $red -le 2 ) {
$red++
Write-Host "Red loop $red" -f Red
Start-Sleep 1
:yellow while ( $yellow -le 2 ) {
$yellow++
Write-Host "`tYellow loop $yellow" -f Yellow
Start-Sleep 1
while ( $green -le 2 ) {
$green++
Write-Host "`t`tGreen loop $green" -f Green
Start-Sleep 1
if ($breakGreen) {break}
if ($breakYellow) {break yellow}
if ($breakRed) {break red}
}
Write-Host "`t`tAfter green loop" -f Green
}
Write-Host "`tAfter yellow loop" -f Yellow
}
Write-Host "After red loop" -f Red
#endregion
#region: Switch
<#
Switch (Variable to test) {
1 {command 1} # multiple values can be true
2 {command 2}
Default {action default}
}
#>
$x = 2
Switch ($x) {
1 {Write-Host "Option 1"}
2 {Write-Host "Option 2"}
3 {Write-Host "Option 3"}
Default {Write-Host "Something Else"}
}
$x = 5
Switch ($x) {
1 {Write-Host "Option 1"}
2 {Write-Host "Option 2"}
3 {Write-Host "Option 3"}
Default {Write-Host "Something Else"}
}
#> Option 2
$x = 'Rotterdam'
Switch -Wildcard ($x) {
*dam {Write-Host "Rotterdam or Amsterdam"}
A* {Write-Host "Amsterdam"}
R* {Write-Host "Rotterdam"}
Default {Write-Host "Somewhere else"}
}
#> Rotterdam or Amsterdam
#> Rotterdam
$Size = 465388000000
Switch ($Size) {
DEFAULT { $Unit = 1 ; $Symbol = 'B'}
{$_ -gt 1KB} { $Unit = 1KB ; $Symbol = 'KB'}
{$_ -gt 1MB} { $Unit = 1MB ; $Symbol = 'MB'}
{$_ -gt 1GB} { $Unit = 1GB ; $Symbol = 'GB'}
}
"Total size: {0:N2} $Symbol" -f ($Size/$Unit)
#endregion
#region: Begin..Proces..End
Function Demo-BeginProcessEnd {
PARAM (
$Par1,
[parameter(ValueFromPipeline=$true)]$Par2,
[parameter(ValueFromPipeline=$true)]$Par3
)
Begin{
Write-Host "Start Function: $($MyInvocation.MyCommand)"
Write-Host "Begin:`tExecuted once" -ForegroundColor Green
Write-Host "="
$i = 1
}
Process {
Write-Host "Process Pipeline input: $Par2" -BackgroundColor White -ForegroundColor Blue
foreach ($p in $Par1) {
Write-Host "`t Parameter: $p"
}
}
End{
write-Host "="
Write-Host "End Function: $($MyInvocation.MyCommand)"
Write-Host "End:`tExecuted once" -ForegroundColor Red
}
}
cls
"ABC", "DEF" | Demo-BeginProcessEnd -Par1 "123", "456", "789"
##################
Function Test
{
begin
{
$i = 0
}
process
{
"Iteration: $i"
$i++
"`tInput: $input, $input"
"`tInput: $input"
"`tAccess Again: $input"
$input.Reset()
"`tAfter Reset: $input"
}
}
"one","two" | Test
#endregion
#region: Demo-Menu:
$gsv = 'Get-Service'
$gps = 'Get-Process'
$msg = $null
Function MakeMenu {
$Script:Menu= @"
Menu
---------------------------
`t1.`t$gsv
`t2.`t$gps
`t3.`tGet System Eventlog
`t4.`tCheck Freespace (GB) `t$msg
`t5.`tQuit
`tSelect an option
"@ # @"" = Multi-line string literal with embedded variables.
}
Do {
MakeMenu
$msg = $null
$choice = Read-Host $Menu
Switch ($choice) {
1 {Invoke-Expression $gsv}
2 {Invoke-Expression $gps}
3 {Get-Eventlog -LogName System -Newest 10}
4 {$FreeSpace = '{0:N0}'-f ((Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceId='c:'").FreeSpace/1GB)+" GB"
#{((Get-wmiObject -Class Win32_LogicalDisk -Filter "DeviceId='c:'").FreeSpace/1GB)}
$msg = "Freespace: $FreeSpace"
}
5 {Break}
default {Write-Warning "$choice is not a valid choice"}
}
} While ($choice -ne 5)
#endregion
Function MCT-GetFolderInfo {
<#
.SYNOPSIS
Gets the number of files and total storage for a specified folder.
.DESCRIPTION
Gets the number of files and total storage for a specified folder on the local or remote computer.
If no computer is specified, the local computer is queried
.EXAMPLE
'SVR1', 'SVR2' | GetFolderInfo -path 'C:\Data'
Folder info is retrieved from 2 computers
Names are presented through the pipeline
.EXAMPLE
GetFolderInfo -path 'C:\data' -recurse -computerName 'SVR1', 'SVR2'
Folder info is retrieved from 2 computers as presented via the ComputerName parameter
-Recurse directs the function to process underlying subdirectories
.NOTES
Version 2022-04-06
Author Frits van Drie (3-link.nl)
#>
[CmdletBinding()]
param(
[parameter(mandatory=$false)]
$path = "$env:USERPROFILE\documents",
[parameter(mandatory=$false)]
[switch]$recurse = $false,
[parameter(mandatory=$false,ValueFromPipeline=$true)]
[string[]]$computerName = 'localhost'
)
Begin {
Write-Verbose "Start Function"
if ( $PSBoundParameters.Keys -contains 'Verbose' ) {
$verboseAction = 'Continue'
}
else {
$verboseAction = $VerbosePreference
}
}
Process {
foreach ($deviceName in $computerName) {
Write-Verbose "Connecting to $deviceName"
$objReturn = Invoke-Command -ComputerName $deviceName {
$VerbosePreference = $using:verboseAction
$path = $using:path
$recurse = $using:recurse
Write-Verbose "Connected to $env:COMPUTERNAME"
Write-Verbose "Path : $path"
Write-Verbose "Recurse: $recurse"
if ( -not (Test-Path $path) ) {
Write-Error "$path is not a valid path"
break
}
Write-Verbose "$path exists"
if ( -not ((Get-Item $path).psIsContainer) ){
Write-Warning "$path is not a valid folder"
break
}
Write-Verbose "$path is a container"
# Collect Files
try {
Write-Verbose "Retrieving files in $path"
$fileList = Get-ChildItem -Path $path -Recurse:$recurse -File -ErrorAction stop
Write-Verbose "Success"
Write-Verbose "Found $($fileList.count) files"
Write-Verbose "Measuring files"
$objReturn = $fileList | Measure-Object -Property Length -Sum
}
catch {
Write-Warning "$path is not a valid path"
break
}
return $objReturn
} # end invoke
Write-Output $objReturn
} # end Foreach
} # end Process
End {
Write-Verbose "End Function"
}
}
|
3LToolKit.psm1 | 3LToolKit-211020.1829.0 | Function Get-3LLogonEventAccountName {
#requires -RunAsAdministrator
#requires -Modules PSScriptTools
<#
.SYNOPSIS
Get all logon events (Success and Failure) and extract some logon details
.SYNOPSIS
Get all authenticate events that are used to authenticate.
Logon attempts are retrieved from events in the security eventlog with eventid 4624 and 4625.
Each computer is queried as a separate job. The output of all jobs is merged in the end.
.EXAMPLE
Get-3LLogonEventAccountName -InformationAction Continue
Get all logon events on the local machine and displays status messages.
.EXAMPLE
Get-3LLogonEventAccountName -afterDate (Get-Date).addDays(-14)
Get all logon events on the local machine in the last 14 days
.EXAMPLE
Get-3LLogonEventAccountName -afterDate (Get-Date).addHours(-1)
Get all logon events on the local machine in the hour
.EXAMPLE
Get-3LLogonEventAccountName -computerName SVR1, SVR2 -Progress
Get all logon events on the specified computers.
During analyzing the Security log Events, a progressbar is displayed.
.EXAMPLE
Get-3LLogonEventAccountName -InformationVariable info
$info | Where Tags -eq 'Success'
The first command collect all logon events on the local computer.
Messages from the Information stream are collected in the info variable
The second command shows all Information messages tagged as 'Success'
.NOTES
Author: Frits van Drie (3-Link.nl)
Date : 2021-10-20
#>
[CmdletBinding()]
param(
[string[]]$computerName,
[datetime]$afterDate = (Get-Date).AddDays(-1),
[switch]$progress
)
Begin {
Function Write--JobProgress {
<#
.NOTES
Date: 2021-10-19
#>
param($job)
# Make sure the first child job exists
if($job.ChildJobs[0].Progress -ne $null) {
# Extract the latest progress of the job and write the progress
$jobProgressHistory = $job.ChildJobs[0].Progress
$latestProgress = $jobProgressHistory[$jobProgressHistory.Count - 1]
$latestPercentComplete = $latestProgress | Select -expand PercentComplete
$latestActivity = $latestProgress | Select -expand Activity
$latestStatus = $latestProgress | Select -expand StatusDescription
# a unique ID per ProgressBar
if ( $latestProgress.PercentComplete -ge 0 ) {
Write-Progress -Id $job.Id -Activity $latestActivity -Status $latestStatus -PercentComplete $latestPercentComplete
}
}
}
# module PSScriptTools required
try {
$module = 'PSScriptTools'
Import-Module $module -ErrorAction Stop
Write-Information "SUCCESS: Imported Module: $module"
$function_ConvertEventLogRecord = "Function Convert-EventLogRecord {" + (Get-Item function:Convert-EventLogRecord).ScriptBlock + " }"
}
catch {
Write-Information "FAILURE: Could not import required Module: $module"
Write-Error $_
Break
}
if ( ($PSBoundParameters.Keys -notcontains 'computerName') -or ($computerName -eq 'localhost') ) {
$computerName = $env:COMPUTERNAME
}
$msec = ((Get-Date)- $afterDate).TotalMilliseconds
$xml = @"
<QueryList>
<Query Id="0" Path="Security">
<Select Path="Security">*[System[(Level=2 or Level=4 or Level=0) and (EventID=4624 or EventID=4625) and (TimeCreated[timediff(@SystemTime) `<= $msec])]]</Select>
</Query>
</QueryList>
"@ # xmlFilter
[array]$startedJobs = @()
} # end Begin{}
Process {
foreach ( $computer in $computerName ) {
$jobName = "LogonEvents-$computer"
Write-Information "STATUS : Running Job $jobName" -Tags 'Status'
$job = Start-Job -Name $jobName -ArgumentList $xml, $computer, $progress, $function_ConvertEventLogRecord {
param($xml, $computer, $progress, $function_ConvertEventLogRecord)
Write-Information "STATUS : Setting up session to computer $computer" -Tags 'Status'
try {
New-PSSession -ComputerName $computer -ErrorAction Stop
Write-Information "SUCCESS: Connected to computer $computer" -Tags 'Success'
} # try New-PSSession
catch {
Write-Information "FAILURE: Session to computer $computer failed" -Tags 'Failure'
continue
}
if ( $session = Get-PSSession -ComputerName $computer -ErrorAction SilentlyContinue) {
Write-Information "STATUS : Starting Invoke-Command to computer $computer" -Tags 'Status'
$outputInvoke = Invoke-Command -Session $session -ArgumentList $xml, $progress, $activity, $function_ConvertEventLogRecord {
param($xml, $progress, $activity, $function_ConvertEventLogRecord)
iex $function_ConvertEventLogRecord # load function: Convert-EventLogRecord
$computer = $env:COMPUTERNAME
$splatParam = @{}
$splatParam.add('FilterXml', $xml)
$splatParam.add('ComputerName', $computer)
try {
Write-Information "STATUS : Reading events from computer $computer" -Tags 'Status'
$events = Get-WinEvent @splatParam -ErrorAction Stop
$total = $events.Count
}
catch {
Write-Information "INFO : $($_.tostring())"
Write-Error $_
return
}
$activity = "Analyzing $total Events from computer $computer"
Write-Information "STATUS : $activity" -Tags 'Status'
$done = 0
$returnInvoke = @()
foreach ($event in $events) {
$obj = Convert-EventLogRecord $event
$returnInvoke += $obj
if ( $progress ) {
$done++
Write-Progress -Activity $activity -Status "$done\$total" -PercentComplete ($done/$total*100)
}
} # end foreach event
if ( $progress ) {
Write-Progress -Activity $activity -Status "$done\$total" -PercentComplete ($done/$total*100)
#Write-Progress -Activity $activity -Completed
}
return $returnInvoke
}
# end Invoke-Command
Get-PSSession -ComputerName $computer | Remove-PSSession
return $outputInvoke
} # end if Get-PSSession
} # end Start-Job
[array]$startedJobs += $job
} # end foreach computer
Write-Information ""
} # end Process{}
End {
# while ( $jobs = (Get-Job -Name '*-LogonEvents') ) {
Write-Information "STATUS : Waiting for jobs to finish`n"
while ( $startedJobs ) {
# foreach ( $job in $jobs ) {
foreach ( $job in $startedJobs ) {
$jobState = $job.State # to prevent status changes during processing
if ($jobState -eq 'Completed' ) {
Write--JobProgress -job $job
Write-Information "STATUS : Importing results from job: $(($job).Name)" -Tags 'Status'
$receivedJob = Receive-Job $job
$job | Remove-Job
$startedJobs = $startedJobs | Where {$_ -ne $job}
if ($receivedJob.length -gt 1) {
# remove the first item which is the job
[array]$outputJob += $receivedJob[1..($receivedJob.length-1)]
}
Write-Information "SUCCESS: Job ready: $(($job).Name)`n" -Tags 'Success'
}
else {
Write--JobProgress -job $job
#sleep 1
}
} # end foreach job
} # end While
Write-Output $outputJob
} # end End{}
}
Function Write-3LNetworkConfigurationToFile {
<#
.SYNOPSIS
Find text in a file
.NOTES
Author : Frits van Drie (3-Link.nl)
Versions : 2021.09.24
.EXAMPLE
SaveNetworkConfigurationToFile -openFile
.EXAMPLE
SaveNetworkConfigurationToFile -path 'C:\data\network.txt'
#>
[CmdletBinding()]
param (
[string]$path = "$($env:USERPROFILE)\Documents\$($env:COMPUTERNAME)-$($MyInvocation.MyCommand)-$(Get-Date -Format yyyyMMdd_HHmmss).txt",
[string]$header,
[switch]$openFile,
[switch]$noFile
)
[array]$result = @()
$result += "================================================================================================="
$result += "Computer : $($env:COMPUTERNAME)"
$result += "Date : $(Get-Date -Format 'yy-MM-dd (HH:mm:ss)')"
if ($MyInvocation.BoundParameters.ContainsKey('header')) {
$result += "Description: $header"
}
$result += "=================================================================================================`n"
# Gather info
try {
$result += "`n================================================================================================="
$result += "Get-NetAdapter"
$result += "=================================================================================================`n"
$result += Get-NetAdapter -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Get-NetIPAddress"
$result += "=================================================================================================`n"
$result += Get-NetIPAddress -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Get-NetRoute"
$result += "=================================================================================================`n"
$result += Get-NetRoute -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Get-DnsClientCache"
$result += "=================================================================================================`n"
$result += Get-DnsClientCache -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Show-DnsServerCache"
$result += "=================================================================================================`n"
(Get-DnsClientServerAddress -Family IPv4 | Where serveraddresses ).serveraddresses | foreach {
$result += "`n===================="
$result += "DNS: $_"
$result += "====================`n"
try {
$result += Show-DnsServerCache -ComputerName $_ -ea Stop
}
catch {
$result += "Cache of $_ could not be read"
}
}
$result += "`n================================================================================================="
$result += "Get-NetTCPConnection"
$result += "=================================================================================================`n"
$result += Get-NetTCPConnection -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Get-Process"
$result += "=================================================================================================`n"
$result += Get-Process -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Get-DnsClientServerAddress"
$result += "=================================================================================================`n"
$result += Get-DnsClientServerAddress -ErrorAction Stop | ft -AutoSize
$result += "`n================================================================================================="
$result += "Certificates"
$result += "=================================================================================================`n"
$result += GCI 'Cert:\LocalMachine\My' -ErrorAction Stop | ft -AutoSize
$result += GCI 'Cert:\CurrentUser\My' -ErrorAction Stop | ft -AutoSize
}
catch {
Write-Error $error[0]
break
}
if ( $noFile ) {
$openFile = $true
$path = Join-Path $env:TEMP (Split-Path $path -Leaf)
}
try {
$result | Out-File $path -Append -ErrorAction Stop -Width 200
}
catch {
Write-Error $error[0]
break
}
if ($openFile) {
notepad.exe $path
}
if ($noFile) {
Write-Verbose "Network configuration saved to $path"
Start-Sleep 2
Remove-Item $path -Force -ea SilentlyContinue
}
else {
Write-Host "Network configuration saved to $path" -f Yellow
}
}
Function Out-3LNotepad {
param
(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[String]
[AllowEmptyString()]
$Text
)
begin
{
$sb = New-Object System.Text.StringBuilder
}
process
{
$null = $sb.AppendLine($Text)
}
end
{
$text = $sb.ToString()
$process = Start-Process notepad -PassThru
$null = $process.WaitForInputIdle()
$sig = '
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
'
$type = Add-Type -MemberDefinition $sig -Name APISendMessage -PassThru
$hwnd = $process.MainWindowHandle
[IntPtr]$child = $type::FindWindowEx($hwnd, [IntPtr]::Zero, "Edit", $null)
$null = $type::SendMessage($child, 0x000C, 0, $text)
}
}
Function Publish-3LScriptOrModule {
<#
.NOTES
Author: Frits van Drie (3-Link.nl)
Date : 2021-10-20
.SYNOPSIS
Publishes a script or module to a private or online repository
.DESCRIPTION
Publishes a script (ps1) or module (psm1) to a private or online repository {PSGallery).
Before a module is published, a manifest file is created in the same folder. By default all functions in the module are exported.
If an online repository (PSGallery) is used, a NuGet apiKey is needed.
.PARAMETER ScriptPath
Specifying this parameter will let you publish a script (only .ps1 extensions are valid)
.PARAMETER ModulePath
Specifying this parameter will let you publish a module (only .psm1 extensions are valid)
.PARAMETER Repository
This allows you to specify a private repository instead of the default PSGallery
.PARAMETER GetSavedSettings
Using this parameter settings are listed from a json-file in the user profile.
Settings saved in this file: ApiKey, Author, Company, Copyright, Description, Repository
.PARAMETER UseSavedSettings
Using this parameter some parameters and values are retrieved from json-file in the user profile.
When a parameter is also specified in the command, it will override that setting.
Settings saved in this file: ApiKey, Author, Company, Copyright, Description, Repository
.PARAMETER SaveSettings
Use this parameter to save some settings to a json-file in the user profile.
Settings saved in this file: ApiKey, Author, Company, Copyright, Description, Repository
.PARAMETER FunctionsToExport
This parameter let you specify the FunctionsToExport in the module-manifest file. By default all commands in the module-file are added
Specifying the parameter will override the default.
.PARAMETER Force
Force can only be used when publishing a script.
It allows you to overwrite an existing scriptpackage with the same version
.EXAMPLE
Publish-3LScriptOrModule -GetSavedSettings
This lists the current settings in the json-file that is stored under AppData\Local
If no file exists, a new file is created. Use the saveSettings parameter to update the default values.
.EXAMPLE
Publish-3LScriptOrModule -author $author -company $company -copyright $copyright -description $description -SaveSettings.
This command publishes a module to a private repository. Some settings will be saved in a json-file in the user profile
.EXAMPLE
Publish-3LScriptOrModule `
-author $author -company $company -copyright $copyright -description $description -repository 'PSGallery' -scriptPath $scriptpath -version 1.0.0 -Force
This command publishes a script to the PSGallery. If the version is already present it will be overwritten (-Force).
.EXAMPLE
Publish-3LScriptOrModule -repository 'PSGallery' -scriptPath $scriptpath -version 1.0.0 -UseSavedSettings -verbose
This command publishes a script to the PSGallery. Settings stored in json-file are used.
.EXAMPLE
Publish-3LScriptOrModule -saveSettings -author $author -company $company -copyright $copyright -description $description -repository $repository -apiKey $apiKey
This creates a new json settingsfile in the user profile or overwrites an existing file
.EXAMPLE
Publish-3LScriptOrModule -saveSettings -author 'Joe Codex'
This updates the json settingsfile
#>
[CmdletBinding(DefaultParameterSetName="Module")]
param(
[parameter(ParameterSetName='Script', mandatory=$true, position=0)]
[string]$scriptPath,
[parameter(ParameterSetName='Module', mandatory=$true, position=0)]
[string]$modulePath,
[parameter(ParameterSetName='Script', mandatory=$false, position=1)]
[parameter(ParameterSetName='Module', mandatory=$false, position=1)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false, position=1)]
[string]$repository = 'PSGallery',
[parameter(ParameterSetName='Script', mandatory=$false, position=2)]
[parameter(ParameterSetName='Module', mandatory=$false, position=2)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false, position=2)]
[string]$apiKey,
[parameter(ParameterSetName='Script' , mandatory=$false, position=3)]
[parameter(ParameterSetName='Module' , mandatory=$false, position=3)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false, position=3)]
[string]$author,
[parameter(ParameterSetName='Script', mandatory=$false, position=4)]
[parameter(ParameterSetName='Module', mandatory=$false, position=4)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false)]
[string]$description,
[parameter(ParameterSetName='Script', mandatory=$false, position=5)]
[parameter(ParameterSetName='Module', mandatory=$false, position=5)]
[string]$version,
[parameter(ParameterSetName='Script', mandatory=$false, position=6)]
[parameter(ParameterSetName='Module', mandatory=$false, position=6)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false, position=6)]
[string]$company,
[parameter(ParameterSetName='Script', mandatory=$false, position=7)]
[parameter(ParameterSetName='Module', mandatory=$false, position=7)]
[parameter(ParameterSetName='WriteSettings', mandatory=$false, position=7)]
[string]$copyright,
[parameter(ParameterSetName='Module', mandatory=$false, position=8)]
[array]$functionsToExport,
[parameter(ParameterSetName='Script', mandatory=$false)]
[Switch]$Force=$false,
[parameter(ParameterSetName='ReadSettings', mandatory=$false)]
[Switch]$GetSavedSettings=$false,
[parameter(ParameterSetName='Script', mandatory=$false)]
[parameter(ParameterSetName='Module', mandatory=$false)]
[Switch]$UseSavedSettings=$false,
[parameter(ParameterSetName='WriteSettings', mandatory=$false)]
[Switch]$SaveSettings=$false
)
# Variables
$settingsName = $MyInvocation.MyCommand.Name
$settingsFolder = "$env:LOCALAPPDATA\3-Link\$settingsName"
$settingsFile = "$settingsName.json"
$settingsPath = "$settingsFolder\$settingsFile"
Function ImportSettingsFromFile {
if ( -not(Test-Path $settingsPath -ErrorAction SilentlyContinue) ) {
Write-Verbose "FAILURE: Settingsfile not found: $settingsPath"
try {
Write-Verbose "INFO : Creating new file: $settingsPath"
$objSettings = @{}
$objSettings.add('apiKey' , 'update this')
$objSettings.add('author' , 'update this')
$objSettings.add('company' , 'update this')
$objSettings.add('copyright' , 'update this')
$objSettings.add('description', 'update this')
$objSettings.add('repository' , 'PSGallery')
New-Item (Split-Path $settingsPath -Parent) -ItemType Directory -Force
$objSettings | ConvertTo-Json -ErrorAction Stop | Out-File $settingsPath -ErrorAction Stop
Write-Verbose "SUCCESS: Created new file: $settingsPath"
}
catch {
Write-Error $_
break
} #end try\catch
} # end If
Write-Verbose "SUCCESS: $settingsPath found"
Write-Verbose "INFO : Importing Settings from $settingsPath"
$settings = Get-Content $settingsPath | ConvertFrom-Json
Write-Verbose "SUCCESS: Settings imported"
return $settings
}
# Import Settings
if ( $UseSavedSettings -or $GetSavedSettings ) {
$settings = ImportSettingsFromFile
if ( $GetSavedSettings ) {
return $settings
}
if ( $PSBoundParameters.Keys -notcontains 'apiKey' ) {
$apiKey = $settings.apiKey
}
if ( $PSBoundParameters.Keys -notcontains 'author' ) {
$author = $settings.author
}
if ( $PSBoundParameters.Keys -notcontains 'company' ) {
$company = $settings.company
}
if ( $PSBoundParameters.Keys -notcontains 'copyright' ) {
$copyright = $settings.copyright
}
if ( $PSBoundParameters.Keys -notcontains 'description' ) {
$description = $settings.description
}
if ( $PSBoundParameters.Keys -notcontains 'repository' ) {
$repository = $settings.repository
}
}
# Save Settings
if ( $SaveSettings ) {
$settings = ImportSettingsFromFile
if ( $PSBoundParameters.Keys -contains 'apiKey' ) {
$settings.apiKey = $apiKey
}
if ( $PSBoundParameters.Keys -contains 'author' ) {
$settings.author = $author
}
if ( $PSBoundParameters.Keys -contains 'company' ) {
$settings.company = $company
}
if ( $PSBoundParameters.Keys -contains 'copyright' ) {
$settings.copyright = $copyright
}
if ( $PSBoundParameters.Keys -contains 'description' ) {
$settings.description = $description
}
if ( $PSBoundParameters.Keys -contains 'repository' ) {
$settings.repository = $repository
}
# Save settings
try {
Write-Verbose "INFO : Creating folder: $settingsFolder"
$null = New-Item -Path $settingsFolder -ItemType Directory -Force -ErrorAction Stop
Write-Verbose "SUCCESS: Created folder: $settingsFolder"
Write-Verbose "INFO : Saving settings to $settingsPath"
$settings | ConvertTo-Json | Out-File $settingsPath -ErrorAction Stop
Write-Verbose "SUCCESS: Saved settings to $settingsPath"
return $settings
}
catch {
Write-Error $_
return
}
} # end SaveSettings
# FilePath
if ( $PSBoundParameters.Keys -contains 'scriptPath') {
$filePath = $scriptPath
}
elseif ( $PSBoundParameters.Keys -contains 'modulePath') {
$filePath = $modulePath
}
try {
if ( -not (Test-Path $filePath -ErrorAction Stop) ) {
Throw
}
else {
Write-Verbose "SUCCESS: File exists"
}
}
catch {
Write-Error "$filePath is not a valid file"
return
} # end try\catch
# Repository
if ( $repository -in (Get-PSRepository).Name ) {
Write-Verbose "SUCCESS: $repository exists"
# Repo trusted
if ( (Get-PSRepository -Name $repository).InstallationPolicy -ne 'Trusted' ) {
Write-Error "$repository is not a trusted repository"
return
}
else {
Write-Verbose "SUCCESS: $repository is trusted"
}
}
else {
Write-Error "$repository is not a valid repository"
return
}
# PowerShellGet
Write-Verbose "TEST : Test PowerShellGet version"
if ( (Get-Module -Name PowerShellGet -ListAvailable).Version -lt 2.2.5 ) {
Write-Error "PowerShellGet version 2.2.5 is required"
break
}
Write-Verbose "SUCCESS: PowerShellGet requirements confirmed"
# TLS 12
Write-Verbose "TEST : TLS version min. Tls12 "
if ( ([System.Net.ServicePointManager]::SecurityProtocol).value__ -lt 3072 ) {
#Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols'
Write-Error "Tls12 or newer is required. Use `'[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12`' to enable Tls12"
break
}
Write-Verbose "SUCCESS: TLS requirements confirmed"
# script or module
Write-Verbose "TEST : File extension"
if ( $PSBoundParameters.Keys -contains 'ScriptPath') {
if ( (Get-Item $filePath).Extension -eq '.ps1' ){
$scriptName = (Split-Path $filePath -Leaf).Split('.')[0]
Write-Verbose "SUCCESS: Valid script: $filePath"
}
else {
Write-Error "Fileformat not supported: $filePath (only .ps1 is a valid extension)"
return
}
} # end ScriptPath
if ( $PSBoundParameters.Keys -contains 'ModulePath') {
if ( (Get-Item $filePath).Extension -eq '.psm1' ){
$moduleName = (Split-Path $filePath -Leaf).Split('.')[0]
Write-Verbose "SUCCESS: Valid module: $filePath"
}
else {
Write-Error "Fileformat not supported: $filePath (only .psm1 is a valid extension)"
return
}
} # end ModulePath
# is repository private or online
Write-Verbose "TEST : Is repository Local or Online"
if ( $repoIsLocal = Test-Path (Get-PSRepository $repository).sourcelocation ) {
Write-Verbose "INFO : $repository is a private repository"
} # local Repo
else {
Write-Verbose "INFO : $repository is an online repository"
# Validate apiKey
if ( $apiKey -notmatch "^[a-z0-9]{46}$" ) {
Write-Error "Not a valid ApiKey: $apiKey"
return
}
Write-Verbose "SUCCESS: APIKey $apiKey has a valid format"
} # online Repo
# Publish Script
if ($PSBoundParameters.Keys -contains 'ScriptPath') {
$splatScript = @{}
$splatScript.Add('Path', $filePath)
$splatScript.Add('Repository', $repository)
if ( -not($repoIsLocal) ) {
$splatScript.Add('NuGetApiKey', $apiKey)
}
try {
Write-Verbose "INFO : Publishing $filePath to $repository"
Write-Verbose "INFO : Parameter Force: $Force"
$publishedItem = Publish-Script @splatScript -ErrorAction Stop -Force:$Force
$publishedItem = Find-Script -Name $LOCAL:scriptName -Repository $repository -ErrorAction Stop
Write-Verbose "SUCCESS: Publishing $filePath to $repository successfull"
Write-Output $publishedItem
}
catch {
Write-Error $_
return
} # end try\catch
} # end publish Script
# Publish Module
if ($PSBoundParameters.Keys -contains 'ModulePath') {
if ( $PSBoundParameters.Keys -notcontains 'functionsToExport' ) {
[array]$functionsToExport = (Import-Module $modulePath -PassThru).ExportedCommands.keys
}
try {
Write-Verbose "INFO : Creating Manifest $manifestPath"
$manifestPath = $filePath.replace('psm1','psd1')
$manifestFile = New-ModuleManifest `
-Path $manifestPath `
-Author $author `
-CompanyName $company `
-Copyright $copyright `
-RootModule $moduleName `
-Description $description `
-ModuleVersion $version `
-FunctionsToExport $functionsToExport `
-PassThru `
-ErrorAction Stop
Write-Verbose "SUCCESS: Manifest created"
Write-Verbose "INFO : Testing Manifest $manifestPath"
$null = Test-ModuleManifest `
-Path $modulePath.replace('psm1','psd1') `
-ErrorAction Stop
Write-Verbose "SUCCESS: Manifest tested"
} # try New-ModuleManifest
catch {
Write-Error $_
Break
} # end try\catch
try {
Write-Verbose "INFO : Publishing $filePath to $repository"
Write-Verbose "INFO : Parameter Force: $Force"
$splatModule = @{}
$splatModule.Add('Path' , $moduleFolder)
$splatModule.Add('Repository' , $repository)
$splatModule.Add('Force' , $Force)
if ( $repository -eq 'PSGallery' ) {
$splatModule.Add('NuGetApiKey', $apiKey)
}
$publishedItem = Publish-Module @splatModule -ErrorAction Stop #-WhatIf
$publishedItem = Find-Module $LOCAL:moduleName -Repository $repository -ErrorAction Stop
Write-Verbose "SUCCESS: Publishing $filePath to $repository successfull"
Write-Output $publishedItem
} # try Publish-Module
catch {
$Error[0]
Write-Error $_
return
} # end try\catch
} # end Publish Module
}
Function Find-3LStringInFile {
<#
.SYNOPSIS
Find text in a file
.NOTES
Author : Frits van Drie (3-Link.nl)
Versions : 2021.09.23
.EXAMPLE
FindStringInFile -pattern 'Project' -path "document.txt"
searches document.txt in current folder for 'project' or 'Project'
.EXAMPLE
FindStringInFile -pattern 'Project' -path "document.txt" -caseSensitive
searches document.txt in current folder for 'Project'
.EXAMPLE
gci "C:\Users\user\documents" -File | foreach { FindStringInFile -pattern 'project' -path $_.FullName }
searches all users documents 'project' or 'Project'
#>
[CmdletBinding()]
param (
[parameter(mandatory = $true)]
[string]$pattern,
[parameter(mandatory = $true)]
[string]$path,
[parameter(mandatory = $false)]
[switch]$caseSensitive
)
begin {
Write-Verbose "Start Function: $($MyInvocation.MyCommand)"
}
process {
foreach ($file in $path) {
try {
$objfile = Get-item $path -ea Stop
$result = $objFile | Select-String -Pattern $pattern -ea Stop -CaseSensitive:$caseSensitive
Write-Output $result
}
catch {
Write-Error "File not found: $path"
}
}
}
end {
Write-Verbose "End Function: $($MyInvocation.MyCommand)"
}
}
|
3LToolKit.psd1 | 3LToolKit-211020.1829.0 | #
# Module manifest for module '3LToolkit'
#
# Generated by: F. van Drie (3-link.nl)
#
# Generated on: 20-10-2021
#
@{
# Script module or binary module file associated with this manifest.
RootModule = '3LToolkit'
# Version number of this module.
ModuleVersion = '211020.1829'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'b1d00b06-4fa6-4211-8621-5b65fb12f4db'
# Author of this module
Author = 'F. van Drie (3-link.nl)'
# Company or vendor of this module
CompanyName = '3-Link Opleidingen'
# Copyright statement for this module
Copyright = 'free to use and distribute without modifications'
# Description of the functionality provided by this module
Description = 'Developed by 3-Link Opleidingen for training purposes only'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Find-3LStringInFile', 'Get-3LLogonEventAccountName', 'Out-3LNotepad',
'Publish-3LScriptOrModule', 'Write-3LNetworkConfigurationToFile'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
3LWakeOnLan.psd1 | 3LWakeOnLan-211021.1216.0 | #
# Module manifest for module '3LWakeOnLan'
#
# Generated by: F. van Drie (3-link.nl)
#
# Generated on: 10/21/2021
#
@{
# Script module or binary module file associated with this manifest.
RootModule = '3LWakeOnLan'
# Version number of this module.
ModuleVersion = '211021.1216.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'e2e717c0-f7f6-4093-9485-4589220918da'
# Author of this module
Author = 'F. van Drie (3-link.nl)'
# Company or vendor of this module
CompanyName = '3-Link Opleidingen'
# Copyright statement for this module
Copyright = 'free to use and distribute without modifications'
# Description of the functionality provided by this module
Description = 'Developed by 3-Link Opleidingen for training purposes only'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Add-ComputerMacAddressToFile', 'Add-ComputerMacAddressToRegistry',
'Get-ComputerMacAddressFromFile', 'Get-MacAddress',
'Invoke-WakeUpComputer', 'IsValidMacAddress',
'Remove-ComputerMacAddressFromFile', 'Start-Computer'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
3LWakeOnLan.psm1 | 3LWakeOnLan-211021.1216.0 | # Name : 3LWakeOnLan.psm1
# Author : Frits van Drie (3-Link.nl)
# Date : 2021-10-20
Function Invoke-WakeUpComputer {
<#
.SYNOPSIS
Send a Wake-On-LAN magic packet
.DESCRIPTION
Send a Wake-On-LAN magic packet to all passed MAC-addresses
UDP-port defaults to 7
IPv4-address defaults to 255.255.255.255
The following separators in the MAC-address are accepted: - (dash), : (colon), . (dot)
.EXAMPLE
Start-Computer -macAddress '6805CAAF534A', 'B4-2E-99:A6.55.2D'
Start-Computer -macAddress 'C8-60-00-BF-B8-7E', '00-15-5D-00-02-A8'
Broadcasts a magic packet to multiple mac-addresses through UDP-port 7
Separator characters are removed
.EXAMPLE
Start-Computer -macAddress '6805CAAF534A' -Port 9 -Verbose
Broadcasts a magic packet through UDP-port 9
.NOTES
Author : Frits van Drie (3-Link.nl)
Versions : 2021.09.18
IPv4-address is now optional and defaults to the all-subnet broadcast address
Added support for multiple MAC-addresses
Added support for MAC-address through pipeline
#>
[CmdletBinding()]
Param (
[parameter(mandatory=$true, ValueFromPipeline=$true)]
[string[]]$macAddress,
[ipaddress]$ipv4Address = '255.255.255.255',
[int]$port = 7
)
Begin{
Write-Verbose "Start Function: $($MyInvocation.MyCommand)"
}
Process {
foreach ($mac in $macAddress) {
# Convert mac-address
Write-Verbose "Check MAC-address: $mac"
if ( -not (IsValidMacAddress $mac) ) {
Write-Error "$mac is not a valid MAC-address"
return
}
Write-Verbose "$mac is a valid MAC-address"
Write-Verbose "Convert MAC-address: $mac"
$mac = $mac.replace('-','').Replace(':','').Replace('.','')
$target = 0,2,4,6,8,10 | Foreach {
[convert]::ToByte($mac.substring($_,2),16)
}
Write-Verbose "Create magic packet"
$packet = (,[byte]255 *6) + ($target * 16)
$udpClient = New-Object System.Net.Sockets.UdpClient
Write-Verbose "Send magic packet (MAC: $mac, IPv4: $ipv4Address, Port: UDP-$port)"
Write-Verbose "`t`tMAC : $mac"
Write-Verbose "`t`tIPv4: $ipv4Address"
Write-Verbose "`t`tPort: UDP-$port"
$udpClient.Connect($ipv4Address, $port)
[void]$udpClient.Send($packet, 102)
}
} # process
End {
Write-Verbose "End Function: $($MyInvocation.MyCommand)"
}
}
Function Get-MacAddress{
<#
.SYNOPSIS
Get a computer network hardware address
.DESCRIPTION
.NOTE
Last modified: 2021-10-20
.AUTHOR
Frits van Drie (3-Link.nl)
#>
Param (
[parameter(mandatory=$true)]
[string[]]$computerName
)
foreach ($computer in $computerName) {
try {
$networkadapterconfiguration = Get-CimInstance win32_networkadapterconfiguration -ComputerName $computer | select description, macaddress -ea Stop
}
catch {
Write-Error $Error[0]
}
Write-Output $networkadapterconfiguration
}
}
Function IsValidMacAddress {
<#
.SYNOPSIS
Checks the validity of a given mac-address
.DESCRIPTION
Checks the validity of a given mac-address. Valid separators are: dash (-), colon (:) and dot (.)
.INPUT
String
.OUTPUT
Boolean
.NOTE
Last modified: 2021-09-21
.AUTHOR
Frits van Drie (3-Link.nl)
#>
[CmdletBinding()]
param (
[parameter(mandatory=$true, position=0)]
[string]$macAddress
)
if ( $macAddress -match "([a-fA-F0-9]{2,2}[:\-\.]{0,1}){5}([a-fA-F0-9]{2,2}){1}$" ) {
return $true
}
else {
return $false
}
}
Function Add-ComputerMacAddressToRegistry{
<#
.SYNOPSIS
Save a computer network hardware address in the local registry
.DESCRIPTION
.NOTE
Last modified: 2021-09-20
.AUTHOR
Frits van Drie (3-Link.nl)
#>
[CmdletBinding()]
param (
[parameter(mandatory=$true)]
[string]$computerName,
[parameter(mandatory=$true)]
[string]$macAddress
)
Begin {
Write-Verbose "Start Function: $($MyInvocation.MyCommand)"
try {
$regKey = "HKCU:\Software\3-Link\PSWakeOnLan"
Write-Verbose "Check registry-key: $regKey"
if ( -not (Test-Path $regKey -ea SilentlyContinue) ) {
Write-Verbose "Create new registry-key: $regKey"
$null = New-Item $regKey -Force -ea Stop
Write-Verbose "Success"
}
}
catch {
Write-Verbose "Error creating registry-key: $regKey"
Write-Error $Error[0]
Return
}
}
Process{
# Convert mac-address
Write-Verbose "Check MAC-address: $mac"
if ( -not (IsValidMacAddress $mac) ) {
Write-Error "$mac is not a valid MAC-address"
return
}
Write-Verbose "$mac is a valid MAC-address"
try {
Write-Verbose "Add property $computerName to $regKey"
$null = New-ItemProperty -Name $computerName -Path $regKey -Value $mac -ea Stop
Write-Verbose "Success"
}
catch [System.IO.IOException]{
try {
Write-Verbose "Add $mac to property $regkey\$computerName"
$value = (Get-ItemProperty -Path $regKey).$computerName
$mac = "$value;$mac"
$null = Set-ItemProperty -Name $computerName -Path $regKey -Value $mac -ea Stop
Write-Verbose "Success"
}
catch [System.IO.IOException]{
Write-Verbose "Error adding $mac to $regKey\$computerName"
Write-Error $Error[0]
Return
}
}
}
End {
Write-Verbose "End Function: $($MyInvocation.MyCommand)"
}
}
Function Get-ComputerMacAddressFromFile {
[CmdletBinding()]
param(
[string]$filePath = 'C:\Users\fvd\AppData\Roaming\3-Link\PowerShell\WakeOnLan.json',
[string]$computerName = '*',
[string]$macAddress = '*',
[string]$ipv4Address = '*',
[string]$port = '*'
)
# Check filePath
if ( -not (Test-Path $filePath) ) {
Write-Error "File not found: $filePath"
return
}
try {
[array]$arr = Get-Content $filePath | ConvertFrom-Json -ea Stop
$result = $arr | Where { ($_.computerName -like $computerName) -and ($_.macAddress -like $macAddress) -and ($_.ipv4Address -like $ipv4Address) -and ($_.port -like $port) }
}
catch {
Write-Error "$filePath is not a valid JSON-file"
return
}
Write-Output $result
}
Function Add-ComputerMacAddressToFile {
[CmdletBinding()]
param(
[string]$filePath = 'C:\Users\fvd\AppData\Roaming\3-Link\PowerShell\WakeOnLan.json',
[parameter(mandatory=$true)]
[string]$computerName,
[parameter(mandatory=$true)]
[string]$macAddress,
[parameter(mandatory=$false)]
[string]$ipv4Address = '255.255.255.255',
[parameter(mandatory=$false)]
[string]$port = 7
)
Begin {
Write-Verbose "Start Function ($($MyInvocation.MyCommand))"
# Check filePath
if ( -not (Test-Path $filePath) ) {
try {
Write-Verbose "Create new file: $filePath"
New-Item $filePath -ItemType File -ErrorAction Stop
Write-Verbose "Success"
}
catch {
Write-Verbose "Error creating new file: $filePath"
Write-Error $Error[0]
break
}
}
try {
Write-Verbose "Reading content from file: $filePath"
$content = Get-Content $filePath -ErrorAction Stop
}
catch {
Write-Error "Error reading $filePath"
break
}
try {
Write-Verbose "Convert content from file to JSON"
[array]$arr = $content | ConvertFrom-Json -ErrorAction Stop
}
catch {
Write-Error "$filePath is not a valid JSON-file"
break
}
}
Process {
# Check mac-address
Write-Verbose "Check MAC-address: $macAddress"
if ( -not (IsValidMacAddress $macAddress) ) {
Write-Error "$macAddress is not a valid MAC-address"
return
}
Write-Verbose "$macAddress is a valid MAC-address"
# Check ipv4-Address
Write-Verbose "Check IPv4-address: $ipv4Address"
<#
if ( -not (IsValidIPv4Address $ipv4Address) ) {
Write-Error "$ipv4Address is not a valid IPv4-address"
return
}
#>
Write-Verbose "$ipv4Address is a valid IPv4-address"
$newEntry = New-Object PSObject
Add-Member -InputObject $newEntry -MemberType NoteProperty -Name 'computerName' -Value $computerName
Add-Member -InputObject $newEntry -MemberType NoteProperty -Name 'macAddress' -Value $macAddress
Add-Member -InputObject $newEntry -MemberType NoteProperty -Name 'ipv4Address' -Value $ipv4Address
Add-Member -InputObject $newEntry -MemberType NoteProperty -Name 'port' -Value $port
# Check for duplicates
Write-Verbose "Check for duplicates"
$duplicateFound = $arr | Where { "$_" -eq $newEntry }
if ( $duplicateFound ) {
Write-Warning "Entry for $computerName already exists"
Write-Verbose $duplicateFound
return
}
# Add entry to File
$arr += $newEntry
try {
Write-Verbose "Convert content to JSON"
$json = $arr | ConvertTo-Json -ea Stop
}
catch {
Write-Verbose "Error converting content to JSON"
Write-Error $Error[0]
Return
}
try {
Write-Verbose "Write new JSON-content to file: $filePath"
$json | Set-Content $filePath -ea Stop
}
catch {
Write-Verbose "Error writing content to file: $filePath"
Write-Error $Error[0]
Return
}
}
End {
Write-Verbose "End Function ($($MyInvocation.MyCommand))"
}
}
Function Remove-ComputerMacAddressFromFile {
[CmdletBinding()]
param(
[string]$filePath = 'C:\Users\fvd\AppData\Roaming\3-Link\PowerShell\WakeOnLan.json',
[parameter(mandatory=$true)]
[string]$computerName,
[parameter(mandatory=$false)]
[string]$macAddress = '*',
[parameter(mandatory=$false)]
[string]$ipv4Address = '*',
[parameter(mandatory=$false)]
[string]$port = '*'
)
Begin {
Write-Verbose "Start Function ($($MyInvocation.MyCommand))"
# Check filePath
if ( -not (Test-Path $filePath) ) {
Write-Verbose "File not found: $filePath"
Write-Error $Error[0]
break
}
# Read file
try {
Write-Verbose "Reading content from file: $filePath"
$content = Get-Content $filePath -ErrorAction Stop
}
catch {
Write-Error "Error reading $filePath"
break
}
# Convert content from JSON
try {
Write-Verbose "Convert content from file to JSON"
[array]$arr = $content | ConvertFrom-Json -ErrorAction Stop
}
catch {
Write-Error "$filePath is not a valid JSON-file"
break
}
}
Process {
<# # Check mac-address
Write-Verbose "Check MAC-address: $macAddress"
if ( -not (IsValidMacAddress $macAddress) ) {
Write-Error "$macAddress is not a valid MAC-address"
break
}
Write-Verbose "$macAddress is a valid MAC-address"
# Check ipv4-Address
Write-Verbose "Check IPv4-address: $ipv4Address"
<#
if ( -not (IsValidIPv4Address $ipv4Address) ) {
Write-Error "$ipv4Address is not a valid IPv4-address"
return
}
#>
# Write-Verbose "$ipv4Address is a valid IPv4-address"
#>
# Define object to remove
$entry = New-Object PSObject
Add-Member -InputObject $entry -MemberType NoteProperty -Name 'computerName' -Value $computerName
Add-Member -InputObject $entry -MemberType NoteProperty -Name 'macAddress' -Value $macAddress
Add-Member -InputObject $entry -MemberType NoteProperty -Name 'ipv4Address' -Value $ipv4Address
Add-Member -InputObject $entry -MemberType NoteProperty -Name 'port' -Value $port
# Find object
Write-Verbose "Find entry"
$entryFound = $arr | Where { ($_.computerName -like $computerName) -and ($_.macAddress -like $macAddress) -and ($_.ipv4Address -like $ipv4Address) -and ($_.port -like $port) }
#"$_" -eq $entry }
if ( -not $entryFound ) {
Write-Verbose "Entry not found"
return
}
Write-Verbose "Entry found"
# Remove entry from array
foreach ($item in $entryFound) {
$arr = $arr | Where { "$_" -ne $item }
}
try {
Write-Verbose "Convert content to JSON"
$json = $arr | ConvertTo-Json -ea Stop
}
catch {
Write-Verbose "Error converting content to JSON"
Write-Error $Error[0]
Return
}
try {
Write-Verbose "Write new JSON-content to file: $filePath"
if ( $json -eq $null ) {
$json = ""
}
$json | Set-Content $filePath -ea Stop
}
catch {
Write-Verbose "Error writing content to file: $filePath"
Write-Error $Error[0]
Return
}
}
End {
Write-Verbose "End Function ($($MyInvocation.MyCommand))"
}
}
Function Start-Computer {
[CmdletBinding()]
param(
[parameter(mandatory=$true, position = 0)]
[string]$computerName
)
Get-ComputerMacAddressFromFile -computerName $computerName | foreach {
Invoke-WakeUpComputer -macAddress $_.macAddress -ipv4Address $_.ipv4Address -port $_.port
}
}
|
Remove-3PARHosts.ps1 | 3PAR-Powershell-0.4.0 | Function Remove-3PARHosts {
<#
.SYNOPSIS
Delete a host
.DESCRIPTION
This function will delete a host. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Name of the host to delete
.EXAMPLE
Remove-3PARHosts -Name 'SRV01'
Delete host SRV01
.EXAMPLE
Remove-3PARHosts -Name 'SRV01' -Confirm:$false
Delete host SRV01 without any confirmation
.EXAMPLE
'SRV01','SRV02' | Remove-3PARHosts
Delete host SRV01 and SRV02
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
Switch ($Name.GetType().Name)
{
"string" {
$h = Get-3PARHosts -Name $Name
}
"PSCustomObject" {
$h = $Name
}
}
if ($h) {
if ($pscmdlet.ShouldProcess($h.name,"Remove host")) {
#Build uri
$uri = '/hosts/'+$h.Name
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri $uri -type 'DELETE'
}
}
}
End {
}
}
|
Disconnect-3PAR.ps1 | 3PAR-Powershell-0.4.0 | Function Disconnect-3PAR {
<#
.SYNOPSIS
Delete connection to the HP 3PAR StoreServ array
.DESCRIPTION
This function will delete the key session used for communicating with the HP 3PAR StoreServ array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Disconnect-3PAR
Disconnect the last session to the HP 3PAR StoreServ array
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param(
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
if ($pscmdlet.ShouldProcess($h.name,"Disconnect from array")) {
#Build uri
$uri = '/credentials/'+$global:3parkey
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri $uri -type 'DELETE'
If ($global:3parkey) {
Write-Verbose -Message "Delete key session: $global:3parkey"
Remove-Variable -name 3parKey -scope global
}
If ($global:3parArray) {
Write-Verbose -Message "Delete Array: $global:3parArray"
Remove-Variable -name 3parArray -scope global
}
}
}
End {}
}
|
Remove-3PARVolumes.ps1 | 3PAR-Powershell-0.4.0 | Function Remove-3PARVolumes {
<#
.SYNOPSIS
Remove a storage volume
.DESCRIPTION
This function will remove a storage volume. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Name of the host to delete
.EXAMPLE
Remove-3PARVolumes -Name 'VOL01'
Delete volume SRV01
.EXAMPLE
Remove-3PARVolumes -Name 'VOL01' -Confirm:$false
Delete volume SRV01 without any confirmation
.EXAMPLE
'VOL01','VOL02' | Remove-3PARVolumes
Delete volume SRV01 and VOL02
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
Switch ($Name.GetType().Name)
{
"string" {
$h = Get-3PARVolumes -Name $Name
}
"PSCustomObject" {
$h = $Name
}
}
if ($h) {
if ($pscmdlet.ShouldProcess($h.name,"Remove volume")) {
#Build uri
$uri = '/volumes/'+$h.Name
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri $uri -type 'DELETE'
}
}
}
End {
}
}
|
Format-Result.ps1 | 3PAR-Powershell-0.4.0 | function Format-Result {
[CmdletBinding()]
Param (
[parameter(Mandatory = $true)]
$dataPS,
[parameter(Mandatory = $true)]
[string]$TypeName
)
Begin { $AlldataPS = @() }
Process {
# Add custom type to the resulting oject for formating purpose
Foreach ($data in $dataPS) {
If ($data) {
$data.PSObject.TypeNames.Insert(0,$TypeName)
}
$AlldataPS += $data
}
}
End {return $AlldataPS}
}
|
Show-RequestException.ps1 | 3PAR-Powershell-0.4.0 | Function Show-RequestException {
[CmdletBinding()]
Param(
[parameter(Mandatory = $true)]
$Exception
)
#Exception catch when there's a connectivity problem with the array
If ($Exception.Exception.InnerException) {
Write-Host "Please verify the connectivity with the array. Retry with the parameter -Verbose for more informations" -foreground yellow
Write-Host
Write-Verbose "Status: $($Exception.Exception.Status)"
Write-Verbose "Error code: $($Exception.Exception.Response.StatusCode.value__)"
Write-Verbose "Message: $($Exception.Exception.InnerException.Message)"
Write-Host
}
#Exception catch when the rest request return an error
If ($_.Exception.Response) {
$readStream = New-Object -TypeName System.IO.StreamReader -ArgumentList ($Exception.Exception.Response.GetResponseStream())
$body = $readStream.ReadToEnd()
$readStream.Close()
$result = ConvertFrom-Json -InputObject $body
Write-Host "The array send an error message: $($result.desc)." -foreground yellow
Write-Host "Retry with the parameter -Verbose for more informations" -foreground yellow
Write-Host
Write-Verbose "Status: $($Exception.Exception.Status)"
Write-Verbose "Error code: $($result.code)"
Write-Verbose "HTTP Error code: $($Exception.Exception.Response.StatusCode.value__)"
Write-Verbose "Message: $($result.desc)"
Write-Host
}
}
|
Get-3PARHosts.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARHosts {
<#
.SYNOPSIS
Retrieve informations about Hosts
.DESCRIPTION
This function will retrieve informations about hosts. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARHosts
List all the hosts
.EXAMPLE
Get-3PARHosts -Name 'SRV01'
Retrieve information about the host named SRV01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
$data = $null
#Request
$data = Send-3PARRequest -uri '/hosts' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Hosts'
}
Process {
#Write result + Formating
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
}
|
Set-3PARHosts.ps1 | 3PAR-Powershell-0.4.0 | Function Set-3PARHosts {
<#
.SYNOPSIS
Modify an existing host
.DESCRIPTION
This function will modify an existing host. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Modify the Name of the host.
.PARAMETER AddFCWWNs
One or more WWN to add to the host.
.PARAMETER RemoveFCWWNs
One or more WWN to remove from the host.
.PARAMETER forcePathRemoval
Remove WWN or iSCSI path even if there are VLUNs that are exported to the host.
.PARAMETER Persona
ID of the persona to assign to the host. List of the available personas:
1 : GENERIC
2 : GENERIC_ALUA
3 : GENERIC_LEGACY
4 : HPUX_LEGACY
5 : AIX_LEGACY
6 : EGENERA
7 : ONTAP_LEGACY
8 : VMWARE
9 : OPENVMS
10 : HPUX
11 : WindowsServer
.EXAMPLE
Set-3PARHosts -Name 'SRV01' -newName 'SRV02'
Rename host SRV01 to SRV02
.EXAMPLE
Set-3PARHosts -Name 'SRV01' -Persona 8
Modify SRV01's persona with persona 8 (VMware)
.EXAMPLE
Set-3PARHosts -Name 'SRV01' -Persona 8 -AddFCWWNs '20000000c9695b70','10000000c9695b70'
Set host SRV01 with persona 8 (VMware) and add the specified WWNs
.EXAMPLE
Set-3PARHosts -Name 'SRV01' -Persona 8 -RemoveFCWWNs '20000000c9695b70','10000000c9695b70'
Set host SRV01 with persona 8 (VMware) and remove the specified WWNs
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'New Host Name')]
$Name,
[Parameter(Mandatory = $false,HelpMessage = 'Domain')]
[String]$newName = $null,
[Parameter(Mandatory = $false,HelpMessage = 'Host Personna')]
[ValidateRange(1,11)]
[int]$persona = $null,
[Parameter(Mandatory = $false,HelpMessage = 'Force path removal')]
[switch]$forcePathRemoval,
[Parameter(Mandatory = $false,HelpMessage = 'Host WWN to add')]
[String[]]$AddFCWWNs = $null,
[Parameter(Mandatory = $false,HelpMessage = 'Host WWN to remove')]
[String[]]$RemoveFCWWNs = $null
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
Switch ($Name.GetType().Name)
{
"string" {
$h = Get-3PARHosts -Name $Name
}
"PSCustomObject" {
$h = $Name
}
}
if ($h) {
if ($pscmdlet.ShouldProcess($h.name,"Modify host")) {
# Creation of the body hash
$body = @{}
# Name parameter
If ($newName) {
$body["newName"] = "$($newName)"
}
# persona parameter
If ($persona) {
$body["persona"] = $persona
}
# forcePathRemoval parameter
If ($forcePathRemoval) {
$body["forcePathRemoval"] = $true
}
# AddFCWWNs parameter
If ($AddFCWWNs) {
$body["FCWWNs"] = @()
$WWN = @()
Foreach ($FCWWN in $AddFCWWNs)
{
$FCWWN = $FCWWN -replace ' '
$FCWWN = $FCWWN -replace ':'
If ($FCWWN.Length -ne 16) {
write-host "$($FCWWN) WWN should contains only 16 characters" -foreground red
break
}
$WWN += $FCWWN
}
$body.FCWWNs = $WWN
$body.pathOperation = 1
}
# RemoveFCWWNs parameter
If ($RemoveFCWWNs) {
$body["FCWWNs"] = @()
$WWN = @()
Foreach ($FCWWN in $RemoveFCWWNs)
{
$FCWWN = $FCWWN -replace ' '
$FCWWN = $FCWWN -replace ':'
If ($FCWWN.Length -ne 16) {
write-host "$($FCWWN) WWN should contains only 16 characters" -foreground red
break
}
$WWN += $FCWWN
}
$body.FCWWNs = $WWN
$body.pathOperation = 2
}
#Build uri
$uri = '/hosts/'+$h.Name
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri $uri -type 'PUT' -body $body
# Results
If ($newName) {
Get-3PARHosts -Name $newName
} else {
Get-3PARHosts -Name $h.name
}
}
}
}
End {
}
}
|
Set-3PARVolumes.ps1 | 3PAR-Powershell-0.4.0 | Function Set-3PARVolumes {
<#
.SYNOPSIS
Modify an existing storage volume.
.DESCRIPTION
This function will modify an existing storage volume. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Specifies the name of the volume to modify.
.PARAMETER newName
Specifies a new volume name up to 31 characters in length.
.PARAMETER UserCPG
Specifies the new name of the CPG from which the volume user space will be allocated. It must be part of an AO config.
.PARAMETER comment
Specifies any additional information up to 511 characters for the volume.
.PARAMETER usrSpcAllocWarningPct
This field enables user space allocation warning. It specifies that a warning alert is generated when the reserved user space of the TPVV exceeds the specified percentage of the VV size.
.PARAMETER rmUsrSpcAllocWarning
This field remove user space allocation warning.
.PARAMETER usrSpcAllocLimitPct
This field sets the user space allocation limit. The user space of the TPVV is prevented from growing beyond the indicated percentage of the VV size. After this size is reached, any new writes to the VV will fail.
.PARAMETER rmUsrSpcAllocLimit
This field remove user space allocation limit.
.EXAMPLE
Set-3PARVolumes -Name 'VOL01' -newName 'VOL02'
Rename volume VOL01 to VOL02
.EXAMPLE
Set-3PARVolumes -Name 'VOL01' -rmusrSpcAllocWarning $true'
Remove the space allocation warning for VOL01
.EXAMPLE
Get-3PARVolumes | Set-3PARVolumes -usrSpcAllocWarningPct 90
Set the allocation warning to 90 to all the existing volumes
#>
[CmdletBinding(SupportsShouldProcess = $True,ConfirmImpact = 'High')]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Volume Name')]
[String]$name,
[Parameter(Mandatory = $false,HelpMessage = 'Domain')]
[String]$newName,
[Parameter(Mandatory = $false,HelpMessage = 'User CPG')]
[String]$userCPG,
[Parameter(Mandatory = $false,HelpMessage = 'Additional informations about the volume')]
[String]$comment,
[Parameter(Mandatory = $false,HelpMessage = 'Space allocation warning')]
[int]$usrSpcAllocWarningPct,
[Parameter(Mandatory = $false,HelpMessage = 'Remove space allocation warning')]
[Boolean]$rmUsrSpcAllocWarning = $false,
[Parameter(Mandatory = $false,HelpMessage = 'Space allocation limit')]
[int]$usrSpcAllocLimitPct,
[Parameter(Mandatory = $false,HelpMessage = 'Remove space allocation limit')]
[Boolean]$rmUsrSpcAllocLimit = $false
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
Switch ($Name.GetType().Name)
{
"string" {
$h = Get-3PARVolumes -Name $Name
}
"PSCustomObject" {
$h = $Name
}
}
if ($h) {
if ($pscmdlet.ShouldProcess($h.name,"Modify volume")) {
$body = @{}
# Name parameter
If ($newName) {
$body["newName"] = "$($newName)"
}
# cpg parameter
If ($userCPG) {
$body["userCPG"] = "$($userCPG)"
}
# comment parameter
If ($comment) {
$body["comment"] = "$($comment)"
}
# usrSpcAllocWarningPct parameter
If ($usrSpcAllocWarningPct) {
$body["usrSpcAllocWarningPct"] = $usrSpcAllocWarningPct
}
# rmUsrSpcAllocWarning parameter
If ($rmUsrSpcAllocWarning) {
$body["rmUsrSpcAllocWarning"] = $rmUsrSpcAllocWarning
}
# usrSpcAllocLimitPct parameter
If ($usrSpcAllocLimitPct) {
$body["usrSpcAllocLimitPct"] = $usrSpcAllocLimitPct
}
# rmUsrSpcAllocLimit parameter
If ($rmUsrSpcAllocLimit) {
$body["rmUsrSpcAllocLimit"] = $rmUsrSpcAllocLimit
}
#Build uri
$uri = '/volumes/'+$h.Name
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri $uri -type 'PUT' -body $body
# Results
If ($newName) {
Get-3PARVolumes -Name $newName
} else {
Get-3PARVolumes -Name $h.name
}
}
}
}
End {
}
}
|
New-3PARHosts.ps1 | 3PAR-Powershell-0.4.0 | Function New-3PARHosts {
<#
.SYNOPSIS
Create a new host
.DESCRIPTION
This function will create a new host. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Name of the host
.PARAMETER Domain
Create the host in the specified domain, or default domain if unspecified
.PARAMETER FCWWNs
One or more WWN to set for the host
.PARAMETER Persona
ID of the persona to assign to the host. List of the available personas:
1 : GENERIC
2 : GENERIC_ALUA
3 : GENERIC_LEGACY
4 : HPUX_LEGACY
5 : AIX_LEGACY
6 : EGENERA
7 : ONTAP_LEGACY
8 : VMWARE
9 : OPENVMS
10 : HPUX
11 : WindowsServer
.PARAMETER forceTearDown
If True, force to tear down low-priority VLUN exports
.EXAMPLE
New-3PARHosts -Name 'SRV01'
Create new host SRV01 with default values
.EXAMPLE
New-3PARHosts -Name 'SRV01' -Persona 8
Create new host SRV01 with persona 8 (VMware)
.EXAMPLE
New-3PARHosts -Name 'SRV01' -Persona 8 -FCWWNs '20000000c9695b70','10000000c9695b70'
Create new host SRV01 with persona 8 (VMware) and the specified WWNs
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Name')]
[String]$name,
[Parameter(Mandatory = $false,HelpMessage = 'Domain')]
[String]$domain = $null,
[Parameter(Mandatory = $false,HelpMessage = 'Host WWN')]
[String[]]$FCWWNs = $null,
[Parameter(Mandatory = $false,HelpMessage = 'forceTearDown')]
[Boolean]$forceTearDown = $false,
[Parameter(Mandatory = $false,HelpMessage = 'Host Personna')]
[ValidateRange(1,11)]
[int]$persona = $null
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($name)"
# Domain parameter
If ($domain) {
$body["domain"] = "$($domain)"
}
# forceTearDown parameter
If ($forceTearDown) {
$body["forceTearDown"] = "$($forceTearDown)"
}
# persona parameter
If ($persona) {
$body["persona"] = $persona
}
# FCWWNs parameter
If ($FCWWNs) {
$body["FCWWNs"] = @()
$WWN = @()
Foreach ($FCWWN in $FCWWNs)
{
$FCWWN = $FCWWN -replace ' '
$FCWWN = $FCWWN -replace ':'
If ($FCWWN.Length -ne 16) {
write-host "$($FCWWN) WWN should contains only 16 characters" -foreground red
break
}
$WWN += $FCWWN
}
$body.FCWWNs = $WWN
}
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri '/hosts' -type 'POST' -body $body
# Results
Get-3PARHosts -Name $name
}
End {
}
}
|
Connect-3PAR.ps1 | 3PAR-Powershell-0.4.0 | Function Connect-3PAR {
<#
.SYNOPSIS
Establish connection to the HP 3PAR StoreServ array
.DESCRIPTION
This function will retrieve a key session from the HP 3PAR StoreServ array. This key will be used by the other functions.
.NOTES
Written by Erwan Quelin under Apache licence
Based on the work of Chris Wahl - http://wahlnetwork.com/2015/10/29/tackling-basic-restful-authentication-with-powershell/
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Connect-3PAR -Server 192.168.0.1
Connect to the array with the IP 192.168.0.1
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true,Position = 0,HelpMessage = 'HP 3PAR StoreServ FQDN or IP address')]
[ValidateNotNullorEmpty()]
[String]$Server,
[Parameter(Mandatory = $false,Position = 1,HelpMessage = 'HP 3PAR StoreServ username')]
[String]$Username,
[Parameter(Mandatory = $false,Position = 2,HelpMessage = 'HP 3PAR StoreServ password')]
[SecureString]$Password,
[Parameter(Mandatory = $false,Position = 4,HelpMessage = 'HP 3PAR StoreServ credentials')]
[System.Management.Automation.CredentialAttribute()]$Credentials
)
Write-Verbose -Message 'Validating that login details were passed into username/password or credentials'
if ($Password -eq $null -and $Credentials -eq $null)
{
Write-Verbose -Message 'Missing username, password, or credentials.'
$Credentials = Get-Credential -Message 'Please enter administrative credentials for your HP 3PAR StoreServ Array'
}
Write-Verbose -Message 'Build the URI'
$APIurl = 'https://'+$Server+':8080/api/v1'
Write-Verbose -Message 'Build the JSON body for Basic Auth'
if ($Credentials -eq $null)
{
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
}
$body = @{
user=$Credentials.username;
password=$Credentials.GetNetworkCredential().Password
}
$headers = @{}
$headers["Accept"] = "application/json"
Write-Verbose -Message 'Submit the session key request'
Try
{
$credentialdata = Invoke-WebRequest -Uri "$APIurl/credentials" -Body (ConvertTo-Json -InputObject $body) -ContentType "application/json" -Headers $headers -Method POST -UseBasicParsing
}
catch
{
Show-RequestException -Exception $_
throw
}
$global:3parArray = $Server
$global:3parKey = ($credentialdata.Content | ConvertFrom-Json).key
Write-Verbose -Message "Acquired token: $global:3parKey"
Write-Verbose -Message 'You are now connected to the HP 3PAR StoreServ Array.'
Write-Verbose -Message 'Show array informations:'
Get-3PARSystems | ft
}
|
Check-3PARConnection.ps1 | 3PAR-Powershell-0.4.0 | Function Check-3PARConnection {
[CmdletBinding()]
Param()
Write-Verbose 'Test if the session key exists'
# Validate the 3PAR session key exists
if (-not $global:3parKey)
{
throw 'You are not connected to a 3PAR array. Use Connect-3PAR.'
}
}
|
Get-3PARVLuns.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARVLuns {
<#
.SYNOPSIS
Retrieve informations about virtual luns
.DESCRIPTION
This function will retrieve informations about virtual luns. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARVLuns
List all the virtual luns
.EXAMPLE
Get-3PARVLuns -Name 'VL01'
Retrieve information about the virtual lun named VL01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Virtual LUN Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/vluns' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Vluns'
#Write result + Formating
Write-Verbose "Total number of volumes: $($dataCount)"
}
Process {
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.volumeName -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
}
|
Get-3PARAo.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARAo {
<#
.SYNOPSIS
Retrieve informations about the configuration of Adaptive optimization (AO).
.DESCRIPTION
This function will retrieve informations about the configuration of Adaptive optimization (AO). You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARAo
Retrieve information about the configuration of Adaptive optimization (AO).
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'AO Name')]
[String]$name
)
Write-host "This function is deprecated. It's still present for compatibility purpose." -foreground yellow
<#
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/aoconfigurations' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Ao'
#Write result + Formating
Write-Verbose "Total number of AO Configuration: $($dataCount)"
}
Process {
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
#>
}
|
Get-3PARPorts.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARPorts {
<#
.SYNOPSIS
Retrieve informations about ports.
.DESCRIPTION
This function will retrieve informations about ports. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARHostSets
List all the ports.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Port Position n:s:p')]
[String]$Position
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/ports' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.ports'
[array]$result = @()
Foreach ($data in $AlldataPS)
{
#Translate information into more understable values using dictionaries
$data.PortPos = "$($data.PortPos.node):$($data.PortPos.slot):$($data.PortPos.cardPort)"
$data.mode = $global:portMode.([string]$data.mode)
$data.linkState = $global:portLinkState.([string]$data.linkState)
$data.type = $global:portConnType.([string]$data.type)
$data.protocol = $global:portProtocol.([string]$data.protocol)
$result += $data
}
#Write result + Formating
Write-Verbose "Total number of ports: $($dataCount)"
}
process {
If ($Position) {
Write-Verbose "Return result(s) with the filter: $($Position)"
return $result | Where-Object -FilterScript {$_.portPos -like $Position}
} else {
Write-Verbose "Return result(s) without any filter"
return $result
}
}
}
|
3PAR-Powershell.psd1 | 3PAR-Powershell-0.4.0 | #
# Module manifest for module '3PAR-Powershell'
#
# Generated by: Erwan Quélin
#
# Generated on: 28/11/2015
#
@{
# Script module or binary module file associated with this manifest.
RootModule = '3PAR-Powershell.psm1'
# Version number of this module.
ModuleVersion = '0.4.0'
# ID used to uniquely identify this module
GUID = 'bef3789f-2093-4ed3-93de-7b1b5c40c2ac'
# Author of this module
Author = 'Erwan Quelin'
# Company or vendor of this module
#CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) 2015 Erwan Quelin. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Powershell module for working with HP 3PAR StoreServ array'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = '3PAR-Powershell.Volumes.Format.ps1xml','3PAR-Powershell.Hosts.Format.ps1xml',
'3PAR-Powershell.Systems.Format.ps1xml','3PAR-Powershell.Cpgs.Format.ps1xml',
'3PAR-Powershell.VolumeSets.Format.ps1xml','3PAR-Powershell.HostSets.Format.ps1xml',
'3PAR-Powershell.Ports.Format.ps1xml','3PAR-Powershell.Vluns.Format.ps1xml',
'3PAR-Powershell.Ao.Format.ps1xml','3PAR-Powershell.WsapiConfiguration.Format.ps1xml'
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('HP','3PAR','StoreServ')
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
ProjectUri = 'https://github.com/equelin/3PAR-Powershell'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Check-WSAPICompatibility.ps1 | 3PAR-Powershell-0.4.0 | Function Check-WSAPICompatibility {
[CmdletBinding()]
Param (
[parameter(Mandatory = $true)]
[version]$WSAPIVersion
)
[version]$WSAPI = (Get-3PARWsapiConfiguration).version
If ($WSAPI -le $WSAPIVersion) {
Write-Warning 'The array does not support this functionnality'
Write-Warning "The WSAPI version needed is: $($WSAPIVersion)"
return $false
} else {
return $true
}
}
|
Get-3PARSystems.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARSystems {
<#
.SYNOPSIS
Retrieve informations about the array.
.DESCRIPTION
This function will retrieve informations about the array. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARSystems
Retrieve information about the array.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,HelpMessage = 'System Name')]
[String]$name
)
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/system' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json)
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Systems'
#Write result + Formating
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
|
New-3PARVolumes.ps1 | 3PAR-Powershell-0.4.0 | Function New-3PARVolumes {
<#
.SYNOPSIS
Create a new storage volume
.DESCRIPTION
This function will create a new storage volume. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.PARAMETER Name
Specifies a volume name up to 31 characters in length.
.PARAMETER Cpg
Specifies the name of the CPG from which the volume user space will be allocated.
.PARAMETER sizeMiB
Specifies the size for the volume in MiB. The volume size is rounded up to the next multiple of 256 MiB.
.PARAMETER comment
Specifies any additional information up to 511 characters for the volume.
.PARAMETER tpvv
Create a thin volume (default)
.PARAMETER tdvv
Create a fully provisionned volume
.PARAMETER usrSpcAllocWarningPct
This field enables user space allocation warning. It specifies that a warning alert is generated when the reserved user space of the TPVV exceeds the specified percentage of the VV size.
.PARAMETER usrSpcAllocLimitPct
This field sets the user space allocation limit. The user space of the TPVV is prevented from growing beyond the indicated percentage of the VV size. After this size is reached, any new writes to the VV will fail.
.EXAMPLE
New-3PARVolumes -Name 'VOL01' -cpg 'FC_r1' -sizeMiB 2048
Create new volume VOL01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Volume Name')]
[String]$name,
[Parameter(Mandatory = $true,HelpMessage = 'Volume CPG')]
[String]$cpg,
[Parameter(Mandatory = $true,HelpMessage = 'Volume size')]
[int]$sizeMiB,
[Parameter(Mandatory = $false,HelpMessage = 'Additional informations about the volume')]
[String]$comment,
[Parameter(Mandatory = $false,HelpMessage = 'Create thin volume')]
[switch]$tpvv,
[Parameter(Mandatory = $false,HelpMessage = 'Create fully provisionned volume')]
[switch]$tdvv,
[Parameter(Mandatory = $false,HelpMessage = 'Space allocation warning')]
[int]$usrSpcAllocWarningPct,
[Parameter(Mandatory = $false,HelpMessage = 'Space allocation limit')]
[int]$usrSpcAllocLimitPct
)
Begin {
# Test if connection exist
Check-3PARConnection
}
Process {
# Creation of the body hash
$body = @{}
# Name parameter
$body["name"] = "$($name)"
# cpg parameter
If ($cpg) {
$body["cpg"] = "$($cpg)"
}
# sizeMiB parameter
If ($sizeMiB) {
$body["sizeMiB"] = $sizeMiB
}
# comment parameter
If ($comment) {
$body["comment"] = "$($comment)"
}
# tpvv parameter
If ($tpvv) {
$body["tpvv"] = $true
}
# tdvv parameter
If ($tdvv) {
$body["tdvv"] = $true
}
# usrSpcAllocWarningPct parameter
If ($usrSpcAllocWarningPct) {
$body["usrSpcAllocWarningPct"] = $usrSpcAllocWarningPct
}
# usrSpcAllocLimitPct parameter
If ($usrSpcAllocLimitPct) {
$body["usrSpcAllocLimitPct"] = $usrSpcAllocLimitPct
}
#init the response var
$data = $null
#Request
$data = Send-3PARRequest -uri '/volumes' -type 'POST' -body $body
# Results
Get-3PARVolumes -Name $name
}
End {
}
}
|
Get-3PARVolumes.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARVolumes {
<#
.SYNOPSIS
Retrieve informations about Volumes
.DESCRIPTION
This function will retrieve informations about Volumes. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARVolumes
List all the volumes
.EXAMPLE
Get-3PARVolumes -Name 'LUN01'
Retrieve information about the volume named LUN01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Volume Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/volumes' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Volumes'
[array]$result = @()
Foreach ($data in $AlldataPS)
{
#Translate information into more understable values using dictionaries
$data.provisioningType = $global:provisioningType.([string]$data.provisioningType)
$data.CopyType = $global:CopyType.([string]$data.CopyType)
$data.state = $global:state.([string]$data.state)
$result += $data
}
Write-Verbose "Total number of volumes: $($dataCount)"
}
Process {
#Write result + Formating
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $result | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $result
}
}
}
|
Get-3PARCapacity.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARCapacity {
<#
.SYNOPSIS
Retrieve informations about the space usage of the array.
.DESCRIPTION
This function will retrieve informations about the space usage of the array. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARCapacity
Retrieve information about space usage.
#>
[CmdletBinding()]
Param()
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/capacity' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json)
#Write result + Formating
Write-Verbose "Return result(s) without any filter"
return $dataPS
}
|
Get-3PARVolumeSets.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARVolumeSets {
<#
.SYNOPSIS
Retrieve informations about Volume Sets.
.DESCRIPTION
This function will retrieve informations about Volume Sets. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARVolumeSets
List all the volume sets
.EXAMPLE
Get-3PARVolumeSets -Name 'VS01'
Retrieve information about the volume sets named VS01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Volume Set Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/volumesets' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.VolumeSets'
#Write result + Formating
Write-Verbose "Total number of Volume Sets: $($dataCount)"
}
Process {
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
}
|
Send-3PARRequest.ps1 | 3PAR-Powershell-0.4.0 | function Send-3PARRequest {
[CmdletBinding()]
Param (
[parameter(Position = 0, Mandatory = $true, HelpMessage = "Enter the resource URI (ex. /volumes)")]
[ValidateScript({if ($_.startswith('/')) {$true} else {throw "-URI must begin with a '/' (eg. /volumes) in its value. Please correct the value and try again."}})]
[string]$uri,
[parameter(Position = 1, Mandatory = $true, HelpMessage = "Enter request type (GET POST DELETE)")]
[string]$type,
[parameter(Position = 2, Mandatory = $false, HelpMessage = "Body of the message")]
[array]$body
)
$APIurl = 'https://'+$global:3parArray+':8080/api/v1'
$url = $APIurl + $uri
#Construct header
$headers = @{}
$headers["Accept"] = "application/json"
$headers["Accept-Language"] = "en"
$headers["Content-Type"] = "application/json"
$headers["X-HP3PAR-WSAPI-SessionKey"] = $global:3parKey
$data = $null
# Request
If ($type -eq 'GET') {
Try
{
$data = Invoke-WebRequest -Uri "$url" -Headers $headers -Method $type -UseBasicParsing
return $data
}
Catch
{
Show-RequestException -Exception $_
throw
}
}
If (($type -eq 'POST') -or ($type -eq 'PUT')) {
Try
{
$json = $body | ConvertTo-Json
$data = Invoke-WebRequest -Uri "$url" -Body $json -Headers $headers -Method $type -UseBasicParsing
return $data
}
Catch
{
Show-RequestException -Exception $_
throw
}
}
If ($type -eq 'DELETE') {
Try
{
$data = Invoke-WebRequest -Uri "$url" -Headers $headers -Method $type -UseBasicParsing
return $data
}
Catch
{
Show-RequestException -Exception $_
throw
}
}
}
|
Get-3PARCpgs.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARCpgs {
<#
.SYNOPSIS
Retrieve informations about CPGs
.DESCRIPTION
This function will retrieve informations about CPGs. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARCpgs
List all the CPGs
.EXAMPLE
Get-3PARCpgs -Name 'SSD-RAID1'
Retrieve information about the CPG named SSD-RAID1
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'CPG Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/cpgs' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.Cpgs'
Write-Verbose "Total number of CPG(s): $($dataCount)"
}
Process {
#Write result + Formating
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
}
|
3PAR-Powershell.psm1 | 3PAR-Powershell-0.4.0 | #Get public and private function definition files.
$Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue )
#Dot source the files
Foreach($import in @($Public + $Private))
{
Try
{
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
# Export public functions
Export-ModuleMember -Function $Public.Basename
# Hack for allowing untrusted SSL certs with https connexions
Add-Type -TypeDefinition @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
#Dictionnary declaration
##### Port Dictionnary
[pscustomobject]$global:portMode = @{
'1' = "SUSPENDED";
'2' = "TARGET";
'3' = "INITIATOR";
'4' = "PEER";
}
[pscustomobject]$global:portLinkState = @{
'1' = "CONFIG_WAIT";
'2' = "ALPA_WAIT";
'3' = "LOGIN_WAIT";
'4' = "READY";
'5' = "LOSS_SYNC";
'6' = "ERROR_STATE";
'7' = "XXX";
'8' = "NONPARTICIPATE";
'9' = "COREDUMP";
'10' = "OFFLINE";
'11' = "FWDEAD";
'12' = "IDLE_FOR_RESET";
'13' = "DHCP_IN_PROGRESS";
'14' = "PENDING_RESET";
}
[pscustomobject]$global:portConnType = @{
'1' = "HOST";
'2' = "DISK";
'3' = "FREE";
'4' = "IPORT";
'5' = "RCFC";
'6' = "PEER";
'7' = "RCIP";
'8' = "ISCSI";
'9' = "CNA";
'10' = "FS";
}
[pscustomobject]$global:portProtocol = @{
'1' = "FC";
'2' = "iSCSI";
'3' = "FCOE";
'4' = "IP";
'5' = "SAS";
}
[pscustomobject]$global:portFailOverState = @{
'1' = "NONE";
'2' = "FAILOVER_PENDING";
'3' = "FAILED_OVER";
'4' = "ACTIVE";
'5' = "ACTIVE_DOWN";
'6' = "ACTIVE_FAILED";
'7' = "FAILBACK_PENDING";
}
##### Host Dictionnary
[pscustomobject]$global:provisioningType = @{
'1' = "FULL";
'2' = "TPVV";
'3' = "SNP";
'4' = "PEER";
'5' = "UNKNOWN";
'6' = "TDVV";
}
[pscustomobject]$global:CopyType = @{
'1' = "BASE";
'2' = "PHYSICAL_COPY";
'3' = "VIRTUAL_COPY";
}
[pscustomobject]$global:state = @{
'1' = "NORMAL";
'2' = "DEGRADED";
'3' = "FAILED";
}
[pscustomobject]$global:DetailedState = @{
'1' = "LDS_NOT_STARTED";
'2' = "NOT_STARTED";
'3' = "NEEDS_CHECK";
'4' = "NEEDS_MAINT_CHECK";
'5' = "INTERNAL_CONSISTENCY_ERROR";
'6' = "SNAPDATA_INVALID";
'7' = "PRESERVED";
'8' = "STALE";
'9' = "COPY_FAILED";
'10' = "DEGRADED_AVAIL";
'11' = "DEGRADED_PERF";
'12' = "PROMOTING";
'13' = "COPY_TARGET";
'14' = "RESYNC_TARGET";
'15' = "TUNING";
'16' = "CLOSING";
'17' = "REMOVING";
'18' = "REMOVING_RETRY";
'19' = "CREATING";
'20' = "COPY_SOURCE";
'21' = "IMPORTING";
'22' = "CONVERTING";
'23' = "INVALID";
}
|
Get-3PARFlashCache.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARFlashCache {
<#
.SYNOPSIS
Retrieve informations about the configuration of flash cache.
.DESCRIPTION
This function will retrieve informations about the configuration of flash cache. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARFlashCache
Retrieve information about the configuration of flash cache.
#>
[CmdletBinding()]
Param()
# Test if connection exist
Check-3PARConnection
#Test if the WSAPI's version is compatible
If (Check-WSAPICompatibility -WSAPIVersion "1.4.2") {
#Request
$data = Send-3PARRequest -uri '/flashcache' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json)
#Write result + Formating
Write-Verbose "Return result(s) without any filter"
return $dataPS
}
}
|
Get-3PARHostSets.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARHostSets {
<#
.SYNOPSIS
Retrieve informations about Host Sets.
.DESCRIPTION
This function will retrieve informations about Host Sets. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARHostSets
List all the Host Sets
.EXAMPLE
Get-3PARHostSets -Name 'HS01'
Retrieve information about the host set named HS01
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'Host Set Name')]
[String]$name
)
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/hostsets' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json).members
$dataCount = ($data.content | ConvertFrom-Json).total
# Add custom type to the resulting oject for formating purpose
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.HostSets'
#Write result + Formating
Write-Verbose "Total number of Host Sets: $($dataCount)"
}
Process {
If ($name) {
Write-Verbose "Return result(s) with the filter: $($name)"
return $AlldataPS | Where-Object -FilterScript {$_.Name -like $name}
} else {
Write-Verbose "Return result(s) without any filter"
return $AlldataPS
}
}
}
|
Get-3PARWsapiConfiguration.ps1 | 3PAR-Powershell-0.4.0 | Function Get-3PARWsapiConfiguration {
<#
.SYNOPSIS
Retrieve informations about the configuration of WSAPI.
.DESCRIPTION
This function will retrieve informations about the configuration of WSAPI. You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under Apache licence.
.LINK
https://github.com/equelin/3PAR-Powershell
.EXAMPLE
Get-3PARWsapiConfiguration
Retrieve information about the configuration of WSAPI.
#>
[CmdletBinding()]
Param()
Begin {
# Test if connection exist
Check-3PARConnection
#Request
$data = Send-3PARRequest -uri '/wsapiconfiguration' -type 'GET'
# Results
$dataPS = ($data.content | ConvertFrom-Json)
[array]$AlldataPS = Format-Result -dataPS $dataPS -TypeName '3PAR.WsapiConfiguration'
}
Process {
#Write result + Formating
Write-Verbose "Return result(s) without any filter"
$AlldataPS
}
}
|
Export-4BitSVG.ps1 | 4bitcss-0.1.5 | function Export-4BitSVG
{
<#
.SYNOPSIS
Exports an SVG that uses a 4 bit palette
.DESCRIPTION
Exports an SVG with a slight modifications that make it use a specific color palette.
.NOTES
SVGs can use CSS styles to dynamically change color.
#>
param(
# The SVG content, or a URL to the SVG
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$SVG,
# The color used for strokes within the SVG.
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$Stroke,
# The color used for fill within the SVG.
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$Fill,
# If provided, will output the SVG to a file
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$OutputPath
)
process {
$svgXML = $null
if ($svg -match "^https?://") {
$svgRest = Invoke-RestMethod -Uri $svg
if ($svgRest -isnot [xml]) {
Write-Error "$Svg was not XML"
return
}
$svgXML = $svgRest
$svg = $svgXML.OuterXML
} elseif ($svg -notmatch '[\n\r]' -and (Test-path $svg)) {
$svg = Get-Content -Path $svg -Raw
}
if (-not ($svg -as [xml])) {
try {
$svgXML = [xml]$svg
} catch {
$ex = $_
Write-Error -Exception $ex.Exception -Message "Could not convert to SVG: $($ex.Exception)" -TargetObject $svg
}
}
if (-not $svgXML) { return }
$svgClass = @(
if ($stroke) {
$stroke -replace "(?:-stroke)?$", '-stroke'
}
if ($Fill) {
$fill -replace "(?:-fill)?$", '-fill'
}
) -join ' '
if ($svgClass) {
$svgXML.svg.SetAttribute("class", "$svgClass")
}
if ($OutputPath) {
$svgXML.svg.OuterXML | Set-Content -Path $OutputPath
if ($?) {
Get-Item -Path $OutputPath
}
} else {
$svgXML.svg.OuterXML
}
}
} |
Container.init.ps1 | 4bitcss-0.1.5 | <#
.SYNOPSIS
Initializes a container during build.
.DESCRIPTION
Initializes the container image with the necessary modules and packages.
This script should be called from the Dockerfile, during the creation of the container image.
~~~Dockerfile
# Thank you Microsoft! Thank you PowerShell! Thank you Docker!
FROM mcr.microsoft.com/powershell
# Set the shell to PowerShell (thanks again, Docker!)
SHELL ["/bin/pwsh", "-nologo", "-command"]
# Run the initialization script. This will do all remaining initialization in a single layer.
RUN --mount=type=bind,src=./,target=/Initialize ./Initialize/Container.init.ps1
~~~
The scripts arguments can be provided with either an `ARG` or `ENV` instruction in the Dockerfile.
.NOTES
Did you know that in PowerShell you can 'use' namespaces that do not really exist?
This seems like a nice way to describe a relationship to a container image.
That is why this file is using the namespace 'mcr.microsoft.com/powershell'.
(this does nothing, but most likely will be used in the future)
#>
using namespace 'mcr.microsoft.com/powershell AS powerShell'
param(
# The name of the module to be installed.
[string]$ModuleName = $(
if ($env:ModuleName) { $env:ModuleName }
else {
(Get-ChildItem -Path $PSScriptRoot |
Where-Object Extension -eq '.psd1' |
Select-String 'ModuleVersion\s=' |
Select-Object -ExpandProperty Path -First 1) -replace '\.psd1$'
}
),
# The packages to be installed.
[string[]]$InstallAptGet = @($env:InstallAptGet -split ','),
# The modules to be installed.
[string[]]$InstallModule = @($env:InstallModule -split ','),
# The Ruby gems to be installed.
[string[]]$InstallRubyGem = @($env:InstallRubyGem -split ','),
# If set, will keep the .git directories.
[switch]$KeepGit = $($env:KeepGit -match $true)
)
# Copy all container-related scripts to the root of the container.
Get-ChildItem -Path $PSScriptRoot |
Where-Object Name -Match '^Container\..+?\.ps1$' |
Copy-Item -Destination /
# Create a profile
New-Item -Path $Profile -ItemType File -Force | Out-Null
if ($ModuleName) {
# Get the root module directory
$rootModuleDirectory = @($env:PSModulePath -split '[;:]')[0]
# Determine the path to the module destination.
$moduleDestination = "$rootModuleDirectory/$ModuleName"
# Copy the module to the destination
# (this is being used instead of the COPY statement in Docker, to avoid additional layers).
Copy-Item -Path "$psScriptRoot" -Destination $moduleDestination -Recurse -Force
# and import this module in the profile
Add-Content -Path $profile -Value "Import-Module $ModuleName" -Force
}
# If we have modules to install
if ($InstallModule) {
# Install the modules
Install-Module -Name $InstallModule -Force -AcceptLicense -Scope CurrentUser
# and import them in the profile
Add-Content -Path $Profile -Value "Import-Module '$($InstallModule -join "','")'" -Force
}
# If we have packages to install
if ($InstallAptGet) {
# install the packages
apt-get update &&
apt-get install -y @InstallAptGet '--no-install-recommends' &&
apt-get clean |
Out-Host
}
if ($InstallRubyGem) {
# Install the Ruby gems
gem install @InstallRubyGem
}
if ($ModuleName) {
# In our profile, push into the module's directory
Add-Content -Path $Profile -Value "Get-Module $ModuleName | Split-Path | Push-Location" -Force
}
if (-not $KeepGit) {
# Remove the .git directories from any modules
Get-ChildItem -Path $rootModuleDirectory -Directory -Force -Recurse |
Where-Object Name -eq '.git' |
Remove-Item -Recurse -Force
}
# Congratulations! You have successfully initialized the container image.
# This script should work in about any module, with minor adjustments.
# If you have any adjustments, please put them below here, in the `#region Custom`
#region Custom
bundle config --global silence_root_warning true
#endregion Custom |
Container.start.ps1 | 4bitcss-0.1.5 | <#
.SYNOPSIS
Starts the container.
.DESCRIPTION
Starts a container.
This script should be called from the Dockerfile as the ENTRYPOINT (or from within the ENTRYPOINT).
It should be deployed to the root of the container image.
~~~Dockerfile
# Thank you Microsoft! Thank you PowerShell! Thank you Docker!
FROM mcr.microsoft.com/powershell
# Set the shell to PowerShell (thanks again, Docker!)
SHELL ["/bin/pwsh", "-nologo", "-command"]
# Run the initialization script. This will do all remaining initialization in a single layer.
RUN --mount=type=bind,src=./,target=/Initialize ./Initialize/Container.init.ps1
ENTRYPOINT ["pwsh", "-nologo", "-file", "/Container.start.ps1"]
~~~
.NOTES
Did you know that in PowerShell you can 'use' namespaces that do not really exist?
This seems like a nice way to describe a relationship to a container image.
That is why this file is using the namespace 'mcr.microsoft.com/powershell'.
(this does nothing, but most likely will be used in the future)
#>
using namespace 'ghcr.io/2bitdesigns/4bitcss'
param()
$env:IN_CONTAINER = $true
$PSStyle.OutputRendering = 'Ansi'
$mountedDrives = @(if (Test-Path '/proc/mounts') {
(Select-String "\S+\s(?<p>\S+).+rw?,.+symlinkroot=/mnt/host" "/proc/mounts").Matches.Groups |
Where-Object Name -eq p |
Get-Item -path { $_.Value } |
New-PSDrive -Name { "Mount", $_.Name -join '.' } -PSProvider FileSystem -Root { $_.Value } -Scope Global -ErrorAction Ignore
})
if ($global:ContainerInfo.MountedPaths) {
"Mounted $($mountedPaths.Length) drives:" | Out-Host
$mountedDrives | Out-Host
}
if ($args) {
# If there are arguments, output them (you could handle them in a more complex way).
"$args" | Out-Host
} else {
# If there are no arguments, see if there is a Microservice.ps1
if (Test-Path './Microservice.ps1') {
# If there is a Microservice.ps1, run it.
. ./Microservice.ps1
}
#region Custom
else
{
Start-ThreadJob -Name "${env:ModuleName}.Jekyll" -ScriptBlock {
Push-Location ./docs
jekyll serve --host "$(
if ($env:JEKYLL_HOST) { $env:JEKYLL_HOST }
else { '*' }
)" '--port' $(
if ($env:JEKYLL_PORT) { $env:JEKYLL_PORT }
else { 4000 }
)
}
}
#endregion Custom
}
# If you want to do something when the container is stopped, you can register an event.
# This can call a script that does some cleanup, or sends a message as the service is exiting.
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
if (Test-Path '/Container.stop.ps1') {
& /Container.stop.ps1
}
} | Out-Null |
Export-4BitCSS.ps1 | 4bitcss-0.1.5 | function Export-4BitCSS
{
<#
.SYNOPSIS
Exports 4bitCSS
.DESCRIPTION
Converts a color scheme into 4bitCSS and outputs a .CSS file.
.EXAMPLE
$palette = @{
Foreground = '#FFFFFF'
Background = '#010101'
Black = '#000420'
Red = '#ff4422'
Green = '#008100'
Yellow = '#e68d00'
Blue = '#4488ff'
Purple = '#844284'
Cyan = '#008080'
White = '#efefef'
BrightBlack = '#808080'
BrightRed = '#e50000'
BrightGreen = '#44ff22'
BrightYellow = '#e6d600'
BrightBlue = '#004cff'
BrightPurple = '#760188'
BrightCyan = '#42F4F4'
BrightWhite = '#FFFFFF'
}
Export-4bitcss -Name 4bit @palette -OutputPath .\4bit
#>
[Alias('Template.CSS.4Bit','Template.4bit.css')]
param(
# The name of the color scheme.
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[ComponentModel.DefaultBindingProperty("name")]
[string]
$Name,
# The color for Black (ANSI0).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI0')]
[ComponentModel.DefaultBindingProperty("black")]
[string]
$Black,
# The color for Red (ANSI 1).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI1')]
[ComponentModel.DefaultBindingProperty("red")]
[string]
$Red,
# The color for Green (ANSI 2).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI2')]
[ComponentModel.DefaultBindingProperty("green")]
[string]
$Green,
# The color for Yellow (ANSI 3).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI3')]
[ComponentModel.DefaultBindingProperty("yellow")]
[string]
$Yellow,
# The color for Blue (ANSI 4).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI4')]
[ComponentModel.DefaultBindingProperty("blue")]
[string]
$Blue,
# The color for Purple/Magneta (ANSI 5).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI5')]
[Alias('Magenta')]
[ComponentModel.DefaultBindingProperty("purple")]
[string]
$Purple,
# The color for Cyan (ANSI 6).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI6')]
[ComponentModel.DefaultBindingProperty("cyan")]
[string]
$Cyan,
# The color for White (ANSI 7).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI7')]
[ComponentModel.DefaultBindingProperty("white")]
[string]
$White,
# The color for Bright Black (ANSI 8).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI8')]
[ComponentModel.DefaultBindingProperty("brightBlack")]
[string]
$BrightBlack,
# The color for Bright Red (ANSI 9).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI9')]
[ComponentModel.DefaultBindingProperty("brightRed")]
[string]
$BrightRed,
# The color for Bright Green (ANSI 10).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI10')]
[ComponentModel.DefaultBindingProperty("brightGreen")]
[string]
$BrightGreen,
# The color for Bright Yellow (ANSI 11).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI11')]
[ComponentModel.DefaultBindingProperty("brightYellow")]
[string]
$BrightYellow,
# The color for Bright Blue (ANSI 12).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI12')]
[ComponentModel.DefaultBindingProperty("brightBlue")]
[string]
$BrightBlue,
# The color for Bright Purple / Magneta (ANSI 13).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('BrightMagenta')]
[Alias('ANSI13')]
[ComponentModel.DefaultBindingProperty("brightPurple")]
[string]
$BrightPurple,
# The color for Bright Cyan (ANSI 14).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI14')]
[ComponentModel.DefaultBindingProperty("brightCyan")]
[string]
$BrightCyan,
# The color for Bright White (ANSI 15).
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[Alias('ANSI15')]
[ComponentModel.DefaultBindingProperty("brightWhite")]
[string]
$BrightWhite,
# The background color. (Should be the value for Black)
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[ComponentModel.DefaultBindingProperty("background")]
[string]
$Background,
# The foreground color. (Should be the value for White)
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[ComponentModel.DefaultBindingProperty("foreground")]
[string]
$Foreground,
# The cursor color.
[Parameter(ValueFromPipelineByPropertyName)]
[ComponentModel.DefaultBindingProperty("cursorColor")]
[string]
$CursorColor,
# The selection background.
[Parameter(ValueFromPipelineByPropertyName)]
[ComponentModel.DefaultBindingProperty("selectionBackground")]
[string]
$SelectionBackground,
# The output path. If not specified, will output to the current directory.
[string]
$OutputPath,
# If set, will not generate css classes for well-known streams
[Alias('NoStreams','NoStreamColors')]
[switch]
$NoStream,
# If set, will not generate css classes for each color.
[Alias('NoColorNames', 'NoNamedColors')]
[switch]
$NoColorName,
# If set, will not generate css classes for each potential fill
[Alias('NoFills','NoNamedColorFill')]
[switch]
$NoFill,
# If set, will not generate css classes for each potential stroke.
[Alias('NoStrokes','NoNamedColorStroke')]
[switch]
$NoStroke,
# If set, will not generate css classes for each background-color.
[Alias('NoBackgrounColors')]
[switch]
$NoBackgroundColor,
# If set, will not generate css classes that correspond to `$psStyle`.
[Alias('NoStyles','NoPSStyle','NoPSStyles')]
[switch]
$NoStyle,
# If set, will not include CSS for common page elements
[Alias('NoElements')]
[switch]
$NoElement,
# If set, will not generate CSS for highlight.js
[Alias('NoHighlights','NoHighlightJS')]
[switch]
$NoHighlight,
# A collection of highlight styles.
# The key should be the selector for one or more highlight js classes, and the value should be a series of CSS rules.
[Collections.IDictionary]
$HighlightStyle = $([Ordered]@{
".hljs" = 'display: block','overflow-x: auto','padding: 0.5em','background: var(--background)','color: var(--foreground)'
".hljs-comment, .hljs-quote, .hljs-variable, .hljs-string, .hljs-doctag" = 'color: var(--green);'
".hljs-keyword, .hljs-selector-tag, .hljs-built_in, .hljs-name, .hljs-tag" = 'color: var(--cyan);'
".hljs-title, .hljs-section, .hljs-attribute, .hljs-literal, .hljs-template-tag, .hljs-template-variable, .hljs-type, .hljs-addition" = 'color: var(--blue);'
".hljs-deletion, .hljs-selector-attr, .hljs-selector-pseudo, .hljs-meta" = 'color: var(--red);'
".hljs-attr,.hljs-symbol,.hljs-bullet,.hljs-link" = 'color: var(--purple);'
".hljs-emphasis" = 'font-style: italic;'
".hljs-strong" = 'font-weight: bold;'
}),
# If set, will generate minimal css (not minimized)
# Implies all other -No* switches
[Alias('VariablesOnly')]
[switch]
$Minimal
)
begin {
filter GetLuma {
$colorString = $_
# Convert the background color to a uint32
$rgb = ($colorString -replace "#", "0x" -replace ';') -as [UInt32]
# then make it into a percentage red, green, and blue.
$r, $g, $b = ([float][byte](($rgb -band 0xff0000) -shr 16)/255),
([float][byte](($rgb -band 0x00ff00) -shr 8)/255),
([float][byte]($rgb -band 0x0000ff)/255)
# Calculate the luma of the background color
0.2126 * $R + 0.7152 * $G + 0.0722 * $B
}
$myCmd = $MyInvocation.MyCommand
}
process {
if (-not $OutputPath) {
$OutputPath =
if ($MyInvocation.MyCommand.ScriptBlock.Module) {
$MyInvocation.MyCommand.ScriptBlock.Module
} else {
$PSScriptRoot | Split-Path
}
}
if (-not (Test-Path $OutputPath)) {
$null = New-Item -ItemType Directory -Force -Path $OutputPath
}
$jsonObject = [Ordered]@{}
$ColorOrder = @(
'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Purple', 'Cyan', 'White'
)
# Walk over each parameter
:nextParam foreach ($keyValue in $PSBoundParameters.GetEnumerator()) {
# and walk over each of it's attributes to see if it part of the payload
foreach ($attr in $myCmd.Parameters[$keyValue.Key].Attributes) {
# If the parameter is bound to part of the payload
if ($attr -is [ComponentModel.DefaultBindingPropertyAttribute]) {
# copy it into our payload dicitionary.
$jsonObject[$attr.Name] = $keyValue.Value
# (don't forget to turn switches into booleans)
if ($jsonObject[$attr.Name] -is [switch]) {
$jsonObject[$attr.Name] = [bool]$jsonObject[$attr.Name]
}
continue nextParam
}
}
}
$jsonObject['Luma'] = $Background | GetLuma
$jsonObject['Contrast'] = [Math]::Abs(($foreground | GetLuma) - $jsonObject['Luma'])
$jsonObject = [PSCustomObject]$jsonObject
# and determine if it is bright or dark.
$IsBright = $luma -ge .4
if ($Minimal) {
$NoStream = $true
$NoColorName = $true
$NoFill = $true
$NoElement = $true
$NoStroke = $true
$NoBackgroundColor = $true
$NoStyle = $true
$NoHighlight = $true
}
# Generate a CSS file name for the color scheme
$cssFile = (Join-Path $OutputPath "$($name | Convert-4BitName).css")
# Generate a CSS class name for the color palette
# replacing space and leading digits with an underscore.
$className = $Name -replace '\s' -replace '^\d', '_$0'
# Generate the CSS content
$cssContent = @(
@"
:root {
$(@(
foreach ($prop in $jsonObject.psobject.properties) {
if ($prop.Name -eq 'Name') {
"--$($prop.Name): '$($prop.Value)'"
} else {
"--$($prop.Name): $($prop.Value)"
}
}) -join (';' + [Environment]::NewLine + ' '));
--IsBright: $($IsBright -as [int]);
--IsDark: $((-not $IsBright) -as [int]);
}
.colorSchemeName::before, .ColorSchemeName::before { content: '$($name)'; }
.colorSchemeFileName::before, .ColorSchemeFileName::before { content: '$($name | Convert-4BitName).css'; }
"@
# Foreground and background colors
@"
.foreground, .Foreground { color: var(--foreground); }
.background, .Background { background-color: var(--background); }
.foreground-border , .Foreground-Border { border-color: var(--foreground) }
.foreground-fill , .Foreground-Fill { fill: var(--foreground) }
.foreground-stroke , .Foreground-Stroke { stroke: var(--foreground) }
.background-border , .Background-Border { border-color: var(--background) }
.background-fill , .Background-Fill { fill: var(--background) }
.background-stroke , .Background-Stroke { stroke: var(--background) }
"@
# Colors for well-known "Streams" of data.
if (-not $NoStream) {
@"
.output , .Output { color: var(--foreground) }
.success , .Success { color: var(--brightGreen) }
.failure , .Failure { color: var(--red) }
.error , .Error { color: var(--brightRed) }
.warning , .Warning { color: var(--brightYellow) }
.debug , .Debug { color: var(--yellow) }
.verbose , .Verbose { color: var(--brightCyan) }
.progress , .Progress { color: var(--cyan) }
.link , .Link { color: var(--cyan) }
.error-border , .Error-Border { border-color: var(--brightRed) }
.error-fill , .Error-Fill { fill: var(--brightRed) }
.error-stroke , .Error-Stroke { stroke: var(--brightRed) }
.success-border , .Success-Border { border-color: var(--brightGreen) }
.success-fill , .Sucesss-Fill { fill: var(--brightGreen) }
.sucesss-stroke , .Success-Stroke { stroke: var(--brightGreen) }
.warning-border , .Warning-Border { border-color: var(--brightYellow) }
.warning-fill , .Warning-Fill { fill: var(--brightYellow) }
.warning-stroke , .Warning-Stroke { stroke: var(--brightYellow) }
"@
}
if (-not $NoColorName) {
@"
/* colors */
.black , .Black , .ANSI0 { color: var(--black) }
.red , .Red , .ANSI1 { color: var(--red) }
.green , .Green , .ANSI2 { color: var(--green) }
.yellow , .Yellow , .ANSI3 { color: var(--yellow) }
.blue , .Blue , .ANSI4 { color: var(--blue) }
.magenta , .Magenta , .ANSI5 { color: var(--purple) }
.cyan , .Cyan , .ANSI6 { color: var(--cyan) }
.white , .White , .ANSI7 { color: var(--white) }
.brightblack , .bright-black , .BrightBlack , .ANSI8 { color: var(--brightBlack) }
.brightred , .bright-red , .BrightRed , .ANSI9 { color: var(--brightRed) }
.brightgreen , .bright-green , .BrightGreen , .ANSI10 { color: var(--brightGreen) }
.brightyellow , .bright-yellow , .BrightYellow , .ANSI11 { color: var(--brightYellow) }
.brightblue , .bright-blue , .BrightBlue , .ANSI12 { color: var(--brightBlue) }
.brightmagenta , .bright-magenta , .BrightMagenta , .ANSI13 { color: var(--brightPurple) }
.brightcyan , .bright-cyan , .BrightCyan , .ANSI14 { color: var(--brightCyan) }
.brightwhite , .bright-white , .BrightWhite , .ANSI15 { color: var(--brightWhite) }
.purple , .Purple { color: var(--purple) }
.brightpurple , .bright-purple , .BrightPurple { color: var(--brightPurple) }
"@
}
if (-not $NoBackgroundColor) {
@"
/* background colors */
.black-background, .BlackBackground, .ANSI0-Background, .ansi0-background { background-color: var(--black) }
.red-background, .RedBackground, .ANSI1-Background, .ansi1-background { background-color: var(--red) }
.green-background, .GreenBackground, .ANSI2-Background, .ansi2-background { background-color: var(--green) }
.yellow-background, .YellowBackground, .ANSI3-Background, .ansi3-background { background-color: var(--yellow) }
.blue-background, .BlueBackground, .ANSI4-Background, .ansi4-background { background-color: var(--blue) }
.magenta-background, .MagentaBackground, .ANSI5-Background, .ansi5-background { background-color: var(--purple) }
.cyan-background, .CyanBackground, .ANSI6-Background, .ansi6-background { background-color: var(--cyan) }
.white-background, .WhiteBackground, .ANSI7-Background, .ansi7-background { background-color: var(--white) }
.brightblack-background, .bright-black-background, .BrightBlackBackground, .ANSI8-Background, .ansi8-background { background-color: var(--brightBlack) }
.brightred-background, .bright-red-background, .BrightRedBackground, .ANSI9-Background, .ansi9-background { background-color: var(--brightRed) }
.brightgreen-background, .bright-green-background, .BrightGreenBackground, .ANSI10-Background, .ansi10-background { background-color: var(--brightGreen) }
.brightyellow-background, .bright-yellow-background, .BrightYellowBackground, .ANSI11-Background, .ansi11-background { background-color: var(--brightYellow) }
.brightblue-background, .bright-blue-background, .BrightBlueBackground, .ANSI12-Background, .ansi12-background { background-color: var(--brightBlue) }
.brightmagenta-background, .bright-magenta-background, .BrightMagentaBackground, .ANSI13-Background, .ansi13-background { background-color: var(--brightPurple) }
.brightcyan-background, .bright-cyan-background, .BrightCyanBackground, .ANSI14-Background, .ansi14-background { background-color: var(--brightCyan) }
.brightwhite-background, .bright-white-background, .BrightWhiteBackground, .ANSI15-Background, .ansi15-background { background-color: var(--brightWhite) }
"@
}
if (-not $NoFill) {
@"
/* fills */
.black-fill , .BlackFill , .ANSI0-Fill, .ansi0-fill { fill: var(--black) }
.red-fill , .RedFill , .ANSI1-Fill, .ansi1-fill { fill: var(--red) }
.green-fill , .GreenFill , .ANSI2-Fill, .ansi2-fill { fill: var(--green) }
.yellow-fill , .YellowFill , .ANSI3-Fill, .ansi3-fill { fill: var(--yellow) }
.blue-fill , .BlueFill , .ANSI4-Fill, .ansi4-fill { fill: var(--blue) }
.magenta-fill , .MagentaFill , .ANSI5-Fill, .ansi5-fill { fill: var(--purple) }
.purple-fill, .PurpleFill { fill: var(--purple) }
.cyan-fill , .CyanFill , .ANSI6-Fill, .ansi6-fill { fill: var(--cyan) }
.white-fill , .WhiteFill , .ANSI7-Fill, .ansi7-fill { fill: var(--white) }
.brightblack-fill , .bright-black-fill , .BrightBlackFill , .ANSI8-Fill, .ansi8-fill { fill: var(--brightBlack) }
.brightred-fill , .bright-red-fill , .BrightRedFill , .ANSI9-Fill, .ansi9-fill { fill: var(--brightRed) }
.brightgreen-fill , .bright-green-fill , .BrightGreenFill , .ANSI10-Fill, .ansi10-fill { fill: var(--brightGreen) }
.brightyellow-fill , .bright-yellow-fill , .BrightYellowFill , .ANSI11-Fill, .ansi11-fill { fill: var(--brightYellow) }
.brightblue-fill , .bright-blue-fill , .BrightBlueFill , .ANSI12-Fill, .ansi12-fill { fill: var(--brightBlue) }
.brightmagneta-fill , .bright-magneta-fill , .BrightMagnetaFill , .ANSI13-Fill, .ansi13-fill { fill: var(--brightPurple) }
.brightpurple-fill , .bright-purple-fill, .BrightPurpleFill { fill: var(--brightPuple) }
.brightcyan-fill , .bright-cyan-fill , .BrightCyanFill , .ANSI14-Fill, .ansi14-fill { fill: var(--brightCyan) }
.brightwhite-fill , .bright-white-fill , .BrightWhiteFill , .ANSI15-Fill, .ansi15-fill { fill: var(--brightWhite) }
"@
}
if (-not $NoStroke) {
@"
/* strokes */
.black-stroke , .BlackStroke , .ANSI0-Stroke, .ansi0-stroke { stroke: var(--black) }
.red-stroke , .RedStroke , .ANSI1-Stroke, .ansi1-stroke { stroke: var(--red) }
.green-stroke , .GreenStroke , .ANSI2-Stroke, .ansi2-stroke { stroke: var(--green) }
.yellow-stroke , .YellowStroke , .ANSI3-Stroke, .ansi3-stroke { stroke: var(--yellow) }
.blue-stroke , .BlueStroke , .ANSI4-Stroke, .ansi4-stroke { stroke: var(--blue) }
.magenta-stroke , .MagentaStroke , .ANSI5-Stroke, .ansi5-stroke { stroke: var(--purple) }
.purple-stroke, .PurpleStroke { stroke: var(--purple) }
.cyan-stroke , .CyanStroke , .ANSI6-Stroke, .ansi6-stroke { stroke: var(--cyan) }
.white-stroke , .WhiteStroke , .ANSI7-Stroke, .ansi7-stroke { stroke: var(--white) }
.brightblack-stroke , .bright-black-stroke , .BrightBlackStroke , .ANSI8-Stroke, .ansi8-stroke { stroke: var(--brightBlack) }
.brightred-stroke , .bright-red-stroke , .BrightRedStroke , .ANSI9-stroke, .ansi9-stroke { stroke: var(--brightRed) }
.brightgreen-stroke , .bright-green-stroke , .BrightGreenStroke , .ANSI10-Stroke, .ansi10-stroke { stroke: var(--brightGreen) }
.brightyellow-stroke , .bright-yellow-stroke , .BrightYellowStroke, .ANSI11-Stroke, .ansi11-stroke { stroke: var(--brightYellow) }
.brightblue-stroke , .bright-blue-stroke , .BrightBlueStroke , .ANSI12-Stroke, .ansi12-stroke { stroke: var(--brightBlue) }
.brightmagneta-stroke , .bright-magneta-stroke , .BrightMagnetaStroke , .ANSI13-Stroke, .ansi13-stroke { stroke: var(--brightPuple) }
.brightpurple-stroke , .bright-purple-stroke, .BrightPurpleStroke { stroke: var(--brightPuple) }
.brightcyan-stroke , .bright-cyan-stroke , .BrightCyanStroke , .ANSI14-Stroke, .ansi14-stroke { stroke: var(--brightCyan) }
.brightwhite-stroke , .bright-white-stroke , .BrightWhiteStroke , .ANSI15-Stroke, .ansi15-stroke { stroke: var(--brightWhite) }
"@
}
if (-not $NoStyle) {
@"
/* psStyles */
.dim, .Dim { opacity: .5; }
.hidden, .Hidden { opacity: 0; }
b, bold, .bold, .Bold { font-weight: bold; }
.boldOff, .BoldOff { font-weight: normal; }
i, italic, .italic, .Italic { font-style: italic; }
.italicOff, .ItalicOff { font-style: normal; }
u, underline, .underline, .Underline { text-decoration: underline; }
.underlineOff, .UnderlineOff { text-decoration: none; }
s, strike, .strike, .Strike, .strikethrough, .Strikethrough { text-decoration: line-through; }
.strikeOff, .StrikeOff, .strikethroughOff, .StrikethroughOff { text-decoration: none; }
"@
foreach ($subproperty in 'Formatting', 'Progress') {
:nextStyleProperty foreach ($styleProperty in $PSStyle.$subproperty.psobject.properties) {
if ($styleProperty.Value -notmatch '\e') { continue }
$null = $styleProperty.Value -match '\e\[(?<n>[\d;]+)m'
$styleBytes = $matches.n -split ';' -as [byte[]]
$cssProperties = @(
switch ($styleBytes) {
1 { 'font-weight: bold' }
3 { 'font-style: italic' }
4 { 'text-decoration: underline' }
9 { 'text-decoration: line-through' }
22 { 'font-weight: normal' }
23 { 'font-style: normal' }
24 { 'text-decoration: none' }
default {
if ($_ -in 30..37) {
$colorName = $ColorOrder[$_ - 30]
if (-not $colorName) {
Write-Warning "Could not translate `$psStyle.$($subproperty).$($styleProperty.Name) to a color."
continue nextStyleProperty
}
$colorName = $colorName.Substring(0, 1).ToLower() + $colorName.Substring(1)
"color: var(--$colorName)"
} elseif ($_ -in 40..47) {
$colorName = $ColorOrder[$_ - 40]
if (-not $colorName) {
Write-Warning "Could not translate `$psStyle.$($subproperty).$($styleProperty.Name) to a color."
continue nextStyleProperty
}
$colorName = $colorName.Substring(0, 1).ToLower() + $colorName.Substring(1)
"background-color: var(--$colorName)"
} elseif ($_ -eq 38) {
"color: var(--foreground)"
} elseif ($_ -eq 48) {
"background-color: var(--background)"
}
elseif ($_ -in 90..97) {
$colorName = "bright$($ColorOrder[$_ - 90])"
if (-not $colorName) {
Write-Warning "Could not translate `$psStyle.$($subproperty).$($styleProperty.Name) to a color."
continue nextStyleProperty
}
"color: var(--$colorName)"
} elseif ($_ -in 100..107) {
$colorName = "bright$($ColorOrder[$_ - 100])"
if (-not $colorName) {
Write-Warning "Could not translate `$psStyle.$($subproperty).$($styleProperty.Name) to a color."
continue nextStyleProperty
}
"background-color: var(--$colorName)"
}
}
}
)
$className = ".$subproperty-$($styleProperty.Name)"
"$className { $($cssProperties -ne '' -join ';') }"
}
}
}
if ((-not $NoHighlight) -and $HighlightStyle.Count) {
"/* highlight.js styles */"
foreach ($keyValuePair in $HighlightStyle) {
foreach ($key in $HighlightStyle.Keys) {
$cssProperties = $HighlightStyle[$key]
$cssProperties = if ($cssProperties -is [Collections.IDictionary]) {
foreach ($cssKeyValue in $cssProperties.GetEnumerator()) {
"$($cssKeyValue.Key): $($cssKeyValue.Value)"
}
} else {
$cssProperties
}
@("$key {"
" $($cssProperties -join (';' + [Environment]::NewLine + ' '))"
"}") -join [Environment]::NewLine
}
}
}
if (-not $NoElement) {
@"
body {
color: var(--foreground);
background-color: var(--background);
caret-color: var(--cursorColor);
}
a, a:visited, a:hover { color: var(--cyan); }
::selection, ::-moz-selection {
color: var(--cursorColor);
background-color: var(--selectionBackground);
}
form input[type="text"], form input[type="checkbox"], input[type="button"], button, textarea, select, option {
color: var(--foreground);
background-color: var(--background);
}
option {
color: var(--foreground);
background: var(--background);
}
form input[type="text"], textarea, select, button {
border : 1px solid var(--foreground);
outline: 1px solid var(--foreground);
}
hr {
color: var(--foreground)
}
"@
}
) -join [Environment]::NewLine
$cssContent | Set-Content -Path $cssFile
Get-Item -Path $cssFile
}
}
|
4bitcss.GitHubWorkflow.PSDevOps.ps1 | 4bitcss-0.1.5 | #requires -Module PSDevOps
Push-Location ($PSScriptRoot | Split-Path)
Import-BuildStep -SourcePath (
Join-Path $PSScriptRoot 'GitHub'
) -BuildSystem GitHubWorkflow
New-GitHubWorkflow -Name "Build 4bitcss" -On Push, PullRequest, Demand -Job TestPowerShellOnLinux, TagReleaseAndPublish, Build4BitCss -Environment @{
NoCoverage = $true
REGISTRY = "ghcr.io"
IMAGE_NAME = '${{ github.repository }}'
} -OutputPath (Join-Path $pwd .github\workflows\Build4bitcss.yml)
Pop-Location |
Export-4BitJSON.ps1 | 4bitcss-0.1.5 | function Export-4BitJSON {
<#
.SYNOPSIS
Exports 4bitcss data to a json file
.DESCRIPTION
Exports 4bitcss data to a json file.
This is simple wrapper of ConvertTo-Json, with support for writing to a file.
#>
param(
# The input object to convert to JSON
[Parameter(ValueFromPipeline)]
[PSObject]
$InputObject,
# The output path.
[string]
$OutputPath
)
process {
$asJson = ConvertTo-Json -Compress -InputObject $InputObject
if ($OutputPath) {
New-Item -Path $outputPath -Force -Value $asJson
} else {
$asJson
}
}
} |
Container.stop.ps1 | 4bitcss-0.1.5 | <#
.SYNOPSIS
Stops the container.
.DESCRIPTION
This script is called when the container is about to stop.
It can be used to perform any necessary cleanup before the container is stopped.
#>
"Container now exiting, thank you for using $env:ModuleName!" | Out-Host
|
Export-4BitJS.ps1 | 4bitcss-0.1.5 | function Export-4BitJS {
<#
.SYNOPSIS
Exports 4bitJS
.DESCRIPTION
Exports JavaScript to change 4bitCSS themes.
#>
[Alias('Template.4bit.js','Template.JavaScript.4bit')]
param(
# The names of all color schemes
[Alias('ColorSchemeNames')]
[string[]]
$ColorSchemeName,
# The names of all dark color schemes
[Alias('DarkColorSchemeNames')]
[string[]]
$DarkColorSchemeName,
# The names of all light color schemes
[Alias('LightColorSchemeNames')]
[string[]]
$LightColorSchemeName,
# The default color scheme to use.
[string]
$DefaultColorScheme = 'Konsolas',
# The stylesheet root. By default, slash. This can also be set to a CDN
[uri]
$StylesheetRoot = "/",
# If set, will link directly to the StyleSheetRoot.
# Without passing this switch, 4bitJS will look for a stylesheet in a named subdirectory.
# e.g. `AdventureTime/AdventureTime.css`.
[Alias('InStyleSheetRoot')]
[switch]
$InRoot
)
@"
var defaultTheme = "$DefaultColorScheme";
function GetColorSchemeList() {
return [
"$($ColorSchemeName -join '","')"
]
}
function GetDarkColorSchemes() {
return [
"$($DarkColorSchemeName -join '","')"
]
}
function GetLightColorSchemes() {
return [
"$($LightColorSchemeName -join '","')"
]
}
function feelingLucky() {
var colorSchemes = GetColorSchemeList();
var randomNumber = Math.floor(Math.random() * colorSchemes.length);
var fourBitCssLink = document.getElementById("4bitcss");
if (! fourBitCssLink) {
throw "Must have a stylesheet link with the id '4bitcss'"
}
SetColorScheme(colorSchemes[randomNumber])
}
function SetColorScheme(colorSchemeName) {
var fourBitCssLink = document.getElementById("4bitcss");
if (! fourBitCssLink) {
throw "Must have a stylesheet link with the id '4bitcss'"
}
var foundScheme = GetColorSchemeList().find(element => element == colorSchemeName);
if (! foundScheme) {
throw ("Color Scheme '" + colorSchemeName + "' does not exist");
}
$(
if (-not $InRoot) {
@"
fourBitCssLink.href = "$StyleSheetRoot" + foundScheme + "/" + foundScheme + ".css";
"@
} else {
@"
fourBitCssLink.href = "$StyleSheetRoot" + foundScheme + ".css";
"@
}
)
fourBitCssLink.themeName = foundScheme;
var downloadLink = document.getElementById("downloadSchemeLink");
if (downloadLink) {
$(
if (-not $InRoot) {
@"
downloadLink.href = "$StyleSheetRoot" + foundScheme + "/" + foundScheme + ".css";
"@
} else {
@"
downloadLink.href = "$StyleSheetRoot" + foundScheme + ".css";
"@
}
)
}
var cdnLink = document.getElementById("cdnSchemeLink")
if (cdnLink) {
cdnLink.href = "https://cdn.jsdelivr.net/gh/2bitdesigns/4bitcss@latest/css/" + foundScheme + ".css";
}
var colorSchemeNameLink = document.getElementById("colorSchemeNameLink")
if (colorSchemeNameLink) {
colorSchemeNameLink.href = "/" + foundScheme;
}
var schemeSelector = document.getElementById("schemeSelector");
if (schemeSelector) {
schemeSelector.value = foundScheme;
}
}
function GetCSSVariable(name) {
var root = document.querySelector(":root");
var rootStyle = getComputedStyle(root);
return rootStyle.getPropertyValue(name);
}
function saveTheme() {
var fourBitCssLink = document.getElementById("4bitcss");
if (! fourBitCssLink) {
throw "Must have a stylesheet link with the id '4bitcss'"
}
if (typeof(Storage) == "undefined") {
throw "Cannot save themes without HTML5 Local Storage"
}
localStorage.setItem("savedThemeLink", fourBitCssLink.themeName);
}
function loadTheme() {
if (typeof(Storage) == "undefined") {
throw "Cannot save themes without HTML5 Local Storage"
}
var previouslySaved = localStorage.getItem("savedThemeLink");
if (previouslySaved) {
SetColorScheme(previouslySaved);
}
for (arg in arguments) {
if (arguments[arg].value) {
arguments[arg].value = previouslySaved;
}
}
}
"@
}
|
4bitcss.ps.psm1 | 4bitcss-0.1.5 | [Include('*-*.ps1')]$PSScriptRoot
$myModule = $MyInvocation.MyCommand.ScriptBlock.Module
$ExecutionContext.SessionState.PSVariable.Set($myModule.Name, $myModule)
$myModule.pstypenames.insert(0, $myModule.Name)
$newDriveSplat = @{PSProvider='FileSystem';ErrorAction='Ignore';Scope='Global'}
New-PSDrive -Name $MyModule.Name -Root ($MyModule | Split-Path) @newDriveSplat
if ($home) {
$myMyModule = "My$($myModule.Name)"
$myMyModuleRoot = Join-Path $home $myMyModule
if (Test-Path $myMyModuleRoot) {
New-PSDrive -Name $myMyModule -Root $myMyModuleRoot @newDriveSplat
}
}
Export-ModuleMember -Function *-* -Alias * -Variable $myModule.Name |
4bitcss.build.ps1 | 4bitcss-0.1.5 | Push-Location ($PSScriptRoot | Split-Path)
# clone the iTermColorSchemes repo
git clone https://github.com/mbadolato/iTerm2-Color-Schemes.git | Out-Host
# and get all of the JSON files from it
$jsonFiles = Get-ChildItem -Path iTerm2-Color-Schemes -Recurse -Filter *.json |
Where-Object Fullname -like '*terminal*' |
Where-Object FullName -notlike '*templates*'
# Get the credits from the CREDITS.md file in the iTerm2-Color-Schemes repo
$creditLines = Get-Content -Path (Join-Path iTerm2-Color-Schemes CREDITS.md)
# and declare a small pattern to match markdown links
$markdownLinkPattern = '\[(?<text>.+?)\]\((?<link>.+?)\)'
# and a filter to get the credits from the CREDITS.md file
filter GetCredits {
$colorSchemeName = $_
$colorSchemePattern = [Regex]::Escape($colorSchemeName) -replace '\\ ', '\s'
foreach ($line in $creditLines) {
if (-not $line ) { continue }
if ($line -notmatch $colorSchemePattern) {
continue
}
if ($line -notmatch $markdownLinkPattern) {
continue
}
[Ordered]@{credit=$Matches.text; link=$Matches.link}
}
}
filter GetLuma {
$colorString = $_
# Convert the background color to a uint32
$rgb = ($colorString -replace "#", "0x" -replace ';') -as [UInt32]
# then make it into a percentage red, green, and blue.
$r, $g, $b = ([float][byte](($rgb -band 0xff0000) -shr 16)/255),
([float][byte](($rgb -band 0x00ff00) -shr 8)/255),
([float][byte]($rgb -band 0x0000ff)/255)
# Calculate the luma of the background color
0.2126 * $R + 0.7152 * $G + 0.0722 * $B
}
# Import the module
Import-Module .\4bitcss.psd1 -Global
# Build the index file.
$transpiledPreview = Build-PipeScript -InputPath (
Join-Path $pwd "docs" |
Join-Path -ChildPath "index.ps.markdown"
)
# (we'll slightly modify this for each preview)
$transpiledText = [IO.File]::ReadAllText($transpiledPreview.FullName)
$yamlHeader, $transpiledText = $transpiledText -split '---' -ne ''
# Also, get the preview template.
$previewSvg = (Get-ChildItem -Path docs -Filter 4bitpreviewtemplate.svg | Get-Content -raw)
# The ./docs directory is our destination for most file.
$docsPath = Join-Path $pwd docs
$allColorSchemes = @()
$brightColorSchemes = @()
$darkColorSchemes = @()
$allPalettes = [Ordered]@{}
# Walk thru each json file of a color scheme
foreach ($jsonFile in $jsonFiles) {
# convert the contents from JSON
$jsonContent = [IO.File]::ReadAllText($jsonFile.FullName)
$jsonObject = $jsonContent | ConvertFrom-Json
# and determine the name of the scheme and it's files.
$colorSchemeName = $jsonObject.Name
$colorSchemeFileName =
$jsonObject.Name | Convert-4BitName
$creditInfo = @($colorSchemeName | GetCredits)[0]
$jsonObject |
Add-Member NoteProperty creditTo -Force -PassThru -Value $creditInfo.credit |
Add-Member NoteProperty creditToLink -Force -Value $creditInfo.link
if ($jsonObject.background) {
$jsonObject |
Add-Member NoteProperty luma -Force -Value $($jsonObject.Background | GetLuma)
}
if ($jsonObject.foreground -and $jsonObject.background) {
$jsonObject |
Add-Member NoteProperty contrast -Force -Value $(
[Math]::Abs(
($jsonObject.background | GetLuma) - ($jsonObject.foreground | GetLuma)
)
)
}
$jsonObject |
Add-Member NoteProperty contrast -Force -PassThru -Value @($jsonObject.Background | GetLuma)
if (-not $colorSchemeFileName) { continue }
$distinctColors = @($jsonObject.psobject.Properties.value) -match '^#[0-9a-fA-F]{6}' | Select-Object -Unique
$allPalettes[$colorSchemeFileName] = $jsonObject
# If the name wasn't there, continue.
if (-not $jsonObject.Name) { continue }
# If it wasn't legal, continue.
if ($jsonObject.Name -match '^\{') { continue }
$cssPath = (Join-Path $pwd css)
$jsonPath = (Join-Path $pwd json)
# Export the theme to /css (so that repo-based CDNs have a logical link)
$jsonObject | Export-4BitCSS -OutputPath $cssPath -OutVariable colorSchemeCssFile
$jsonObject | Export-4BitJSON -OutputPath (
Join-Path $jsonPath "$colorSchemeFileName.json"
) -OutVariable colorSchemeJsonFile
$ColorSchemePath = Join-Path $docsPath $colorSchemeFileName
if (-not (Test-Path $ColorSchemePath)) {
$null = New-Item -ItemType Directory -Path $ColorSchemePath
}
# Then export it again to /docs (so the GitHub page works)
$jsonObject | Export-4BitCSS -OutputPath $ColorSchemePath
$jsonObject | Export-4BitJSON -OutputPath (
Join-Path $ColorSchemePath "$colorSchemeFileName.json"
) -OutVariable colorSchemeJsonFile
$dotTextPath = Join-Path $ColorSchemePath "$colorSchemeFileName.txt"
$distinctColors -join ';' | Set-Content -Path $dotTextPath -Encoding utf8
Get-Item -Path $dotTextPath
$allColorSchemes += $colorSchemeFileName
$wasBright = $colorSchemeCssFile | Select-String "IsBright: 1"
if ($wasBright) {
$brightColorSchemes += $colorSchemeFileName
}
$wasDark = $colorSchemeCssFile | Select-String "IsDark: 1"
if ($wasDark) {
$darkColorSchemes += $colorSchemeFileName
}
# Create a preview file. All we need to change is the stylesheet.
$previewFilePath = Join-Path $ColorSchemePath "$colorSchemeFileName.md"
@"
---
stylesheet: /$colorSchemeFileName/$colorSchemeFileName.css
colorSchemeName: $colorSchemeName
colorSchemeFileName: $colorSchemeFileName
image: /$colorSchemeFileName/$colorSchemeFileName.png
description: $colorSchemeName color scheme
permalink: /$colorSchemeFileName/
---
$transpiledText
"@ |
Set-Content $previewFilePath -Encoding utf8
# output the file so that PipeScript will check it in.
Get-Item -Path $previewFilePath
# Now create a preview SVG
$previewSvgPath = Join-Path $ColorSchemePath "$colorSchemeFileName.svg"
# by expanding the string we have in $previewSVG (this will replace $ColorSchemeName)
$executionContext.SessionState.InvokeCommand.ExpandString($previewSvg) |
Set-Content -Path $previewSvgPath
# output the file so that PipeScript will check it in.
Get-Item -Path $previewSvgPath
}
$DataPath = Join-Path $docsPath "_data"
if (-not (Test-Path $DataPath)) {
$null = New-Item -ItemType Directory -Path $DataPath
}
$allSchemesPath = Join-Path $docsPath "Palette-List.json"
$allColorSchemes |
ConvertTo-Json -Compress |
Set-Content -Path $allSchemesPath
Get-Item -Path $allSchemesPath
Get-Item -Path $allSchemesPath |
Copy-Item -Destination $DataPath -Force -PassThru
$allBrightSchemesPath = Join-Path $docsPath "Bright-Palette-List.json"
$brightColorSchemes |
ConvertTo-Json -Compress |
Set-Content -Path $allBrightSchemesPath
Get-Item -Path $allBrightSchemesPath
Get-Item -Path $allBrightSchemesPath |
Copy-Item -Destination $DataPath -Force -PassThru
$allDarkSchemesPath = Join-Path $docsPath "Dark-Palette-List.json"
$darkColorSchemes |
ConvertTo-Json -Compress |
Set-Content -Path $allDarkSchemesPath
Get-Item -Path $allDarkSchemesPath
Get-Item -Path $allDarkSchemesPath |
Copy-Item -Destination $DataPath -Force -PassThru
$allPalettesPath = Join-Path $docsPath "Palettes.json"
$allPalettes |
ConvertTo-Json -Depth 4 -Compress |
Set-Content -Path $allPalettesPath
Get-Item -Path $allPalettesPath
Get-Item -Path $allPalettesPath |
Copy-Item -Destination $DataPath -Force -PassThru
$4bitJS = Export-4BitJS -ColorSchemeName $allColorSchemes -DarkColorSchemeName $darkColorSchemes -LightColorSchemeName $LightColorSchemeName
$4bitJSDocsPath = Join-Path $docsPath "js" | Join-Path -ChildPath "4bit.js"
New-Item -ItemType File -Path $4bitJSDocsPath -Force -Value $4bitJS
New-Item -ItemType File -Path ".\4bit.js" -Force -Value $4bitJS
#region Icons
$IncludesPath = Join-Path $docsPath "_includes"
if (-not (Test-Path $IncludesPath)) {
$null = New-Item -ItemType Directory -Path $IncludesPath
}
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/download.svg -Stroke "ansi6" -OutputPath (Join-Path $IncludesPath "download-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/github.svg -Stroke "ansi6" -OutputPath (Join-Path $IncludesPath "github-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/download-cloud.svg -Stroke "ansi6" -OutputPath (Join-Path $IncludesPath "download-cloud-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/shuffle.svg -Stroke "ansi6" -OutputPath (Join-Path $IncludesPath "shuffle-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/help-circle.svg -Stroke "ansi6" -OutputPath (Join-Path $IncludesPath "help-circle-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/save.svg -OutputPath (Join-Path $IncludesPath "save-icon.svg")
Export-4BitSVG -SVG https://raw.githubusercontent.com/feathericons/feather/master/icons/skip-back.svg -OutputPath (Join-Path $IncludesPath "skip-back-icon.svg")
Get-Module 4bitcss |
Split-Path |
Join-Path -ChildPath Assets |
Get-ChildItem -Filter 4bit*.svg |
Copy-Item -Destination {
Join-Path $IncludesPath "$($_.Name)"
} -Force -PassThru
$defaultColorScheme = 'Konsolas'
@"
---
stylesheet: /$defaultColorScheme/$defaultColorScheme.css
colorSchemeName: $defaultColorScheme
colorSchemeFileName: $defaultColorScheme
image: /$defaultColorScheme/$defaultColorScheme.png
description: $defaultColorScheme color scheme
permalink: /
---
$transpiledText
"@ |
Set-Content (Join-Path $docsPath "index.md") -Encoding utf8
Get-item -Path (Join-Path $docsPath "index.md")
#endregion Icons
if ($env:GITHUB_WORKSPACE) {
Remove-Item -Path iTerm2-Color-Schemes -Recurse -Force
} |
Convert-4BitName.ps1 | 4bitcss-0.1.5 | filter Convert-4BitName
{
<#
.SYNOPSIS
Converts a 4Bit Name into a path
.DESCRIPTION
Converts a 4Bit Color Scheme Name into a path
#>
$_ -replace '\s','-' -replace '\p{P}','-' -replace '-+','-' -replace '-$'
}
|
4bitcss.PSSVG.ps1 | 4bitcss-0.1.5 | #requires -Module PSSVG
Push-Location ($PSScriptRoot | Split-Path)
$assetsRoot = Join-Path $pwd "Assets"
if (-not (Test-Path $assetsRoot)) {
$null = New-Item -ItemType Directory -Path $assetsRoot
}
$docsRoot = Join-Path $pwd "docs"
if (-not (Test-Path $docsRoot)) {
$null = New-Item -ItemType Directory -Path $docsRoot
}
$includesRoot = Join-Path $docsRoot "_includes"
if (-not (Test-Path $includesRoot)) {
$null = New-Item -ItemType Directory -Path $includesRoot
}
$fontSettings = [Ordered]@{
TextAnchor = 'middle'
AlignmentBaseline = 'middle'
Style = "font-family: 'Abel';"
}
$assetFile =
svg -ViewBox 400,400 @(
svg.defs @(
SVG.GoogleFont -FontName Abel
)
=<svg.ellipse> -StrokeWidth 1.25 -Fill transparent -Cx 50% -Cy 50% -Stroke '#4488ff' -Ry 75 -Rx 50 -Class foreground-stroke
=<svg.text> -FontSize 28 -Content 4bit -X 50% -Y 45% @fontSettings -Class foreground-fill -Fill '#4488ff'
$xPercent = 47.5,48.75,51.25,52.55
foreach ($n in 0..3) {
$x = $xPercent[$n]
=<svg.circle> -Class "ansi$($n+1)-fill" -Fill '#4488ff' -Cx "$x%" -Cy 50% -R 0.5%
}
=<svg.text> -FontSize 28 -Content 'css' -X 50% -Y 55% @fontSettings -Class foreground-fill -Fill '#4488ff'
) -OutputPath (Join-Path $assetsRoot .\4bitcss.svg)
$assetFile
$assetFile | Copy-Item -Destination (Join-Path $docsRoot .\4bitcss.svg) -PassThru
svg -ViewBox 640, 640 @(
foreach ($n in 16..1) {
svg.rect -X (
((16 - $n - 1 ) * 20)
) -Y (
((16 - $n - 1 ) * 20)
) -Class "ansi$($n - 1)-fill" -Width (
640 - ((16 - $n - 1 ) * 40)
) -Height (
640 - ((16 - $n - 1 ) * 40)
)
}
) -OutputPath (Join-Path $docsRoot .\4bitpreview.svg) -Width 320
$boxSize = [Ordered]@{Width = 80; Height = 80}
svg -ViewBox 640, 160 @(
foreach ($n in 0..7) {
svg.rect -X ($boxSize.Width * $n) -Y 0 -Class "ansi$n-fill" @boxSize
}
foreach ($n in 8..15) {
svg.rect -X ($boxSize.Width * ($n - 8)) -Y 79 -Class "ansi$n-fill" @boxSize
}
) -OutputPath (Join-Path $docsRoot .\4bitpreview.svg) -Width 320
Copy-Item -Path (Join-Path $docsRoot .\4bitpreview.svg) -Destination (Join-Path $assetsRoot .\4bitpreview.svg) -Force -PassThru
Copy-Item -Path (Join-Path $docsRoot .\4bitpreview.svg) -Destination (Join-Path $includesRoot .\4bitpreview.svg) -Force -PassThru
$colors = 'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Purple', 'Cyan', 'White',
'BrightBlack', 'BrightRed', 'BrightGreen', 'BrightYellow', 'BrightBlue', 'BrightPurple', 'BrightCyan', 'BrightWhite'
svg -ViewBox 640, 240 @(
svg.defs @(
svg.style -Type 'text/css' @'
@import url('/$ColorSchemeFileName/$ColorSchemeFileName.css')
'@
svg.style -Type 'text/css' @'
@import url('https://fonts.googleapis.com/css?family=Abel')
'@
)
svg.rect -Width 640 -Height 80 -X 0 -Y 0 -Class 'background-fill'
svg.text -X 50% -Y 16.5% -Class 'foreground-fill' -Content @(
'$ColorSchemeName'
) @fontSettings
foreach ($n in 0..7) {
svg.rect -X ($boxSize.Width * $n) -Y 79 -Class "ansi$n-fill" @boxSize -Fill $($colors[$n])
}
foreach ($n in 8..15) {
svg.rect -X ($boxSize.Width * ($n - 8)) -Y 159 -Class "ansi$n-fill" @boxSize -Fill $($colors[$n])
}
) -OutputPath (Join-Path $docsRoot .\4bitpreviewtemplate.svg) -Class background-fill
svg -ViewBox 1920, 1080 @(
svg.rect -Width 300% -Height 300% -X -100% -Y -100% -Class 'background-fill'
$initialRadius = (1080/2) - 42
$wobble = .23
$flipFlop = 1
$duration = "04.2s"
filter wobbler {
$initialRadius * (($wobble * $flipFlop) + 1)
}
SVG.ellipse -Id 'foregroundCircle' -Cx 50% -Cy 50% -RX $initialRadius -Ry $initialRadius -Class 'foreground-fill' -Children @(
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'rx' -Dur $duration -RepeatCount indefinite
$flipFlop *= -1
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'ry' -Dur $duration -RepeatCount indefinite
SVG.animate -Values "1;.42;1" -AttributeName 'opacity' -Dur $duration -RepeatCount indefinite
)
foreach ($n in 0..7) {
$initialRadius -= 23
SVG.ellipse -Id "ANSI${N}-Ellipse" -cx 50% -cy 50% -rx $initialRadius -ry $initialRadius -Class "ansi$n-fill" -Fill $($colors[$n]) -Children @(
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'rx' -Dur $duration -RepeatCount indefinite
$flipFlop *= -1
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'ry' -Dur $duration -RepeatCount indefinite
SVG.animate -Values "1;.42;1" -AttributeName 'opacity' -Dur $duration -RepeatCount indefinite
)
$initialRadius -= 16
SVG.ellipse -Id "ANSI$($N + 8)-Ellipse" -Cx 50% -Cy 50% -RX $initialRadius -Ry $initialRadius -Class "ansi$($n + 8)-fill" -Fill $($colors[$n]) -Children @(
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'rx' -Dur $duration -RepeatCount indefinite
$flipFlop *= -1
SVG.animate -Values "$initialRadius;$(wobbler);$initialRadius" -AttributeName 'ry' -Dur $duration -RepeatCount indefinite
SVG.animate -Values "1;.42;1" -AttributeName 'opacity' -Dur $duration -RepeatCount indefinite
)
}
) -OutputPath (Join-Path $includesRoot .\Animated-Palette.svg) -Class background-fill
Copy-Item -Path (Join-Path $docsRoot .\4bitpreviewtemplate.svg) -Destination (Join-Path $assetsRoot ..\4bitpreviewtemplate.svg) -Force -PassThru
Copy-Item -Path (Join-Path $docsRoot .\4bitpreviewtemplate.svg) -Destination (Join-Path $includesRoot .\4bitpreviewtemplate.svg) -Force -PassThru
Pop-Location
|
4bitcss.psd1 | 4bitcss-0.1.5 | @{
ModuleVersion = '0.1.5'
RootModule = '4bitcss.psm1'
Description = 'CSS3 Color Schemes for 4-bit color palettes'
Guid = '93e1d6ab-ce88-4751-bb14-b21fbb9f66f3'
CompanyName = 'Start-Automating'
Author = 'James Brundage'
Copyright = '2022-2024 Start-Automating'
PrivateData = @{
PSData = @{
ProjectURI = 'https://github.com/2bitdesigns'
LicenseURI = 'https://github.com/2bitdesigns/4bitcss/blob/main/LICENSE'
ReleaseNotes = @'
> Like It? [Star It](https://github.com/2bitdesigns/4bitcss)
> Love It? [Support It](https://github.com/sponsors/StartAutomating)
## 0.1.5:
* 336 color palettes (and counting)!
* Improved functionality
* Support for `<button>` (#96)
* `carat-color` support (#97)
* HighlightJS support (#104, #105, #107)
* Added json data files and credits (#79, #80)
* Adding `--Luma` and `--Contrast` to CSS (#94, #95)
* 4bitcss Docker Container (#74, #75, #76, #77)
* Animated Palette Example (#109, #111)
* Improved documentation and examples
---
Additional History in [Changelog](https://github.com/2bitdesigns/4bitcss/blob/main/CHANGELOG.md)
'@
Website = @{
Url = 'https://4bitcss.com/'
Platform = 'Jekyll'
Root = '/docs'
}
}
}
}
|
Build4bitcss.psd1 | 4bitcss-0.1.5 | @{
"runs-on" = "ubuntu-latest"
if = '${{ success() }}'
steps = @(
@{
name = 'Check out repository'
uses = 'actions/checkout@v2'
},
@{
name = 'Use PSSVG Action'
uses = 'StartAutomating/PSSVG@main'
id = 'PSSVG'
},
'RunEZOut',
@{
name = 'PipeScript'
uses = 'StartAutomating/PipeScript@main'
id = 'PipeScript'
with = @{
serial = $true
}
},
'RunHelpOut',
@{
name = 'GitLogger'
uses = 'GitLogging/GitLoggerAction@main'
id = 'GitLogger'
},
@{
'name'='Log in to ghcr.io'
'uses'='docker/login-action@master'
'with'=@{
'registry'='${{ env.REGISTRY }}'
'username'='${{ github.actor }}'
'password'='${{ secrets.GITHUB_TOKEN }}'
}
},
@{
name = 'Extract Docker Metadata (for branch)'
if = '${{github.ref_name != ''main'' && github.ref_name != ''master'' && github.ref_name != ''latest''}}'
id = 'meta'
uses = 'docker/metadata-action@master'
with = @{
'images'='${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}'
}
},
@{
name = 'Extract Docker Metadata (for main)'
if = '${{github.ref_name == ''main'' || github.ref_name == ''master'' || github.ref_name == ''latest''}}'
id = 'metaMain'
uses = 'docker/metadata-action@master'
with = @{
'images'='${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}'
'flavor'='latest=true'
}
},
@{
name = 'Build and push Docker image (from main)'
if = '${{github.ref_name == ''main'' || github.ref_name == ''master'' || github.ref_name == ''latest''}}'
uses = 'docker/build-push-action@master'
with = @{
'context'='.'
'push'='true'
'tags'='${{ steps.metaMain.outputs.tags }}'
'labels'='${{ steps.metaMain.outputs.labels }}'
}
},
@{
name = 'Build and push Docker image (from branch)'
if = '${{github.ref_name != ''main'' && github.ref_name != ''master'' && github.ref_name != ''latest''}}'
uses = 'docker/build-push-action@master'
with = @{
'context'='.'
'push'='true'
'tags'='${{ steps.meta.outputs.tags }}'
'labels'='${{ steps.meta.outputs.labels }}'
}
}
)
} |
4bitcss.psm1 | 4bitcss-0.1.5 | :ToIncludeFiles foreach ($file in (Get-ChildItem -Path "$PSScriptRoot" -Filter "*-*.ps1" -Recurse)) {
if ($file.Extension -ne '.ps1') { continue } # Skip if the extension is not .ps1
foreach ($exclusion in '\.[^\.]+\.ps1$') {
if (-not $exclusion) { continue }
if ($file.Name -match $exclusion) {
continue ToIncludeFiles # Skip excluded files
}
}
. $file.FullName
}
$myModule = $MyInvocation.MyCommand.ScriptBlock.Module
$ExecutionContext.SessionState.PSVariable.Set($myModule.Name, $myModule)
$myModule.pstypenames.insert(0, $myModule.Name)
$newDriveSplat = @{PSProvider='FileSystem';ErrorAction='Ignore';Scope='Global'}
New-PSDrive -Name $MyModule.Name -Root ($MyModule | Split-Path) @newDriveSplat
if ($home) {
$myMyModule = "My$($myModule.Name)"
$myMyModuleRoot = Join-Path $home $myMyModule
if (Test-Path $myMyModuleRoot) {
New-PSDrive -Name $myMyModule -Root $myMyModuleRoot @newDriveSplat
}
}
Export-ModuleMember -Function *-* -Alias * -Variable $myModule.Name
|
64SE.psd1 | 64SE-1.0.0 | @{
# Module manifest for module '64SE'
# Script module or binary module file associated with this manifest.
RootModule = '64SE.psm1'
# Version number of this module.
ModuleVersion = '1.0.0'
# Supported PSEditions
CompatiblePSEditions = @('Desktop', 'Core')
# ID used to uniquely identify this module
GUID = '4a95e4d7-fc7c-437d-a8b1-cf1c2737f0a4'
# Author of this module
Author = 'Kalichuza'
# Company or vendor of this module
CompanyName = 'Kalichuza'
# Copyright statement for this module
Copyright = '(c) 2024 Kalichuza. All rights reserved.'
# Description of the functionality provided by this module
Description = '64SE is a PowerShell module for encoding and decoding strings and files using Base64.'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '5.1'
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @()
# Functions to export from this module
FunctionsToExport = @('Encode-StringToBase64', 'Decode-Base64ToString', 'Encode-FileToBase64', 'Decode-Base64ToFile')
# Cmdlets to export from this module
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = @()
# Aliases to export from this module
AliasesToExport = @()
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @('64SE.psm1', 'en-US/about_64SE.help.txt', 'en-US/Encode-StringToBase64.help.xml', 'en-US/Decode-Base64ToString.help.xml', 'en-US/Encode-FileToBase64.help.xml', 'en-US/Decode-Base64ToFile.help.xml', 'README.md')
# Private data to pass to the module specified in RootModule/ModuleToProcess
PrivateData = @{
# A string containing the license for this module
LicenseUri = 'https://www.gnu.org/licenses/gpl-3.0.txt'
# A URL to the online help for this module
HelpUri = 'https://github.com/kalichuza/64SE'
# Release Notes of this module
ReleaseNotes = 'Initial release of the 64SE module.'
}
# HelpInfo URI of this module
HelpInfoUri = 'https://github.com/kalichuza/64SE'
}
|
64SE.psm1 | 64SE-1.0.0 | # 64SE.psm1
function Encode-StringToBase64 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[string]$InputString
)
process {
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString)
[Convert]::ToBase64String($Bytes)
}
}
function Decode-Base64ToString {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[string]$Base64String
)
process {
$Bytes = [Convert]::FromBase64String($Base64String)
[System.Text.Encoding]::UTF8.GetString($Bytes)
}
}
function Encode-FileToBase64 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$FilePath
)
process {
if (-not (Test-Path $FilePath)) {
Write-Error "File not found: $FilePath"
return
}
$Bytes = [System.IO.File]::ReadAllBytes($FilePath)
$Base64String = [Convert]::ToBase64String($Bytes)
# Create new file path with 64SE before the file extension
$NewFilePath = [System.IO.Path]::ChangeExtension($FilePath, "64SE" + [System.IO.Path]::GetExtension($FilePath))
# Write the Base64 string to the new file
[System.IO.File]::WriteAllText($NewFilePath, $Base64String)
Write-Output "Encoded file created at $NewFilePath"
}
}
function Decode-Base64ToFile {
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Base64String,
[Parameter(Mandatory = $true, Position = 1)]
[string]$FilePath
)
process {
if (-not $Base64String) {
# Read the content from the file if Base64String is not provided
$Base64String = Get-Content -Path $FilePath -Raw
}
try {
$Bytes = [Convert]::FromBase64String($Base64String)
# Determine the new file path
if ($FilePath -like "*.64SE.*") {
$NewFilePath = $FilePath -replace '\.64SE\.', '.decoded.'
} else {
$NewFilePath = [System.IO.Path]::ChangeExtension($FilePath, ".decoded" + [System.IO.Path]::GetExtension($FilePath))
}
[System.IO.File]::WriteAllBytes($NewFilePath, $Bytes)
Write-Output "Decoded file created at $NewFilePath"
} catch {
Write-Error "Failed to decode Base64 string: $_"
}
}
}
# Exporting functions
Export-ModuleMember -Function Encode-StringToBase64, Decode-Base64ToString, Encode-FileToBase64, Decode-Base64ToFile
|
Test-Module.ps1 | 7-ZipSetupManager-1.0.0.1 | <#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2023 v5.8.219
Created on: 26.3.2023. 00:58
Created by: chxus
Organization: CHXOFT
Filename: Test-Module.ps1
===========================================================================
.DESCRIPTION
The Test-Module.ps1 script lets you test the functions and other features of
your module in your PowerShell Studio module project. It's part of your project,
but it is not included in your module.
In this test script, import the module (be careful to import the correct version)
and write commands that test the module features. You can include Pester
tests, too.
To run the script, click Run or Run in Console. Or, when working on any file
in the project, click Home\Run or Home\Run in Console, or in the Project pane,
right-click the project name, and then click Run Project.
#>
#Explicitly import the module for testing
Import-Module '7-ZipSetupManager'
#Run each module function
Get-7ZipDownloadLink
Get-7ZipInstallationPath
Get-7ZipSetup -Path C:\Temp\
Get-7ZipInstallationPath -GetVersionOnly
Get-7ZipInstallationPath -Property
#Sample Pester Test
#Describe "Test 7-ZipSetupManager" {
# It "tests Write-HellowWorld" {
# Write-HelloWorld | Should BeExactly "Hello World"
# }
#}
|
7ZipSetupManager-Module.ps1 | 7-ZipSetupManager-1.0.0.1 | <#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2023 v5.8.219
Created on: 26.3.2023. 00:58
Created by: chx
Organization: CHXOFT
Filename: 7ZipSetupManager-Module.ps1
===========================================================================
.DESCRIPTION
The Test-Module.ps1 script lets you test the functions and other features of
your module in your PowerShell Studio module project. It's part of your project,
but it is not included in your module.
In this test script, import the module (be careful to import the correct version)
and write commands that test the module features. You can include Pester
tests, too.
To run the script, click Run or Run in Console. Or, when working on any file
in the project, click Home\Run or Home\Run in Console, or in the Project pane,
right-click the project name, and then click Run Project.
#>
#Explicitly import the module for testing
Import-Module '7-ZipSetupManager'
#Run each module function
Write-HelloWorld
#Sample Pester Test
#Describe "Test 7-ZipSetupManager" {
# It "tests Write-HellowWorld" {
# Write-HelloWorld | Should BeExactly "Hello World"
# }
#}
|
7-ZipSetupManager.psm1 | 7-ZipSetupManager-1.0.0.1 | <#
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2023 v5.8.219
Created on: 26.3.2023. 00:58
Created by: chxus
Organization: CHXOFT
Filename: 7-ZipSetupManager.psm1
-------------------------------------------------------------------------
Module Name: 7-ZipSetupManager
===========================================================================
#>
<#
.EXTERNALHELP 7-ZipSetupManager.psm1-Help.xml
#>
function Get-7ZipDownloadLink
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $false,
Position = 1,
HelpMessage = 'Get 32bit installer.')]
[switch]$x86,
[Parameter(Mandatory = $false,
Position = 2)]
[switch]$GetFileNameOnly
)
$7zipDownloadWebpage = (Invoke-WebRequest https://7-zip.org/download.html).AllElements
if (-not ($x86))
{
$setup = $7zipDownloadWebpage.href -like "*7z*-x64.exe"
if ($setup.Count -gt 1)
{
$setup = $setup.Split([Environment]::NewLine) | Select-Object -First 1
}
}
else
{
$setup = $7zipDownloadWebpage.href -like "*7z*.exe" -cnotlike "*x64*"
if ($setup.Count -gt 1)
{
$setup = $setup.Split([Environment]::NewLine) | Select-Object -First 1
}
}
$name = $setup.Split('/')
$name = $name[1]
$DownloadLink = "https://7-zip.org/$setup"
if ($GetFileNameOnly)
{
return $name
}
else
{
return $DownloadLink
}
}
<#
.EXTERNALHELP 7-ZipSetupManager.psm1-Help.xml
#>
function Get-7ZipInstallationPath
{
[CmdletBinding()]
param
(
[switch]$GetVersionOnly,
[switch]$Property,
[switch]$CheckAll
)
$GetPath = Microsoft.PowerShell.Management\Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip*
if (-not ($GetPath))
{
$GetPath = Microsoft.PowerShell.Management\Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip*
}
if ($GetPath)
{
$GetPath = Microsoft.PowerShell.Management\Get-ItemProperty $GetPath.PsPath
$InstallPath = $GetPath.InstallLocation
$Version = $GetPath.DisplayVersion
if ($CheckAll)
{
if ($GetPath.DisplayName -like '*x64*')
{
$Pathx86 = Microsoft.PowerShell.Management\Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip*
if ($Pathx86)
{
$Pathx86 = Microsoft.PowerShell.Management\Get-ItemProperty $Pathx86.PsPath
$InstallPathx86 = $Pathx86.InstallLocation
$InstallPath = $InstallPath + "`n" + $InstallPathx86
}
}
}
if ($Property)
{
return $GetPath
}
elseif ($GetVersionOnly)
{
return $Version
}
else
{
return $InstallPath
}
}
else
{
return $false
}
}
<#
.EXTERNALHELP 7-ZipSetupManager.psm1-Help.xml
#>
function Get-7ZipSetup
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $false,
Position = 1,
HelpMessage = 'Enter valid path to download.',
HelpMessageBaseName = 'Download path')]
[AllowEmptyString()]
[string]$Path,
[Parameter(Position = 2)]
[switch]$x86,
[Parameter(Position = 3)]
[switch]$AndStartInstallation,
[Parameter(Mandatory = $false,
Position = 4,
DontShow = $true)]
[switch]$Silent
)
# Get-7ZipDownloadLink
if ($x86)
{
$DownloadLink = Get-7ZipDownloadLink -x86
$FileName = Get-7ZipDownloadLink -GetFileNameOnly
}
else
{
$DownloadLink = Get-7ZipDownloadLink
$FileName = Get-7ZipDownloadLink -GetFileNameOnly
}
$DownloadPath = (Microsoft.PowerShell.Management\Get-Location).Path + "\$FileName"
if ($path)
{
if (Microsoft.PowerShell.Management\Resolve-Path -Path "$Path" -ErrorAction SilentlyContinue)
{
$DownloadPath = $Path + $FileName
}
else
{
return 'Path does not exist.'
}
}
Microsoft.PowerShell.Utility\Invoke-WebRequest -Uri $DownloadLink -OutFile $DownloadPath -ErrorAction Stop
if ($AndStartInstallation)
{
if (-not ($Silent))
{
Microsoft.PowerShell.Management\Start-Process -FilePath $DownloadPath -Wait
}
else
{
Microsoft.PowerShell.Management\Start-Process -FilePath $DownloadPath -ArgumentList "/S" -Wait
}
return 'Installation complete.'
}
else
{
return "Downloaded to: $DownloadPath"
}
}
<#
.EXTERNALHELP 7-ZipSetupManager.psm1-Help.xml
#>
function Uninstall-7Zip
{
[CmdletBinding()]
param
(
[switch]$Silent
)
# Get-7ZipInstallationPath
$path = Get-7ZipInstallationPath -CheckAll
if (-not ($path))
{
return '7-Zip is not installed.'
}
else
{
$check = $path | Microsoft.PowerShell.Utility\Measure-Object -Line
if ($check.Lines -eq 2)
{
Microsoft.PowerShell.Utility\Write-Warning 'Found both 64bit and 32bit installations, removing 64bit first, to remove the 32bit also run this command again.'
}
$uninstall = Get-7ZipInstallationPath -Property
$uninstall = $uninstall.UninstallString
if ($Silent)
{
Microsoft.PowerShell.Management\Start-Process -FilePath $uninstall -ArgumentList "/S" -Wait -ErrorAction Stop
}
else
{
Microsoft.PowerShell.Management\Start-Process -FilePath $uninstall -Wait -ErrorAction Stop
}
$path = Get-7ZipInstallationPath -CheckAll
if (-not ($path))
{
return '7-Zip for Windows uninstalled completely.'
}
else
{
$check = $path | Microsoft.PowerShell.Utility\Measure-Object -Line
if ($check.Lines -eq 2)
{
return 'Uninstall canceled or error occured, both versions present 64 and 32 bit.'
}
else
{
return 'Uninstall canceled or there is 32bit version left to uninstall.'
}
}
}
}
# SIG # Begin signature block
# MIIbRwYJKoZIhvcNAQcCoIIbODCCGzQCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB4Bw+FFzxoNNs0
# aCPZma7ILY8+jg8+dfAyCSuY1N2SDaCCFYYwggMyMIICGqADAgECAhCuC7oCPbvl
# rEJ4JzUZnfD8MA0GCSqGSIb3DQEBCwUAMBoxGDAWBgNVBAMTD0NNYWtlIFRlc3Qg
# Q2VydDAgFw0xNDAxMDEwNzAwMDBaGA8yMTAwMDEwMTA3MDAwMFowGjEYMBYGA1UE
# AxMPQ01ha2UgVGVzdCBDZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
# AQEAy/GcWKj93HO+1SylOUMgS6KhJLQrTvn2Qscmm6XzRcZhUTxPWMJ/q6YvN3uY
# m7qIvfQw6nBPfCvZIEjkmGECRZPdCZc0v1KLhvhLYSxIpxHpYIFW9+mxEj0fJEOL
# PI1UeVgQnZCutFBPNEjCLhiR2v+pnF03tbuFO9P2q2ksYUhkapw5Y7Z7nOQVKgNC
# np5bDj4ONVIw4SBcqDukQZzcOHc0IEHleCP9R0BuBdT6LWqovYWD5F0AVPnmm7G1
# DpYKzAl+IwS2eCBGH2Q5H2UODEXa24R5XEWFl70CODl+wPzvpkID2UXRxrKpnxk/
# pUOhPq7Ia2jjepEU+aX5lKZlzQIDAQABo3IwcDAMBgNVHRMBAf8EAjAAMBMGA1Ud
# JQQMMAoGCCsGAQUFBwMDMEsGA1UdAQREMEKAEHT4UyF9dmOb2B+yY+KJZQOhHDAa
# MRgwFgYDVQQDEw9DTWFrZSBUZXN0IENlcnSCEK4LugI9u+WsQngnNRmd8PwwDQYJ
# KoZIhvcNAQELBQADggEBADf+AAZY1XexFIR6aLecXEFk2J9UjmL5WD2m6VNpgJd4
# 1SFesljqNTwu6qpOJ16qrK9ikHjbTpQBtxOEVrZz3XlbrgbC6jvDNegkm2eOD8NQ
# toEozzgu/Aj8cGSDK7vXv314ViZ5j10Dl+chKwhr7sipLQO317/eaWOTmAkvHQ+n
# tvVi81K87UlYtiPtKZz6haNqfRYM9DkJM5lzLl/wyyXf1UAP+uQSEHfizwYwUUNe
# MCfaGMuvYZqecACaETQBWCaKfe7/cwDcOiO0WEz9e4utvSVxgZfoICb1BXFmF1Fc
# xN6Z4mq4RxrdcRswl37IHYaU2p+oebwf7xGPHqXebkYwggWDMIIDa6ADAgECAg5F
# 5rsDgzPDhWVI5v9FUTANBgkqhkiG9w0BAQwFADBMMSAwHgYDVQQLExdHbG9iYWxT
# aWduIFJvb3QgQ0EgLSBSNjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMK
# R2xvYmFsU2lnbjAeFw0xNDEyMTAwMDAwMDBaFw0zNDEyMTAwMDAwMDBaMEwxIDAe
# BgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFI2MRMwEQYDVQQKEwpHbG9iYWxT
# aWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
# MIICCgKCAgEAlQfoc8pm+ewUyns89w0I8bRFCyyCtEjG61s8roO4QZIzFKRvf+kq
# zMawiGvFtonRxrL/FM5RFCHsSt0bWsbWh+5NOhUG7WRmC5KAykTec5RO86eJf094
# YwjIElBtQmYvTbl5KE1SGooagLcZgQ5+xIq8ZEwhHENo1z08isWyZtWQmrcxBsW+
# 4m0yBqYe+bnrqqO4v76CY1DQ8BiJ3+QPefXqoh8q0nAue+e8k7ttU+JIfIwQBzj/
# ZrJ3YX7g6ow8qrSk9vOVShIHbf2MsonP0KBhd8hYdLDUIzr3XTrKotudCd5dRC2Q
# 8YHNV5L6frxQBGM032uTGL5rNrI55KwkNrfw77YcE1eTtt6y+OKFt3OiuDWqRfLg
# nTahb1SK8XJWbi6IxVFCRBWU7qPFOJabTk5aC0fzBjZJdzC8cTflpuwhCHX85mEW
# P3fV2ZGXhAps1AJNdMAU7f05+4PyXhShBLAL6f7uj+FuC7IIs2FmCWqxBjplllnA
# 8DX9ydoojRoRh3CBCqiadR2eOoYFAJ7bgNYl+dwFnidZTHY5W+r5paHYgw/R/98w
# EfmFzzNI9cptZBQselhP00sIScWVZBpjDnk99bOMylitnEJFeW4OhxlcVLFltr+M
# m9wT6Q1vuC7cZ27JixG1hBSKABlwg3mRl5HUGie/Nx4yB9gUYzwoTK8CAwEAAaNj
# MGEwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFK5s
# BaOTE+Ki5+LXHNbH8H/IZ1OgMB8GA1UdIwQYMBaAFK5sBaOTE+Ki5+LXHNbH8H/I
# Z1OgMA0GCSqGSIb3DQEBDAUAA4ICAQCDJe3o0f2VUs2ewASgkWnmXNCE3tytok/o
# R3jWZZipW6g8h3wCitFutxZz5l/AVJjVdL7BzeIRka0jGD3d4XJElrSVXsB7jpl4
# FkMTVlezorM7tXfcQHKso+ubNT6xCCGh58RDN3kyvrXnnCxMvEMpmY4w06wh4OMd
# +tgHM3ZUACIquU0gLnBo2uVT/INc053y/0QMRGby0uO9RgAabQK6JV2NoTFR3VRG
# HE3bmZbvGhwEXKYV73jgef5d2z6qTFX9mhWpb+Gm+99wMOnD7kJG7cKTBYn6fWN7
# P9BxgXwA6JiuDng0wyX7rwqfIGvdOxOPEoziQRpIenOgd2nHtlx/gsge/lgbKCuo
# bK1ebcAF0nu364D+JTf+AptorEJdw+71zNzwUHXSNmmc5nsE324GabbeCglIWYfr
# exRgemSqaUPvkcdM7BjdbO9TLYyZ4V7ycj7PVMi9Z+ykD0xF/9O5MCMHTI8Qv4aW
# 2ZlatJlXHKTMuxWJU7osBQ/kxJ4ZsRg01Uyduu33H68klQR4qAO77oHl2l98i0qh
# kHQlp7M+S8gsVr3HyO844lyS8Hn3nIS6dC1hASB+ftHyTwdZX4stQ1LrRgyU4fVm
# R3l31VRbH60kN8tFWk6gREjI2LCZxRWECfbWSUnAZbjmGnFuoKjxguhFPmzWAtcK
# Z4MFWsmkEDCCBlkwggRBoAMCAQICDQHsHJJA3v0uQF18R3QwDQYJKoZIhvcNAQEM
# BQAwTDEgMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoT
# Ckdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTgwNjIwMDAwMDAw
# WhcNMzQxMjEwMDAwMDAwWjBbMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFs
# U2lnbiBudi1zYTExMC8GA1UEAxMoR2xvYmFsU2lnbiBUaW1lc3RhbXBpbmcgQ0Eg
# LSBTSEEzODQgLSBHNDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPAC
# 4jAj+uAb4Zp0s691g1+pR1LHYTpjfDkjeW10/DHkdBIZlvrOJ2JbrgeKJ+5Xo8Q1
# 7bM0x6zDDOuAZm3RKErBLLu5cPJyroz3mVpddq6/RKh8QSSOj7rFT/82QaunLf14
# TkOI/pMZF9nuMc+8ijtuasSI8O6X9tzzGKBLmRwOh6cm4YjJoOWZ4p70nEw/XVvs
# tu/SZc9FC1Q9sVRTB4uZbrhUmYqoMZI78np9/A5Y34Fq4bBsHmWCKtQhx5T+QpY7
# 8Quxf39GmA6HPXpl69FWqS69+1g9tYX6U5lNW3TtckuiDYI3GQzQq+pawe8P1Zm5
# P/RPNfGcD9M3E1LZJTTtlu/4Z+oIvo9Jev+QsdT3KRXX+Q1d1odDHnTEcCi0gHu9
# Kpu7hOEOrG8NubX2bVb+ih0JPiQOZybH/LINoJSwspTMe+Zn/qZYstTYQRLBVf1u
# kcW7sUwIS57UQgZvGxjVNupkrs799QXm4mbQDgUhrLERBiMZ5PsFNETqCK6dSWcR
# i4LlrVqGp2b9MwMB3pkl+XFu6ZxdAkxgPM8CjwH9cu6S8acS3kISTeypJuV3AqwO
# VwwJ0WGeJoj8yLJN22TwRZ+6wT9Uo9h2ApVsao3KIlz2DATjKfpLsBzTN3SE2R1m
# qzRzjx59fF6W1j0ZsJfqjFCRba9Xhn4QNx1rGhTfAgMBAAGjggEpMIIBJTAOBgNV
# HQ8BAf8EBAMCAYYwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU6hbGaefj
# y1dFOTOk8EC+0MO9ZZYwHwYDVR0jBBgwFoAUrmwFo5MT4qLn4tcc1sfwf8hnU6Aw
# PgYIKwYBBQUHAQEEMjAwMC4GCCsGAQUFBzABhiJodHRwOi8vb2NzcDIuZ2xvYmFs
# c2lnbi5jb20vcm9vdHI2MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwuZ2xv
# YmFsc2lnbi5jb20vcm9vdC1yNi5jcmwwRwYDVR0gBEAwPjA8BgRVHSAAMDQwMgYI
# KwYBBQUHAgEWJmh0dHBzOi8vd3d3Lmdsb2JhbHNpZ24uY29tL3JlcG9zaXRvcnkv
# MA0GCSqGSIb3DQEBDAUAA4ICAQB/4ojZV2crQl+BpwkLusS7KBhW1ky/2xsHcMb7
# CwmtADpgMx85xhZrGUBJJQge5Jv31qQNjx6W8oaiF95Bv0/hvKvN7sAjjMaF/ksV
# JPkYROwfwqSs0LLP7MJWZR29f/begsi3n2HTtUZImJcCZ3oWlUrbYsbQswLMNEhF
# Vd3s6UqfXhTtchBxdnDSD5bz6jdXlJEYr9yNmTgZWMKpoX6ibhUm6rT5fyrn50hk
# aS/SmqFy9vckS3RafXKGNbMCVx+LnPy7rEze+t5TTIP9ErG2SVVPdZ2sb0rILmq5
# yojDEjBOsghzn16h1pnO6X1LlizMFmsYzeRZN4YJLOJF1rLNboJ1pdqNHrdbL4gu
# PX3x8pEwBZzOe3ygxayvUQbwEccdMMVRVmDofJU9IuPVCiRTJ5eA+kiJJyx54jzl
# mx7jqoSCiT7ASvUh/mIQ7R0w/PbM6kgnfIt1Qn9ry/Ola5UfBFg0ContglDk0Xuo
# yea+SKorVdmNtyUgDhtRoNRjqoPqbHJhSsn6Q8TGV8Wdtjywi7C5HDHvve8U2BRA
# bCAdwi3oC8aNbYy2ce1SIf4+9p+fORqurNIveiCx9KyqHeItFJ36lmodxjzK89kc
# v1NNpEdZfJXEQ0H5JeIsEH6B+Q2Up33ytQn12GByQFCVINRDRL76oJXnIFm2eMak
# aqoimzCCBmgwggRQoAMCAQICEAFIkD3CirynoRlNDBxXuCkwDQYJKoZIhvcNAQEL
# BQAwWzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAv
# BgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMzg0IC0gRzQw
# HhcNMjIwNDA2MDc0MTU4WhcNMzMwNTA4MDc0MTU4WjBjMQswCQYDVQQGEwJCRTEZ
# MBcGA1UECgwQR2xvYmFsU2lnbiBudi1zYTE5MDcGA1UEAwwwR2xvYmFsc2lnbiBU
# U0EgZm9yIE1TIEF1dGhlbnRpY29kZSBBZHZhbmNlZCAtIEc0MIIBojANBgkqhkiG
# 9w0BAQEFAAOCAY8AMIIBigKCAYEAwsncA7YbUPoqDeicpCHbKKcd9YC1EnQj/l4v
# wxpdlrIgGRlQX3YjJjXGIeyU77WiOsWQgZsh7wsnpOMXZDvak9RWLzzXWPltrMAv
# kHgjScD4wY9wE9Rr3yaIWnZ7SPfhpKbvCxrzJVQPgJ4jEhIT0bD3AuMrDf9APgBC
# Q94a70z0h6nynjzQBufiY9LrTFvdXViU0+WlOSiqB152IzD8/H+YDcVlbRvVdEU6
# RrCiFnXeosIqcHy2drzZG666XZz2h5XOqqjitaOxk25ApZsQiHYWTjSh/J7x4RpU
# 0cgkV5R2rcLH7KOjlnXixihrAgXoS7m14FIreAGMKjEsTOgF5W+fD4QmLmhs+stN
# GXwYwf9qGqnLvqN1+OnIGLLM3S9BQCAcz4gLF8mwikPL4muTUfERvkK8+FHy2gAC
# vggYKAUnxNw7XXcpHhnUQSpmfbRSc1xCpZDTjcWjqjfOcwGUJBlCQ9GUj0t+3ctt
# vBtOe/mqCyJLSYBJcBstT940YD69AgMBAAGjggGeMIIBmjAOBgNVHQ8BAf8EBAMC
# B4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwHQYDVR0OBBYEFFtre/RwdAjBDSrI
# 7/HEuUDSSsb9MEwGA1UdIARFMEMwQQYJKwYBBAGgMgEeMDQwMgYIKwYBBQUHAgEW
# Jmh0dHBzOi8vd3d3Lmdsb2JhbHNpZ24uY29tL3JlcG9zaXRvcnkvMAwGA1UdEwEB
# /wQCMAAwgZAGCCsGAQUFBwEBBIGDMIGAMDkGCCsGAQUFBzABhi1odHRwOi8vb2Nz
# cC5nbG9iYWxzaWduLmNvbS9jYS9nc3RzYWNhc2hhMzg0ZzQwQwYIKwYBBQUHMAKG
# N2h0dHA6Ly9zZWN1cmUuZ2xvYmFsc2lnbi5jb20vY2FjZXJ0L2dzdHNhY2FzaGEz
# ODRnNC5jcnQwHwYDVR0jBBgwFoAU6hbGaefjy1dFOTOk8EC+0MO9ZZYwQQYDVR0f
# BDowODA2oDSgMoYwaHR0cDovL2NybC5nbG9iYWxzaWduLmNvbS9jYS9nc3RzYWNh
# c2hhMzg0ZzQuY3JsMA0GCSqGSIb3DQEBCwUAA4ICAQAuaz6Pf7CwYNnxnYTclbbf
# Xw2/JFHjGgaqVQTLYcHvZXGuC/2UJFcAx+T2DLwYlX0vGWpgM6a+0AhVVgS24/4e
# u+UQdlQ7q1whXio1TUbLpky6BEBgYCzb0/ad3soyEAx4sLtWxQdLcLynD6tyvI3L
# 6+7BTGvZ+pihdD7pqMh5fHZ3SP3P4/ANwenDkuAHDBMvP2t/NdnVt+5vfFjA8T8M
# GbICo0lMnATD8LSXp+BNaiW6NBZiZsh4vGlzql9yojVYHibrvzIUqhJ66/SWa39y
# rOqnOQgzATY+YSR+EZ0RHnYiVONAuy6GDHaeadLEHD2iC4yIBANU3ukbF/4sK57Z
# 1lsiOPxkQIbNF3/hqZ+5v5JBqG8mavQPKLBAkZAvTrZ2ULxNI9l/T2uTKads59Aw
# PqmTH8JQKznFsvhNJyTR/XbYvvmT9KlUCtV2WNE8nuoa6CTE+zbxL1nTksPsy2BS
# HhxGJQj/ftmTrhSVqIaKBy5Ui3NMNxU4UFaH8U+uHI/JoWwvC/y7HG8tvaq262gj
# 8O2UJxRjy6z0Z4osgdMUEhgBP4R6ruxHYD9oWJnJSsKhmRUFwq3eou/Xp1V8vIQb
# TZS7jkqFRNmBPaqjJVVfpGvNNmwA+f9y3lrs/8mgQZYaQGqFkRyvdWOoy1oztZQz
# frKND3O+h/yvOnMfeyDbcjGCBRcwggUTAgEBMC4wGjEYMBYGA1UEAxMPQ01ha2Ug
# VGVzdCBDZXJ0AhCuC7oCPbvlrEJ4JzUZnfD8MA0GCWCGSAFlAwQCAQUAoEwwGQYJ
# KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwLwYJKoZIhvcNAQkEMSIEIPzv5yQ5PZW/
# lMMZ+4SxbboaB7c3xcIJCftE9XCIRTAqMA0GCSqGSIb3DQEBAQUABIIBALSnXm8g
# 2bBiv3dKOLsPVcwF+X4MG8PFYxoXpmBM82gfn9i6xMfKeMtN9wzPRvn//+lJBwPB
# 9C9zYdRdsxYAAOmW3iCsg8ygyfAg57Zc3JUhbDzFn2CdmKsgUQ+0KTOpSaPnhpOv
# ycXDjF3TO3syDcaIZ23qsbyLCJfpvFGlilvHkHLa8qbPuPTNYeRTk/z4V2wcdQqX
# wwgtZ06ADepqomUzqZq2m+BT8MjzUsIoZxFEfZjHER3rnY8S9sfeC0AZHaSFdj+D
# Of8C4XTGFpZRonwmWq+lf7aDb9nT84yXbGie7086G/R0LJi6UnqVrDMmWDQ9F0GE
# HTxrFP/JORi36VyhggNsMIIDaAYJKoZIhvcNAQkGMYIDWTCCA1UCAQEwbzBbMQsw
# CQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTExMC8GA1UEAxMo
# R2xvYmFsU2lnbiBUaW1lc3RhbXBpbmcgQ0EgLSBTSEEzODQgLSBHNAIQAUiQPcKK
# vKehGU0MHFe4KTALBglghkgBZQMEAgGgggE9MBgGCSqGSIb3DQEJAzELBgkqhkiG
# 9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTIzMDMyNjA5NDAxN1owKwYJKoZIhvcNAQk0
# MR4wHDALBglghkgBZQMEAgGhDQYJKoZIhvcNAQELBQAwLwYJKoZIhvcNAQkEMSIE
# IBFsxtUHDCTMBMrAfNebv6zHf5/pDFeTf2yYpCHsjhEJMIGkBgsqhkiG9w0BCRAC
# DDGBlDCBkTCBjjCBiwQUMQMOF2qkWS6rLIut6DKZ/LVYXc8wczBfpF0wWzELMAkG
# A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAvBgNVBAMTKEds
# b2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMzg0IC0gRzQCEAFIkD3Ciryn
# oRlNDBxXuCkwDQYJKoZIhvcNAQELBQAEggGAwPggAuo23t9o4yuVzN1nXALyh/CE
# Z77gYI/UiP91luBfXNMyuIDso3moLwgzFIVmfmfZGMsI6Dl7WV6AgUvTGZlwIYcD
# 3CZnvBRr7K39PzG+Y/XaQAmTcaaguy94oeSC4g4lT+QQcdiMgMpvjTmRaFbUNeR7
# 9o/hk8biwkfS1sBEFGZMOPKlOaEGAvJVcbLPp0mpMm5XSESaewsPniYEFbmy0XzY
# 3ZJP8dcsrm4K+yovPHerfaf6RLH6cr5PMEe+PjYDZONAc8Nv1i+gfIh6MLECX+rB
# k7+nOCImnrvDBBs/OzfnbnCFcaflInINpsUYuN1yGdOalBYpiXZOFfsiq1BCLtFE
# AuDDLKFzh7u3xi/eBPCTVRUyFKI44ipqqpSpNW1H87iOFjhrLOpMR0y1PJwtcWox
# QKZEpNZphxm8nZSuyIfSrMjlwQVb4UXotkoFiWs9qHVKdjiIRzziKF5nWIMyhsp7
# EuytGqm8XoH0pcQHwQc8ey5W7xDWLV7X1qhS
# SIG # End signature block
|
7-ZipSetupManager.psd1 | 7-ZipSetupManager-1.0.0.1 | <#
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2023 v5.8.219
Created on: 26.3.2023. 00:58
Created by: chxus
Organization: CHXOFT
Filename: 7-ZipSetupManager.psd1
-------------------------------------------------------------------------
Module Manifest
-------------------------------------------------------------------------
Module Name: 7-ZipSetupManager
===========================================================================
#>
@{
# Script module or binary module file associated with this manifest
RootModule = '7-ZipSetupManager.psm1'
# Version number of this module.
ModuleVersion = '1.0.0.1'
# ID used to uniquely identify this module
GUID = '0c21eacc-a4a1-4a31-9696-ab2e7a161138'
# Author of this module
Author = 'chxus'
# Company or vendor of this module
CompanyName = 'CHXOFT'
# Copyright statement for this module
Copyright = '(c) 2023. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Get direct link to newest version of 7-Zip (x64 and x86), install / uninstall (normal or silently), check installed path, version.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = '2.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = '2.0.50727'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'None'
# Modules that must be imported into the global environment prior to importing
# this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to
# importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in
# ModuleToProcess
NestedModules = @()
# Functions to export from this module
FunctionsToExport = @(
'Get-7ZipDownloadLink',
'Get-7ZipInstallationPath',
'Get-7ZipSetup',
'Uninstall-7Zip'
) #For performance, list functions explicitly
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*' #For performance, list alias explicitly
# DSC class resources to export from this module.
#DSCResourcesToExport = ''
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
#Support for PowerShellGet galleries.
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
} |
testpage.ps1 | 7DWSM-1.4.0 | @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample Web Site Template - PoSH Server</title>
<meta name="author" content="Your Inspiration Web - Nando [php, xhtml, css], Sara [graphic design]" />
<meta name="keywords" content="single web page, single page website, single page template, single page layout"
/>
<meta name="description" content=""
/>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<!-- [template css] begin -->
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/960.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<!--[if IE]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" />
<![endif]-->
<!-- [template css] end -->
<!-- [favicon] begin -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<!-- [favicon] end -->
<!-- Some hacks for the dreaded IE6 ;) -->
<!--[if lt IE 7]>
<link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" />
<script type="text/javascript">
var clear="images/clear.gif";
</script>
<script type="text/javascript" src="js/unitpngfix.js"></script>
<![endif]-->
<script type="text/javascript" src="js/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" charset="utf-8">jQuery.noConflict();</script>
<!-- START SCROLL -->
<script src="js/scroll.js" type="text/javascript"></script>
<!-- END SCROLL -->
<!-- START CUFON -->
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/dustismo_400.font.js"></script>
<script type="text/javascript">
Cufon.replace('h1,ul#nav,h2,h4', {
hover: true,
fontFamily: 'dustismo'
});
</script>
<!-- END CUFON -->
<!-- START VALIDATE FORM CONTACT -->
<script type="text/javascript" src="js/form-contact-validate.js"></script>
<!-- END VALIDATE FORM CONTACT -->
</head>
<body id="home-page">
<!-- START TOP FADE -->
<div class="top-bg"> </div>
<!-- END TOP FADE -->
<!-- START BOTTOM FADE -->
<div class="bottom-bg"> </div>
<!-- END BOTTOM FADE -->
<!-- START HEADER -->
<div class="container_12">
<!-- START NAVIGATION SECTION -->
<div class="grid_3 alpha">
<div class="fixed-column">
<!-- START LOGO -->
<a href="index.htm" title="home page">
<img src="images/logo.png" alt="logo" class="logo" />
</a>
<!-- END LOGO -->
<!-- START NAV -->
<ul id="nav">
<li><a href="#home-page" title="Home page">home</a></li>
<li><a href="#about-page" title="about">about</a></li>
<li><a href="#portfolio-page" title="portfolio">portfolio</a></li>
<li><a href="#contact-page" title="contatti">contact</a></li>
</ul>
<!-- END NAV -->
<!-- START FOLLOW ME -->
<a href="#" title="follow me on twitter">
<img src="images/follow-me.gif" alt="follow-me" class="follow-me" />
</a>
<!-- END FOLLOW ME -->
<!-- START SEND ME AN EMAIL -->
<a href="mailto:[email protected]" title="Send me an email">
<img src="images/send-mail.gif" alt="send mail" />
</a>
<!-- END SEND ME AN EMAIL -->
<!-- START ADD ME ON SKYPE -->
<a href="#" title="Add me on Skype">
<img src="images/add-on-skype.png" alt="add skype" />
</a>
<!-- END ADD ME ON SKYPE -->
<!-- DO NOT REMOVE: START CREDITS -->
<div class="credits">
<!--<a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/2.5/it/80x15.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">Your Inspiration Folio</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.yourinspirationweb.com" property="cc:attributionName" rel="cc:attributionURL">Your Inspiration Web</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/">Creative Commons Attribuzione 2.5 Italia License</a>.--> powered by
<a href="http://www.yourinspirationweb.com/en/free-website-template-present-your-portfolio-online-in-a-single-webpage/" title="The Community of Inspiration Dedicated to Webdesign">
YIW
</a>
</div>
<!-- END CREDITS -->
</div>
</div>
<!-- END NAVIGATION SECTION -->
<div class="grid_9 omega right-column">
<!-- START HOME PAGE -->
<div class="home">
<!--<img src="images/text-home.jpg" alt="contenuto-home" />-->
<h1>
Welcome to <span>PoSH Server!</span> You can use Powershell commands with <span>html</span> codes. HEY Sean! Let's get date: <span>$(Get-Date)</span>
</h1>
<!--<img src="images/arrow-home.png" alt="arrow" class="arrow" />-->
</div>
<div class="home-bottom-bg"></div>
<!-- END HOME PAGE -->
<!-- START ABOUT PAGE -->
<a id="about-page"></a>
<div class="about">
<div class="grid_5 alpha">
<div class="container-about">
<h2>About</h2>
<p>
In the About page you can insert some information on yourself: title of study,
eventual training courses attended, certificates, diplomas.
</p>
<p>
Or you can describe your dreams, your work experiences... in a few words everything
that can represent <span>you on the web</span> in a decisive and original way.
</p>
<p>
Insert a small picture or even a <span>cartoon</span> just like the one I have inserted: nowdays illustrations are the trend!
</p>
</div>
</div>
<!-- START AVATAR -->
<div class="grid_4 omega avatar-image">
<img src="images/avatar.jpg" alt="avatar" class="avatar" />
</div>
<!-- END AVATAR -->
<div class="clear"></div>
</div>
<div class="about-bottom-bg"></div>
<!-- END ABOUT PAGE -->
<!-- START PORTFOLIO PAGE -->
<a id="portfolio-page"></a>
<div class="portfolio">
<div class="grid_4 alpha">
<div class="container-portfolio">
<h2>Portfolio</h2>
</div>
</div>
<!-- START PORTFOLIO QUOTE -->
<div class="grid_4 omega">
<div class="portfolio-quote">
<h4>I hope you like my work and my work speaks for me.</h4>
</div>
</div>
<!-- END PORTFOLIO QUOTE -->
<div class="clear"></div>
<div class="container-portfolio">
<!-- START THUMB IMAGE -->
<div class="photo">
<a href="#project01">
<img src="images/portfolio/003.big.jpg" height="85" width="85" alt="WordPress Theme" />
</a>
</div>
<div class="photo">
<a href="#project02">
<img src="images/portfolio/001.big.jpg" height="85" width="85" alt="Asilo nido" />
</a>
</div>
<div class="photo">
<a href="#project03">
<img src="images/portfolio/002.big.jpg" height="85" width="85" alt="One Page Folio" />
</a>
</div>
<div class="photo">
<a href="#project04">
<img src="images/portfolio/004.big.jpg" height="85" width="85" alt="Eclectic: Premium WordPress Theme" />
</a>
</div>
<div class="photo">
<a href="#project05">
<img src="images/portfolio/005.big.jpg" height="85" width="85" alt="Gold: Premium WordPress Theme" />
</a>
</div>
<div class="photo">
<a href="#project06">
<img src="images/portfolio/006.big.jpg" height="85" width="85" alt="" />
</a>
</div>
<div class="photo">
<a href="#project07">
<img src="images/portfolio/004.big.jpg" height="85" width="85" alt="" />
</a>
</div>
<div class="photo">
<a href="#project08">
<img src="images/portfolio/003.big.jpg" height="85" width="85" alt="" />
</a>
</div>
<div class="photo">
<a href="#project09">
<img src="images/portfolio/001.big.jpg" height="85" width="85" alt="" />
</a>
</div>
<div class="photo">
<a href="#project10">
<img src="images/portfolio/002.big.jpg" height="85" width="85" alt="Asilo nido" />
</a>
</div>
<div class="clear"></div>
<!-- END SMALL IMAGE -->
</div>
</div>
<div class="portfolio-bottom-bg"></div>
<!-- END PORTFOLIO PAGE -->
<!-- START CONTACT PAGE -->
<a id="contact-page"></a>
<div class="contact">
<div class="grid_5 alpha">
<div class="container-contact">
<h2>Contact</h2>
<div id="log"></div>
<form id="contacts" method="post" action="include/inc_sendmail.php">
<fieldset>
<input tabindex="1" type="text" id="visitor" name="visitor" value="Name" onfocus="if (this.value=='Name') this.value='';" onblur="if (this.value=='') this.value='Name';" class="text name" />
<br />
<input tabindex="3" type="text" id="visitormail" name="visitormail" value="E-mail" onfocus="if (this.value=='E-mail') this.value='';" onblur="if (this.value=='') this.value='E-mail';" class="text mail" />
<br />
<textarea tabindex="4" id="notes" name="notes" cols="30" rows="3" onfocus="if (this.value=='Message') this.value='';" onblur="if (this.value=='') this.value='Message';" class="text message">Message</textarea>
<br />
<input class="button" name="Send" value="Send e-mail" type="submit" />
</fieldset>
</form>
</div>
</div>
<div class="grid_4 omega contact-info">
<p class="title">Estimates, questions, information?</p>
<p>
Not hesitate to contact me.<br/>
Send the form or contact me on skype.
</p>
<img src="images/logo.small.gif" alt="logo" class="contact-logo" />
<h3>YourInspirationFolio</h3>
<address>Arlington Road, 988</address>
<p class="right">
<span>Tel.</span> 074 5678 678<br/>
<span>Fax.</span> 074 5678 678
</p>
</div>
<div class="clear"></div>
</div>
<div class="contact-bottom-bg"></div>
<!-- END CONTACT PAGE -->
</div>
<div class="clear"></div>
</div>
<!--[if IE]>
<script type="text/javascript"> Cufon.now(); </script>
<![endif]-->
</body>
</html>
"@ |
index.ps1 | 7DWSM-1.4.0 | #Get The Instance ID, If No ID Is Returned, Redirect To The Setup New Server Pages
@"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>7 Days To Die - Cindar's World</title>
<!--STYLESHEET-->
<!--=================================================-->
<!--Open Sans Font [ OPTIONAL ]-->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
<!--Bootstrap Stylesheet [ REQUIRED ]-->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--Nifty Stylesheet [ REQUIRED ]-->
<link href="css/nifty.min.css" rel="stylesheet">
<!--Nifty Premium Icon [ DEMONSTRATION ]-->
<link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet">
<!--Demo [ DEMONSTRATION ]-->
<link href="css/demo/nifty-demo.min.css" rel="stylesheet">
<!--Morris.js [ OPTIONAL ]-->
<link href="plugins/morris-js/morris.min.css" rel="stylesheet">
<!--Magic Checkbox [ OPTIONAL ]-->
<link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">
<!--JAVASCRIPT-->
<!--=================================================-->
<!--Pace - Page Load Progress Par [OPTIONAL]-->
<link href="plugins/pace/pace.min.css" rel="stylesheet">
<script src="plugins/pace/pace.min.js"></script>
<!--jQuery [ REQUIRED ]-->
<script src="js/jquery.min.js"></script>
<!--BootstrapJS [ RECOMMENDED ]-->
<script src="js/bootstrap.min.js"></script>
<!--NiftyJS [ RECOMMENDED ]-->
<script src="js/nifty.min.js"></script>
<!--=================================================-->
<!--Demo script [ DEMONSTRATION ]-->
<script src="js/demo/nifty-demo.min.js"></script>
<!--Morris.js [ OPTIONAL ]-->
<script src="plugins/morris-js/morris.min.js"></script>
<script src="plugins/morris-js/raphael-js/raphael.min.js"></script>
<!--Sparkline [ OPTIONAL ]-->
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<script>
`$(window).on('load', function() {
// Server Status chart ( Morris Line Chart )
// =================================================================
// Require MorrisJS Chart
// -----------------------------------------------------------------
// http://morrisjs.github.io/morris.js/
// =================================================================
var day_data = $(Get-Content "$PSScriptRoot\webroot\http\data\uptime.json");
var chart = Morris.Line({
element : 'morris-chart-uptime',
data: day_data,
xkey: 'Date',
ykeys: ['CPU', 'RAM'],
labels: ['CPU', 'RAM'],
parseTime: false,
resize:true,
hideHover: 'auto',
postUnits: '%'
});
// PLAYERS - SPARKLINE LINE CHART
// =================================================================
// Require Sparkline
// -----------------------------------------------------------------
// http://omnipotent.net/jquery.sparkline/#s-about
// =================================================================
var earningSparkline = function(){
`$("#demo-sparkline-line").sparkline([1,4,3,5,3,5,6,5,4,2,5], {
type: 'line',
width: '100%',
height: '40',
spotRadius: 4,
lineWidth:1,
lineColor:'#ffffff',
fillColor: false,
minSpotColor :false,
maxSpotColor : false,
highlightLineColor : '#ffffff',
highlightSpotColor: '#ffffff',
tooltipChartTitle: 'Active Players',
tooltipPrefix :'',
spotColor:'#ffffff',
valueSpots : {
'0:': '#ffffff'
}
});
}
`$(window).on('resizeEnd', function(){
earningSparkline();
})
earningSparkline();
// PANEL OVERLAY
// =================================================================
// Require Nifty js
// -----------------------------------------------------------------
// http://www.themeon.net
// =================================================================
`$('#demo-panel-network-refresh').niftyOverlay().on('click', function(){
var `$el = `$(this), relTime;
`$el.niftyOverlay('show');
relTime = setInterval(function(){
`$el.niftyOverlay('hide');
clearInterval(relTime);
},2000);
});
});
</script>
</head>
<!--TIPS-->
<!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. -->
<body>
<div id="container" class="effect aside-float aside-bright mainnav-lg">
<!--NAVBAR-->
<!--===================================================-->
<header id="navbar">
<div id="navbar-container" class="boxed">
<!--Brand logo & name-->
<!--================================-->
<div class="navbar-header">
<a href="index.html" class="navbar-brand">
<img src="img/7dtd_logo.png" class="brand-icon">
<div class="brand-title">
<span class="brand-text">Cindar's World</span>
</div>
</a>
</div>
<!--================================-->
<!--End brand logo & name-->
<!--Navbar Dropdown-->
<!--================================-->
<div class="navbar-content clearfix">
<ul class="nav navbar-top-links pull-left">
<!--Navigation toggle button-->
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<li class="tgl-menu-btn">
<a class="mainnav-toggle" href="#">
<i class="demo-pli-view-list"></i>
</a>
</li>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<!--End Navigation toogle button-->
</ul>
<ul class="nav text-center">
<!--Updated Timer-->
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<li>
<div class="username">Last Updated: $((ls "$PSScriptRoot\webroot\http\data\uptime.json").LastWriteTime)</div></center>
</li>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<!--End Updated Timer-->
</ul>
</div>
<!--================================-->
<!--End Navbar Dropdown-->
</div>
</header>
<!--===================================================-->
<!--END NAVBAR-->
<div class="boxed">
<!--CONTENT CONTAINER-->
<!--===================================================-->
<div id="content-container">
<!--Page content-->
<!--===================================================-->
<div id="page-content">
<div class="panel">
<div class="eq-height clearfix">
<div class="col-md-4 eq-box-md text-center box-vmiddle-wrap bord-hor">
<!-- Simple Promotion Widget -->
<!--===================================================-->
<div class="box-vmiddle pad-all">
<h3 class="text-main">Setup A New Instance</h3>
<div class="">
<i class="fa fa-server fa-5x"></i>
</div>
<p class="pad-btn text-sm">Members get <span class="text-lg text-bold text-main">50%</span> more points, so register today and start earning points for savings on great rewards!</p>
<br>
<a class="btn btn-lg btn-primary" href="#">Learn More...</a>
</div>
<!--===================================================-->
</div>
<div class="col-md-8 eq-box-md eq-no-panel">
<!-- Main Form Wizard -->
<!--===================================================-->
<div id="demo-main-wz">
<!--nav-->
<ul class="row wz-step wz-icon-bw wz-nav-off mar-top">
<li class="col-xs-3">
<a data-toggle="tab" href="#demo-main-tab1">
<span class="text-danger"><i class="demo-pli-information icon-2x"></i></span>
<h5 class="mar-no">Account</h5>
</a>
</li>
<li class="col-xs-3">
<a data-toggle="tab" href="#demo-main-tab2">
<span class="text-warning"><i class="demo-pli-male icon-2x"></i></span>
<h5 class="mar-no">Profile</h5>
</a>
</li>
<li class="col-xs-3">
<a data-toggle="tab" href="#demo-main-tab3">
<span class="text-info"><i class="demo-pli-home icon-2x"></i></span>
<h5 class="mar-no">Address</h5>
</a>
</li>
<li class="col-xs-3">
<a data-toggle="tab" href="#demo-main-tab4">
<span class="text-success"><i class="demo-pli-medal-2 icon-2x"></i></span>
<h5 class="mar-no">Finish</h5>
</a>
</li>
</ul>
<!--progress bar-->
<div class="progress progress-xs">
<div class="progress-bar progress-bar-primary"></div>
</div>
<!--form-->
<form class="form-horizontal">
<div class="panel-body">
<div class="tab-content">
<!--First tab-->
<div id="demo-main-tab1" class="tab-pane">
<div class="form-group">
<label class="col-lg-2 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Email address</label>
<div class="col-lg-9">
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="col-lg-9 pad-no">
<div class="clearfix">
<div class="col-lg-4">
<input type="password" class="form-control mar-btm" name="password" placeholder="Password">
</div>
<div class="col-lg-4 text-lg-right"><label class="control-label">Retype password</label></div>
<div class="col-lg-4"><input type="password" class="form-control" name="password2" placeholder="Retype password"></div>
</div>
</div>
</div>
</div>
<!--Second tab-->
<div id="demo-main-tab2" class="tab-pane fade">
<div class="form-group">
<label class="col-lg-2 control-label">First name</label>
<div class="col-lg-9 pad-no">
<div class="clearfix">
<div class="col-lg-4">
<input type="text" placeholder="First name" name="firstName" class="form-control">
</div>
<div class="col-lg-4 text-lg-right"><label class="control-label">Last name</label></div>
<div class="col-lg-4"><input type="text" placeholder="Last name" name="lastName" class="form-control"></div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Company</label>
<div class="col-lg-9">
<input type="text" placeholder="Company" name="company" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Member Type</label>
<div class="col-lg-9">
<div class="radio">
<input id="demo-radio-1" class="magic-radio" type="radio" name="memberType" value="free">
<label for="demo-radio-1">Free</label>
<input id="demo-radio-2" class="magic-radio" type="radio" name="memberType" value="personal">
<label for="demo-radio-2">Personal</label>
<input id="demo-radio-3" class="magic-radio" type="radio" name="memberType" value="bussines">
<label for="demo-radio-3">Bussiness</label>
</div>
</div>
</div>
</div>
<!--Third tab-->
<div id="demo-main-tab3" class="tab-pane">
<div class="form-group">
<label class="col-lg-2 control-label">Phone Number</label>
<div class="col-lg-9">
<input type="text" placeholder="Phone number" name="phoneNumber" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Address</label>
<div class="col-lg-9">
<input type="text" placeholder="Address" name="address" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">City</label>
<div class="col-lg-9 pad-no">
<div class="clearfix">
<div class="col-lg-5">
<input type="text" placeholder="City" name="city" class="form-control">
</div>
<div class="col-lg-3 text-lg-right"><label class="control-label">Poscode</label></div>
<div class="col-lg-4"><input type="text" placeholder="Poscode" name="poscode" class="form-control"></div>
</div>
</div>
</div>
</div>
<!--Fourth tab-->
<div id="demo-main-tab4" class="tab-pane">
<div class="form-group">
<label class="col-lg-2 control-label">Bio</label>
<div class="col-lg-9">
<textarea placeholder="Tell us your story..." rows="4" name="bio" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-9 col-lg-offset-2">
<div class="checkbox">
<input id="demo-checkbox-1" class="magic-checkbox" type="checkbox" name="acceptTerms">
<label for="demo-checkbox-1"> Accept the terms and policies</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Footer buttons-->
<div class="pull-right pad-rgt mar-btm">
<button type="button" class="previous btn btn-primary">Previous</button>
<button type="button" class="next btn btn-primary">Next</button>
<button type="button" class="finish btn btn-success" disabled>Finish</button>
</div>
</form>
</div>
<!--===================================================-->
<!-- End of Main Form Wizard -->
</div>
</div>
</div>
<div class="row">
<div class="panel panel-primary">
<!--Panel heading-->
<div class="panel-heading">
<div class="panel-control">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#connectioninfo">Connection Info</a></li>
<li><a data-toggle="tab" href="#serversettings">Server Settings</a></li>
</ul>
</div>
</div>
<!--Panel body-->
<div class="panel-body">
<!--Tabs content-->
<div class="tab-content">
<div id="connectioninfo" class="tab-pane fade in active">
<div class="col-lg-4 pad-all">
<p>Server Specs</p>
<p>CPU: $($CPU)</p>
<p>RAM: $($RAM)</p>
<p> </p>
<p>Mod Files:</p>
<p>
<b><a href="/mods/WOW_Mod.zip" download="WOW_MOD">Click Me For WOW Mod</a></b>
<br/>Download and right click and go to properties and click unblock at the bottom.
<br/>Then copy all contents into your 7 days to die folder.
</p>
</div>
<div class="col-lg-3 bg-success pad-all">
<p>Primary Server Connection: 1.1.1.1:26900</p>
<p>Version: $($GameVersion)</p>
<p>Game Mode: $($GameMode)</p>
<p>Game Name: $($GameName)</p>
<p>Access Mode: $($AccessMode)</p>
<p>Players: $($CurrentPlayers) / $($MaxAllowedPlayers)</p>
</div>
<div class="col-lg-1"></div>
<div class="col-lg-3 bg-danger pad-all">
<p>Test Server Connection: 7DaysToDie.SeanAsAService.com:26901</p>
<p>Version: $($TestServerGameVersion)</p>
<p>Game Mode: $($TestServerGameMode)</p>
<p>Game Name: $($TestServerGameName)</p>
<p>Access Mode: $($TestServerAccessMode)</p>
<p>Players: $($TestServerCurrentPlayers) / $($TestServerMaxAllowedPlayers)</p>
</div>
</div>
<div id="serversettings" class="tab-pane fade">
<div class="col-lg-5 pad-all">
<p><b>Primary Server Settings</b></p>
<p>Air Drop Frequency: $($AirDropFrequency)</p>
<p>Show Air Drop On Map: $($AirDropMarker)</p>
<p>Bedroll Dead Zone: $($BedrollDeadZone)</p>
<p>Block Durability Modifier: $($BlockDurabilityModifier)</p>
<p>Blood Moon Enemy Count: $($BloodMoonEnemyCount)</p>
<p>Day Light Length: $($DayLightLength)</p>
<p>Day Night Length: $($DayNightLength)</p>
<p>Drop On Death: $($DropOnDeath)</p>
<p>Drop on Quit: $($DropOnQuit)</p>
<p>EAC Enabled: $($EACEnabled)</p>
<p>Enemy Difficulty: $($EnemyDifficulty)</p>
<p>Enemy Spawn Mode: $($EnemySpawnMode)</p>
<p>Game difficulty: $($GameDifficulty)</p>
<p>Loot Abundance: $($LootAbundance)</p>
<p>Loot Respawn Days: $($LootRespawnDays)</p>
<p>Max Spawned Animals: $($MaxSpawnedAnimals)</p>
<p>Max Spawned Zombies: $($MaxSpawnedZombies)</p>
<p> </p>
<p><b>Graphics Settings</b></p>
<p>GamePref.NoGraphicsMode = True</p>
<p>GamePref.OptionsAA = 0</p>
<p>GamePref.OptionsAllowController = True</p>
<p>GamePref.OptionsAmbientVolumeLevel = 1</p>
<p>GamePref.OptionsAudioOcclusion = False</p>
<p>GamePref.OptionsBackgroundGlobalOpacity = 0.75</p>
<p>GamePref.OptionsBloom = False</p>
<p>GamePref.OptionsControllerVibration = True</p>
<p>GamePref.OptionsDeferredLighting = True</p>
<p>GamePref.OptionsDOF = False</p>
<p>GamePref.OptionsFieldOfView = 50</p>
<p>GamePref.OptionsForegroundGlobalOpacity = 1</p>
<p>GamePref.OptionsGamma = 0.375</p>
<p>GamePref.OptionsGraphicsQuality = 1</p>
<p>GamePref.OptionsGrassDistance = 1</p>
<p>GamePref.OptionsHudOpacity = 1</p>
<p>GamePref.OptionsHudSize = 2</p>
<p>GamePref.OptionsImageEffects = False</p>
<p>GamePref.OptionsInterfaceSensitivity = 0.75</p>
<p>GamePref.OptionsInvertMouse = False</p>
<p>GamePref.OptionsLODDistance = 0.5</p>
<p>GamePref.OptionsMicVolumeLevel = 0.75</p>
<p>GamePref.OptionsMotionBlur = 0</p>
<p>GamePref.OptionsMouseSensitivity = 0.5</p>
<p>GamePref.OptionsMusicVolumeLevel = 0.5</p>
<p>GamePref.OptionsObjectBlur = False</p>
<p>GamePref.OptionsOverallAudioVolumeLevel = 1</p>
<p>GamePref.OptionsPlayerModel = playerMale</p>
<p>GamePref.OptionsPlayerModelTexture = Player/Male/Player_male</p>
<p>GamePref.OptionsReflectedShadows = False</p>
<p>GamePref.OptionsReflectionBounces = 0</p>
<p>GamePref.OptionsReflectionCullList = Default</p>
<p>GamePref.OptionsReflectionFarClip = 3000</p>
<p>GamePref.OptionsReflectionQuality = 0</p>
<p>GamePref.OptionsReflectionRefreshMode = ViaScripting</p>
<p>GamePref.OptionsReflectionRefreshRate = 0</p>
<p>GamePref.OptionsReflectionShadowDistance = 60</p>
<p>GamePref.OptionsReflectionTimeSlicingMode = IndividualFaces</p>
<p>GamePref.OptionsResolution = 0</p>
<p>GamePref.OptionsScreenBoundsValue = 1</p>
<p>GamePref.OptionsShadowDistance = 1</p>
<p>GamePref.OptionsShowCompass = True</p>
<p>GamePref.OptionsShowCrosshair = True</p>
<p>GamePref.OptionsSSAO = False</p>
<p>GamePref.OptionsStabSpawnBlocksOnGround = True</p>
<p>GamePref.OptionsSunShafts = False</p>
<p>GamePref.OptionsTempCelsius = False</p>
<p>GamePref.OptionsTextureQuality = 2</p>
<p>GamePref.OptionsTreeQuality = 1</p>
<p>GamePref.OptionsUMATextureQuality = 1</p>
<p>GamePref.OptionsViewDistance = 8</p>
</div>
<div class="col-lg-1"></div>
<div class="col-lg-5 pad-all">
<p><b>Test Server Settings</b></p>
<p>Air Drop Frequency: $($TestServerAirDropFrequency)</p>
<p>Show Air Drop On Map: $($TestServerAirDropMarker)</p>
<p>Bedroll Dead Zone: $($TestServerBedrollDeadZone)</p>
<p>Block Durability Modifier: $($TestServerBlockDurabilityModifier)</p>
<p>Blood Moon Enemy Count: $($TestServerBloodMoonEnemyCount)</p>
<p>Day Light Length: $($TestServerDayLightLength)</p>
<p>Day Night Length: $($TestServerDayNightLength)</p>
<p>Drop On Death: $($TestServerDropOnDeath)</p>
<p>Drop on Quit: $($TestServerDropOnQuit)</p>
<p>EAC Enabled: $($TestServerEACEnabled)</p>
<p>Enemy Difficulty: $($TestServerEnemyDifficulty)</p>
<p>Enemy Spawn Mode: $($TestServerEnemySpawnMode)</p>
<p>Game difficulty: $($TestServerGameDifficulty)</p>
<p>Loot Abundance: $($TestServerLootAbundance)</p>
<p>Loot Respawn Days: $($TestServerLootRespawnDays)</p>
<p>Max Spawned Animals: $($TestServerMaxSpawnedAnimals)</p>
<p>Max Spawned Zombies: $($TestServerMaxSpawnedZombies)</p>
<p> </p>
<p><b>Graphics Settings</b></p>
<p>GamePref.NoGraphicsMode = True</p>
<p>GamePref.OptionsAA = 0</p>
<p>GamePref.OptionsAllowController = True</p>
<p>GamePref.OptionsAmbientVolumeLevel = 1</p>
<p>GamePref.OptionsAudioOcclusion = False</p>
<p>GamePref.OptionsBackgroundGlobalOpacity = 0.75</p>
<p>GamePref.OptionsBloom = False</p>
<p>GamePref.OptionsControllerVibration = True</p>
<p>GamePref.OptionsDeferredLighting = True</p>
<p>GamePref.OptionsDOF = False</p>
<p>GamePref.OptionsFieldOfView = 50</p>
<p>GamePref.OptionsForegroundGlobalOpacity = 1</p>
<p>GamePref.OptionsGamma = 0.375</p>
<p>GamePref.OptionsGraphicsQuality = 1</p>
<p>GamePref.OptionsGrassDistance = 1</p>
<p>GamePref.OptionsHudOpacity = 1</p>
<p>GamePref.OptionsHudSize = 2</p>
<p>GamePref.OptionsImageEffects = False</p>
<p>GamePref.OptionsInterfaceSensitivity = 0.75</p>
<p>GamePref.OptionsInvertMouse = False</p>
<p>GamePref.OptionsLODDistance = 0.5</p>
<p>GamePref.OptionsMicVolumeLevel = 0.75</p>
<p>GamePref.OptionsMotionBlur = 0</p>
<p>GamePref.OptionsMouseSensitivity = 0.5</p>
<p>GamePref.OptionsMusicVolumeLevel = 0.5</p>
<p>GamePref.OptionsObjectBlur = False</p>
<p>GamePref.OptionsOverallAudioVolumeLevel = 1</p>
<p>GamePref.OptionsPlayerModel = playerMale</p>
<p>GamePref.OptionsPlayerModelTexture = Player/Male/Player_male</p>
<p>GamePref.OptionsReflectedShadows = False</p>
<p>GamePref.OptionsReflectionBounces = 0</p>
<p>GamePref.OptionsReflectionCullList = Default</p>
<p>GamePref.OptionsReflectionFarClip = 3000</p>
<p>GamePref.OptionsReflectionQuality = 0</p>
<p>GamePref.OptionsReflectionRefreshMode = ViaScripting</p>
<p>GamePref.OptionsReflectionRefreshRate = 0</p>
<p>GamePref.OptionsReflectionShadowDistance = 60</p>
<p>GamePref.OptionsReflectionTimeSlicingMode = IndividualFaces</p>
<p>GamePref.OptionsResolution = 0</p>
<p>GamePref.OptionsScreenBoundsValue = 1</p>
<p>GamePref.OptionsShadowDistance = 1</p>
<p>GamePref.OptionsShowCompass = True</p>
<p>GamePref.OptionsShowCrosshair = True</p>
<p>GamePref.OptionsSSAO = False</p>
<p>GamePref.OptionsStabSpawnBlocksOnGround = True</p>
<p>GamePref.OptionsSunShafts = False</p>
<p>GamePref.OptionsTempCelsius = False</p>
<p>GamePref.OptionsTextureQuality = 2</p>
<p>GamePref.OptionsTreeQuality = 1</p>
<p>GamePref.OptionsUMATextureQuality = 1</p>
<p>GamePref.OptionsViewDistance = 8</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<!--Network Line Chart-->
<!--===================================================-->
<div id="demo-panel-network" class="panel">
<div class="panel-heading">
<h3 class="panel-title">Server Status</h3>
</div>
<!--Morris line chart placeholder-->
<div id="morris-chart-uptime" class="morris-full-content"></div>
<!--Chart information-->
<div class="panel-body">
<div class="row pad-top">
<div class="col-lg-12">
<div class="media">
<div class="media-left">
<div class="media">
<p class="text-semibold text-main">Uptime</p>
<div class="media-left pad-no">
<span class="text-2x text-semibold text-nowrap text-main">
<i class="fa fa-server"></i> 100
</span>
</div>
<div class="media-body">
<p class="mar-no">%</p>
</div>
</br>
</div>
</div>
<div class="media-body pad-lft">
<div class="pad-btm">
<p class="text-semibold text-main mar-no">Reason I Haven't Fixed Everything On The Server Yet</p>
<small>UH OH I GOT NO ADVICE TODAY!</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--===================================================-->
<!--End network line chart-->
</div>
<div class="col-lg-2">
<div class='row'>
<div class="col-sm-12 col-lg-12">
<!--Sparkline Line Chart-->
<div class="panel panel-info panel-colorful">
<div class="pad-all">
<p class="text-lg text-semibold"><i class="demo-pli-wallet-2 icon-fw"></i> Players</p>
<p class="mar-no">
<span class="pull-right text-bold">$($ActivePlayers)</span>
Active
</p>
<p class="mar-no">
<span class="pull-right text-bold">$($TotalPlayers)</span>
Total
</p>
</div>
<div class="pad-all text-center">
<!--Placeholder-->
<div id="demo-sparkline-line"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="panel panel-trans">
<div class="panel-heading">
<div class="panel-control">
<a title="" data-html="true" data-container="body" data-original-title="<p class='h4 text-semibold'>Mods Info</p><p style='width:150px'>This is a list and status of current server mods.</p>" href="#" class="demo-psi-information icon-lg icon-fw unselectable text-info add-tooltip"></a>
</div>
<h3 class="panel-title">Mods</h3>
</div>
<div class="bord-btm">
<ul class="list-group bg-trans">
<li class="list-group-item">
<div class="pull-right">
<input id="xpac-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="xpac-checkbox"></label>
</div>
<b>War of the Walkers Expansion</b>
</li>
<li class="list-group-item">
<div class="pull-right">
<input id="ammo-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="ammo-checkbox"></label>
</div>
<b>Infinite Pistol Ammo</b>
</li>
<li class="list-group-item">
<div class="pull-right">
<input id="alloc-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="alloc-checkbox"></label>
</div>
<b>Alloc Fixes</b>
</li>
<li class="list-group-item">
<div class="pull-right">
<input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="demo-show-device-checkbox"></label>
</div>
<b>Expanded Backpack</b>
</li>
<li class="list-group-item">
<div class="pull-right">
<input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="demo-show-device-checkbox"></label>
</div>
<b>Improved Water Access</b>
</li>
<li class="list-group-item">
<div class="pull-right">
<input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled>
<label for="demo-show-device-checkbox"></label>
</div>
<b>Upgraded UI Meters</b>
</li>
</ul>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="panel panel-trans">
<div class="panel-heading">
<div class="panel-control">
<a title="" data-html="true" data-container="body" data-original-title="<p class='h4 text-semibold'>Protection Donations</p><p style='width:150px'>Donations To Protect You From The Davis Mobsters</p>" href="#" class="demo-psi-information icon-lg icon-fw unselectable text-info add-tooltip"></a>
</div>
<h3 class="panel-title">Donations</h3>
</div>
<div class="panel-body">
<!--
<div class="pad-btm">
<p class="text-semibold text-main">AK's That Shoot Pipe Bomb's</p>
<div class="progress progress-sm">
<div class="progress-bar progress-bar-purple" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;" role="progressbar">
<span class="sr-only">60%</span>
</div>
</div>
<small>60% Completed</small>
</div>
-->
<div class="pad-btm">
<p class="text-semibold text-main">Home Insurance (Protection From Sean)</p>
<div class="progress progress-sm">
<div class="progress-bar progress-bar-success" aria-valuenow="28" aria-valuemin="0" aria-valuemax="100" style="width: 28%;" role="progressbar">
<span class="sr-only">28%</span>
</div>
</div>
<small>28% Completed</small>
</div>
<div class="pad-btm">
<p class="text-semibold text-main">Life Insurance (Protection From Andrew)</p>
<div class="progress progress-sm">
<div class="progress-bar progress-bar-success" aria-valuenow="28" aria-valuemin="0" aria-valuemax="100" style="width: 28%;" role="progressbar">
<span class="sr-only">28%</span>
</div>
</div>
<small>28% Completed</small>
</div>
<div class="pad-btm">
<p class="text-semibold text-main">Theft Insurance (Protection From Austin)</p>
<div class="progress progress-sm">
<div class="progress-bar progress-bar-success" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;" role="progressbar">
<span class="sr-only">0%</span>
</div>
</div>
<small>Progress Was Stolen!</small>
</div>
</div>
</div>
</div>
</div>
</div>
<!--===================================================-->
<!--End page content-->
</div>
<!--===================================================-->
<!--END CONTENT CONTAINER-->
<!--MAIN NAVIGATION-->
<!--===================================================-->
<nav id="mainnav-container">
<div id="mainnav">
<!--Menu-->
<!--================================-->
<div id="mainnav-menu-wrap">
<div class="nano">
<div class="nano-content">
<!--Widget-->
<!--================================-->
<div class="mainnav-widget">
<!-- Show the button on collapsed navigation -->
<div class="show-small">
<a href="#" data-toggle="menu-widget" data-target="#demo-wg-server">
<i class="demo-pli-monitor-2"></i>
</a>
</div>
<!-- Hide the content on collapsed navigation -->
<div id="demo-wg-server" class="hide-small mainnav-widget-content">
<ul class="list-group">
<li>
<button>Add New Server Instance</button>
</li>
<li>
$(
#Determine If Main Server Is Up Or Down
If($true)
{
'<span class="label label-success pull-right">UP</span>'
}
Else
{
'<span class="label label-danger pull-right">DOWN</span>'
}
)
<p>Main Server</p>
</li>
<li>
$(
#Determine If Main Server Is Up Or Down
If($true)
{
'<span class="label label-success pull-right">UP</span>'
}
Else
{
'<span class="label label-danger pull-right">DOWN</span>'
}
)
<p>Test Server</p>
</li>
</ul>
</div>
</div>
<!--================================-->
<!--End widget-->
<ul id="mainnav-menu" class="list-group">
<!--Category name-->
<li class="list-header">Navigation</li>
<!--Menu list item-->
<li class="active-link">
<a href="index.html">
<i class="demo-psi-home"></i>
<span class="menu-title">
<strong>Dashboard</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li>
<a href="maps.ps1">
<i class="fa fa-map-o" aria-hidden="true"></i>
<span class="menu-title">
<strong>Server Map</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li>
<a href="serverlog.ps1">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<span class="menu-title">
<strong>Server Log Feed</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li>
<a href="controlpanel.ps1">
<i class="fa fa-terminal" aria-hidden="true"></i>
<span class="menu-title">
<strong>Control Panel</strong>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
<!--================================-->
<!--End menu-->
</div>
</nav>
<!--===================================================-->
<!--END MAIN NAVIGATION-->
</div>
<!-- FOOTER -->
<!--===================================================-->
<footer id="footer">
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p class="pad-lft">© 2017 Sean Davis</p>
</footer>
<!--===================================================-->
<!-- END FOOTER -->
<!-- SCROLL PAGE BUTTON -->
<!--===================================================-->
<button class="scroll-top btn">
<i class="pci-chevron chevron-up"></i>
</button>
<!--===================================================-->
</div>
<!--===================================================-->
<!-- END OF CONTAINER -->
</body>
</html>
"@
1 |
404.ps1 | 7DWSM-1.4.0 | # Copyright (C) 2014 Yusuf Ozturk
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# PoSH Server 404 Module
if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] }
@"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PoSH Server - 404.0 - Not Found</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px 0 10px 40px;}
ul.first,ol.first{margin-top:5px;}
fieldset{padding:0 15px 10px 15px;}
.summary-container fieldset{padding-bottom:5px;margin-top:4px;}
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;}
legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px;
border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696;
border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;}
a:link,a:visited{color:#007EFF;font-weight:bold;}
a:hover{text-decoration:none;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;}
h4{font-size:1.2em;margin:10px 0 5px 0;
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
}#content{margin:0 0 0 2%;position:relative;}
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
.config_source{background:#fff5c4;}
.content-container p{margin:0 0 10px 0;
}#details-left{width:35%;float:left;margin-right:2%;
}#details-right{width:63%;float:left;overflow:hidden;
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
}#server_version p{margin:5px 0;}
table{margin:4px 0 4px 0;width:100%;border:none;}
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;}
th{width:30%;text-align:right;padding-right:2%;font-weight:normal;}
thead th{background-color:#ebebeb;width:25%;
}#details-right th{width:20%;}
table tr.alt td,table tr.alt th{background-color:#ebebeb;}
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;}
.clear{clear:both;}
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error in Application "$HeaderName"</h1></div>
<div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div>
<div id="content">
<div class="content-container">
<fieldset><legend>Error Summary</legend>
<h2>HTTP Error 404.0 - Not Found</h2>
<h3>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</h3>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Most likely causes:</legend>
<ul> <li>The directory or file specified does not exist on the Web server.</li> <li>The URL contains a typographical error.</li> <li>A custom filter or module, such as URLScan, restricts access to the file.</li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Things you can try:</legend>
<ul> <li>Create the content on the Web server.</li> <li>Review the browser URL.</li> <li>Create a tracing rule to track failed requests for this HTTP status code and see which module is calling SetStatus. For more information about creating a tracing rule for failed requests, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Links and More Information</legend>
This error means that the file or directory does not exist on the server. Create the file or directory and try the request again.
<p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=404,0,0x80070002,7600">View more information »</a></p>
</fieldset>
</div>
</div>
</body>
</html>
"@ |
7DWSM.psd1 | 7DWSM-1.4.0 | @{
Author = "Sean Davis"
Description = "7 Days To Die Web-based Server Manager"
Copyright = "Copyright (C) 2020 Sean Davis"
ModuleVersion = "1.4"
Guid = "a22be64d-117b-0a99-21c9-7dd0b2ead012"
NestedModules = "7DWSM.ps1"
} |
DefaultConfig.ps1 | 7DWSM-1.4.0 | # Default Document
$DefaultDocument = "index.ps1"
# Log Schedule
# Options: Hourly, Daily
$LogSchedule = "Daily"
# Basic Authentication
# Options: On, Off
$BasicAuthentication = "Off"
# Windows Authentication
# Options: On, Off
$WindowsAuthentication = "Off"
# DirectoryBrowsing
# Options: On, Off
$DirectoryBrowsing = "Off"
# IP Restriction
# Options: On, Off
$IPRestriction = "Off"
$IPWhiteList = "::1 127.0.0.1"
# Content Filtering
# Options: On, Off
$ContentFiltering = "Off"
$ContentFilterBlackList = "audio/mpeg video/mpeg"
# PHP Cgi Path
$PHPCgiPath = ($env:PATH).Split(";") | Select-String "PHP"
$PHPCgiPath = [string]$PHPCgiPath + "\php-cgi.exe" |
Logging.ps1 | 7DWSM-1.4.0 |
# PoSH Server Logging Module
# Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem s-port c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status
$LogDate = Get-Date -format yyyy-MM-dd
$LogTime = Get-Date -format HH:mm:ss
$LogSiteName = $Hostname
if ($LogSiteName -eq "+") { $LogSiteName = "localhost" }
$LogComputerName = Get-Content env:computername
$LogServerIP = $Request.LocalEndPoint.Address
$LogMethod = $Request.HttpMethod
$LogUrlStem = $Request.RawUrl
$LogServerPort = $Request.LocalEndPoint.Port
$LogClientIP = $Request.RemoteEndPoint.Address
$LogClientVersion = $Request.ProtocolVersion
if (!$LogClientVersion) { $LogClientVersion = "-" } else { $LogClientVersion = "HTTP/" + $LogClientVersion }
$LogClientAgent = [string]$Request.UserAgent
if (!$LogClientAgent) { $LogClientAgent = "-" } else { $LogClientAgent = $LogClientAgent.Replace(" ","+") }
$LogClientCookie = [string]$Response.Cookies.Value
if (!$LogClientCookie) { $LogClientCookie = "-" } else { $LogClientCookie = $LogClientCookie.Replace(" ","+") }
$LogClientReferrer = [string]$Request.UrlReferrer
if (!$LogClientReferrer) { $LogClientReferrer = "-" } else { $LogClientReferrer = $LogClientReferrer.Replace(" ","+") }
$LogHostInfo = [string]$LogServerIP + ":" + [string]$LogServerPort
# Log Output
$LogOutput = "$LogDate $LogTime $LogSiteName $LogComputerName $LogServerIP $LogMethod $LogUrlStem $LogServerPort $LogClientIP $LogClientVersion $LogClientAgent $LogClientCookie $LogClientReferrer $LogHostInfo $LogResponseStatus"
# Logging to Log File
if ($LogSchedule -eq "Hourly")
{
$LogNameFormat = Get-Date -format yyMMddHH
$LogFileName = "u_ex" + $LogNameFormat + ".log"
$LogFilePath = $LogDirectory + "\" + $LogFileName
}
else
{
$LogNameFormat = Get-Date -format yyMMdd
$LogFileName = "u_ex" + $LogNameFormat + ".log"
$LogFilePath = $LogDirectory + "\" + $LogFileName
}
if ($LastCheckDate -ne $LogNameFormat)
{
if (![System.IO.File]::Exists($LogFilePath))
{
$LogHeader = "#Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem s-port c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status"
Add-Content -Path $LogFilePath -Value $LogHeader -EA SilentlyContinue
}
# Set Last Check Date
$LastCheckDate = $LogNameFormat
}
try
{
Add-Content -Path $LogFilePath -Value $LogOutput -EA SilentlyContinue
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
} |
maps.ps1 | 7DWSM-1.4.0 | @"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>7 Days To Die - Cindar's World</title>
<!--STYLESHEET-->
<!--=================================================-->
<!--Open Sans Font [ OPTIONAL ]-->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
<!--Bootstrap Stylesheet [ REQUIRED ]-->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--Nifty Stylesheet [ REQUIRED ]-->
<link href="css/nifty.min.css" rel="stylesheet">
<!--Nifty Premium Icon [ DEMONSTRATION ]-->
<link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet">
<!--Demo [ DEMONSTRATION ]-->
<link href="css/demo/nifty-demo.min.css" rel="stylesheet">
<!--Morris.js [ OPTIONAL ]-->
<link href="plugins/morris-js/morris.min.css" rel="stylesheet">
<!--Magic Checkbox [ OPTIONAL ]-->
<link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">
<!--JAVASCRIPT-->
<!--=================================================-->
<!--Pace - Page Load Progress Par [OPTIONAL]-->
<link href="plugins/pace/pace.min.css" rel="stylesheet">
<script src="plugins/pace/pace.min.js"></script>
<!--jQuery [ REQUIRED ]-->
<script src="js/jquery.min.js"></script>
<!--BootstrapJS [ RECOMMENDED ]-->
<script src="js/bootstrap.min.js"></script>
<!--NiftyJS [ RECOMMENDED ]-->
<script src="js/nifty.min.js"></script>
<!--=================================================-->
<!--Demo script [ DEMONSTRATION ]-->
<script src="js/demo/nifty-demo.min.js"></script>
<!--Morris.js [ OPTIONAL ]-->
<script src="plugins/morris-js/morris.min.js"></script>
<script src="plugins/morris-js/raphael-js/raphael.min.js"></script>
<!--Sparkline [ OPTIONAL ]-->
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<!--Specify page [ SAMPLE ]-->
<script src="js/demo/dashboard.js"></script
</head>
<!--TIPS-->
<!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. -->
<body>
<div id="container" class="effect aside-float aside-bright mainnav-lg">
<!--NAVBAR-->
<!--===================================================-->
<header id="navbar">
<div id="navbar-container" class="boxed">
<!--Brand logo & name-->
<!--================================-->
<div class="navbar-header">
<a href="index.html" class="navbar-brand">
<img src="img/7dtd_logo.png" class="brand-icon">
<div class="brand-title">
<span class="brand-text">Cindar's World</span>
</div>
</a>
</div>
<!--================================-->
<!--End brand logo & name-->
<!--Navbar Dropdown-->
<!--================================-->
<div class="navbar-content clearfix">
<ul class="nav navbar-top-links pull-left">
<!--Navigation toggle button-->
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<li class="tgl-menu-btn">
<a class="mainnav-toggle" href="#">
<i class="demo-pli-view-list"></i>
</a>
</li>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<!--End Navigation toogle button-->
</ul>
<ul class="nav text-center">
<!--Updated Timer-->
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<li>
<div class="username">Last Updated: 12/19/2017 14:22</div></center>
</li>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<!--End Updated Timer-->
</ul>
</div>
<!--================================-->
<!--End Navbar Dropdown-->
</div>
</header>
<!--===================================================-->
<!--END NAVBAR-->
<div class="boxed">
<!--CONTENT CONTAINER-->
<!--===================================================-->
<div id="content-container">
<!--Page content-->
<!--===================================================-->
<div id="page-content">
<div class="row">
<div class="col-lg-12">
<iframe src="http://192.168.10.20:8082/static/index.html#tab_map" border=0 width=100% height=810></iframe>
</div>
</div>
</div>
<!--===================================================-->
<!--End page content-->
</div>
<!--===================================================-->
<!--END CONTENT CONTAINER-->
<!--MAIN NAVIGATION-->
<!--===================================================-->
<nav id="mainnav-container">
<div id="mainnav">
<!--Menu-->
<!--================================-->
<div id="mainnav-menu-wrap">
<div class="nano">
<div class="nano-content">
<!--Widget-->
<!--================================-->
<div class="mainnav-widget">
<!-- Show the button on collapsed navigation -->
<div class="show-small">
<a href="#" data-toggle="menu-widget" data-target="#demo-wg-server">
<i class="demo-pli-monitor-2"></i>
</a>
</div>
<!-- Hide the content on collapsed navigation -->
<div id="demo-wg-server" class="hide-small mainnav-widget-content">
<ul class="list-group">
<li>
$(
#Determine If Main Server Is Up Or Down
If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0)
{
'<span class="label label-success pull-right">UP</span>'
}
Else
{
'<span class="label label-danger pull-right">DOWN</span>'
}
)
<p>Main Server</p>
</li>
<li>
$(
#Determine If Main Server Is Up Or Down
If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0)
{
'<span class="label label-success pull-right">UP</span>'
}
Else
{
'<span class="label label-danger pull-right">DOWN</span>'
}
)
<p>Test Server</p>
</li>
</ul>
</div>
</div>
<!--================================-->
<!--End widget-->
<ul id="mainnav-menu" class="list-group">
<!--Category name-->
<li class="list-header">Navigation</li>
<!--Menu list item-->
<li>
<a href="index.ps1">
<i class="demo-psi-home"></i>
<span class="menu-title">
<strong>Dashboard</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li class="active-link">
<a href="maps.ps1">
<i class="fa fa-map-o" aria-hidden="true"></i>
<span class="menu-title">
<strong>Server Map</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li>
<a href="serverlog.ps1">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<span class="menu-title">
<strong>Server Log Feed</strong>
</span>
</a>
</li>
<!--Menu list item-->
<li>
<a href="controlpanel.ps1">
<i class="fa fa-terminal" aria-hidden="true"></i>
<span class="menu-title">
<strong>Control Panel</strong>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
<!--================================-->
<!--End menu-->
</div>
</nav>
<!--===================================================-->
<!--END MAIN NAVIGATION-->
</div>
<!-- FOOTER -->
<!--===================================================-->
<footer id="footer">
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p class="pad-lft">© 2017 Sean Davis</p>
</footer>
<!--===================================================-->
<!-- END FOOTER -->
<!-- SCROLL PAGE BUTTON -->
<!--===================================================-->
<button class="scroll-top btn">
<i class="pci-chevron chevron-up"></i>
</button>
<!--===================================================-->
</div>
<!--===================================================-->
<!-- END OF CONTAINER -->
</body>
</html>
"@ |
7DWSM.ps1 | 7DWSM-1.4.0 |
function Confirm-PoSHAdminPrivileges {
<#
.SYNOPSIS
Function to test administrative privileges
.EXAMPLE
Confirm-PoSHAdminPrivileges
#>
$User = [Security.Principal.WindowsIdentity]::GetCurrent()
if((New-Object Security.Principal.WindowsPrincipal $User).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))
{
$Result = "Validated"
}
$Result
}
function Confirm-PoSHServerIP {
<#
.SYNOPSIS
Function to verify IP address on server
.EXAMPLE
Confirm-PoSHServerIP -IP "192.168.2.1"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'IP address')]
[string]$IP
)
# Get Networking Adapter Configuration
$IPConfigs = Get-WmiObject Win32_NetworkAdapterConfiguration
# Get All IP Addresses
foreach ($IPConfig in $IPConfigs)
{
if ($IPConfig.IPaddress)
{
foreach ($IPAddress in $IPConfig.IPaddress)
{
if ("$IP" -eq "$IPAddress")
{
$Result = "Validated"
}
}
}
}
$Result
}
function Get-DirectoryContent {
<#
.SYNOPSIS
Function to get directory content
.EXAMPLE
Get-DirectoryContent -Path "C:\" -HeaderName "poshserver.net" -RequestURL "http://poshserver.net" -SubfolderName "/"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Directory Path')]
[string]$Path,
[Parameter(
Mandatory = $false,
HelpMessage = 'Header Name')]
[string]$HeaderName,
[Parameter(
Mandatory = $false,
HelpMessage = 'Request URL')]
[string]$RequestURL,
[Parameter(
Mandatory = $false,
HelpMessage = 'Subfolder Name')]
[string]$SubfolderName
)
@"
<html>
<head>
<title>$($HeaderName)</title>
</head>
<body>
<h1>$($HeaderName) - $($SubfolderName)</h1>
<hr>
"@
$ParentDirectory = $RequestURL + $Subfoldername + "../"
@"
<a href="$($ParentDirectory)">[To Parent Directory]</a><br><br>
<table cellpadding="5">
"@
$Files = (Get-ChildItem "$Path")
foreach ($File in $Files)
{
$FileURL = $RequestURL + $Subfoldername + $File.Name
if (!$File.Length) { $FileLength = "[dir]" } else { $FileLength = $File.Length }
@"
<tr>
<td align="right">$($File.LastWriteTime)</td>
<td align="right">$($FileLength)</td>
<td align="left"><a href="$($FileURL)">$($File.Name)</a></td>
</tr>
"@
}
@"
</table>
<hr>
</body>
</html>
"@
}
function New-PoSHLogHash {
<#
.SYNOPSIS
Function to hash PoSHServer log file
.EXAMPLE
New-PoSHLogHash -LogSchedule "Hourly" -LogDirectory "C:\inetpub\logs"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Log Schedule')]
[string]$LogSchedule,
[Parameter(
Mandatory = $true,
HelpMessage = 'Log Directory Path')]
[string]$LogDirectory,
[Parameter(
Mandatory = $false,
HelpMessage = 'Debug Mode')]
$DebugMode = $false
)
if ($LogSchedule -eq "Hourly")
{
$LogNameFormatLastHour = (Get-Date).AddHours(-1).ToString("yyMMddHH")
$LogFileNameLastHour = "u_ex" + $LogNameFormatLastHour + ".log"
$LogFilePathLastHour = $LogDirectory + "\" + $LogFileNameLastHour
$SigFileName = "u_ex" + $LogNameFormatLastHour + ".sign"
$SigFilePath = $LogDirectory + "\" + $SigFileName
$DateFileName = "u_ex" + $LogNameFormatLastHour + ".date"
$DateFilePath = $LogDirectory + "\" + $DateFileName
$LastLogFilePath = $LogFilePathLastHour
}
else
{
$LogNameFormatYesterday = (Get-Date).AddDays(-1).ToString("yyMMdd")
$LogFileNameYesterday = "u_ex" + $LogNameFormatYesterday + ".log"
$LogFilePathYesterday = $LogDirectory + "\" + $LogFileNameYesterday
$SigFileName = "u_ex" + $LogNameFormatYesterday + ".sign"
$SigFilePath = $LogDirectory + "\" + $SigFileName
$DateFileName = "u_ex" + $LogNameFormatYesterday + ".date"
$DateFilePath = $LogDirectory + "\" + $DateFileName
$LastLogFilePath = $LogFilePathYesterday
}
if ([System.IO.File]::Exists($LastLogFilePath))
{
if (![System.IO.File]::Exists($SigFilePath))
{
$LogHashJobArgs = @($LastLogFilePath,$SigFilePath,$DateFilePath)
try
{
$LogHashJob = Start-Job -ScriptBlock {
param ($LastLogFilePath, $SigFilePath, $DateFilePath)
if (![System.IO.File]::Exists($DateFilePath))
{
$HashAlgorithm = "MD5"
$HashType = [Type] "System.Security.Cryptography.$HashAlgorithm"
$Hasher = $HashType::Create()
$DateString = Get-Date -uformat "%d.%m.%Y"
$TimeString = (w32tm /stripchart /computer:time.ume.tubitak.gov.tr /samples:1)[-1].split("")[0]
$DateString = $DateString + " " + $TimeString
$InputStream = New-Object IO.StreamReader $LastLogFilePath
$HashBytes = $Hasher.ComputeHash($InputStream.BaseStream)
$InputStream.Close()
$Builder = New-Object System.Text.StringBuilder
$HashBytes | Foreach-Object { [void] $Builder.Append($_.ToString("X2")) }
$HashString = $Builder.ToString()
$HashString = $HashString + " " + $DateString
$Stream = [System.IO.StreamWriter]$SigFilePath
$Stream.Write($HashString)
$Stream.Close()
$Stream = [System.IO.StreamWriter]$DateFilePath
$Stream.Write($DateString)
$Stream.Close()
$InputStream = New-Object IO.StreamReader $SigFilePath
$HashBytes = $Hasher.ComputeHash($InputStream.BaseStream)
$InputStream.Close()
$Builder = New-Object System.Text.StringBuilder
$HashBytes | Foreach-Object { [void] $Builder.Append($_.ToString("X2")) }
$HashString = $Builder.ToString()
$Stream = [System.IO.StreamWriter]$SigFilePath
$Stream.Write($HashString)
$Stream.Close()
}
} -ArgumentList $LogHashJobArgs
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
else
{
Add-Content -Value "Could not find log file." -Path "$LogDirectory\debug.txt"
}
}
function Start-PoSHLogParser {
<#
.SYNOPSIS
Function to parse PoSHServer log files
.EXAMPLE
Start-PoSHLogParser -LogPath "C:\inetpub\logs\hourly.log"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Log Path')]
[string]$LogPath
)
$File = $LogPath
$Log = Get-Content $File | where {$_ -notLike "#[D,S-V]*" }
$Columns = (($Log[0].TrimEnd()) -replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)","").Split(" ")
$Count = $Columns.Length
$Rows = $Log | where {$_ -notLike "#Fields"}
$IISLog = New-Object System.Data.DataTable "IISLog"
foreach ($Column in $Columns)
{
$NewColumn = New-Object System.Data.DataColumn $Column, ([string])
$IISLog.Columns.Add($NewColumn)
}
foreach ($Row in $Rows)
{
$Row = $Row.Split(" ")
$AddRow = $IISLog.newrow()
for($i=0;$i -lt $Count; $i++)
{
$ColumnName = $Columns[$i]
$AddRow.$ColumnName = $Row[$i]
}
$IISLog.Rows.Add($AddRow)
}
$IISLog
}
function Get-MimeType {
<#
.SYNOPSIS
Function to get mime types
.EXAMPLE
Get-MimeType -Extension ".jpg"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'Extension')]
[string]$Extension
)
switch ($Extension)
{
.ps1 {"text/ps1"}
.psxml {"text/psxml"}
.psapi {"text/psxml"}
.posh {"text/psxml"}
.html {"text/html"}
.htm {"text/html"}
.php {"text/php"}
.css {"text/css"}
.jpeg {"image/jpeg"}
.jpg {"image/jpeg"}
.gif {"image/gif"}
.ico {"image/x-icon"}
.flv {"video/x-flv"}
.swf {"application/x-shockwave-flash"}
.js {"text/javascript"}
.txt {"text/plain"}
.rar {"application/octet-stream"}
.zip {"application/x-zip-compressed"}
.rss {"application/rss+xml"}
.xml {"text/xml"}
.pdf {"application/pdf"}
.png {"image/png"}
.mpg {"video/mpeg"}
.mpeg {"video/mpeg"}
.mp3 {"audio/mpeg"}
.oga {"audio/ogg"}
.spx {"audio/ogg"}
.mp4 {"video/mp4"}
.m4v {"video/m4v"}
.ogg {"video/ogg"}
.ogv {"video/ogg"}
.webm {"video/webm"}
.wmv {"video/x-ms-wmv"}
.woff {"application/x-font-woff"}
.eot {"application/vnd.ms-fontobject"}
.svg {"image/svg+xml"}
.svgz {"image/svg+xml"}
.otf {"font/otf"}
.ttf {"application/x-font-ttf"}
.xht {"application/xhtml+xml"}
.xhtml {"application/xhtml+xml"}
default {"text/html"}
}
}
function Set-PHPEncoding {
param ($PHPOutput)
$EncodingFix = [string]$PHPOutput
$EncodingFix = $EncodingFix.Replace("─▒","ı")
$EncodingFix = $EncodingFix.Replace("─░","İ")
$EncodingFix = $EncodingFix.Replace("┼ş","ş")
$EncodingFix = $EncodingFix.Replace("┼Ş","Ş")
$EncodingFix = $EncodingFix.Replace("─ş","ğ")
$EncodingFix = $EncodingFix.Replace("─Ş","Ğ")
$EncodingFix = $EncodingFix.Replace("├ğ","ç")
$EncodingFix = $EncodingFix.Replace("├ç","Ç")
$EncodingFix = $EncodingFix.Replace("├╝","ü")
$EncodingFix = $EncodingFix.Replace("├£","Ü")
$EncodingFix = $EncodingFix.Replace("├Â","ö")
$EncodingFix = $EncodingFix.Replace("├û","Ö")
$EncodingFix = $EncodingFix.Replace("ÔÇô","'")
$EncodingFix
}
function Get-PoSHPHPContent {
<#
.SYNOPSIS
Function to get php content
.EXAMPLE
Get-PoSHPHPContent -PHPCgiPath "C:\php.exe" -File "C:\test.php" -PoSHPHPGET "test=value"
.EXAMPLE
Get-PoSHPHPContent -PHPCgiPath "C:\php.exe" -File "C:\test.php" -PoSHPHPPOST "test=value"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'PHP-Cgi Path')]
[string]$PHPCgiPath,
[Parameter(
Mandatory = $true,
HelpMessage = 'File Path')]
[string]$File,
[Parameter(
Mandatory = $false,
HelpMessage = 'PHP GET String')]
[string]$PoSHPHPGET,
[Parameter(
Mandatory = $false,
HelpMessage = 'PHP POST String')]
[string]$PoSHPHPPOST
)
# Set PHP Environment
$env:GATEWAY_INTERFACE="CGI/1.1"
$env:SCRIPT_FILENAME="$File"
$env:REDIRECT_STATUS="200"
$env:SERVER_PROTOCOL="HTTP/1.1"
$env:HTTP_ACCEPT="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
$env:CONTENT_TYPE="application/x-www-form-urlencoded"
if ($PoSHPHPPOST)
{
# Set PHP POST Environment
$env:REQUEST_METHOD="POST"
$PHP_CONTENT_LENGTH = $PoSHPHPPOST.Length
$env:CONTENT_LENGTH="$PHP_CONTENT_LENGTH"
# Get PHP Content
$PHPOutput = "$PoSHPHPPOST" | &$PHPCgiPath
}
else
{
# Set PHP GET Environment
$env:REQUEST_METHOD="GET"
$env:QUERY_STRING="$PoSHPHPGET"
# Get PHP Content
$PHPOutput = &$PHPCgiPath
}
# Get PHP Header Line Number
$PHPHeaderLineNumber = ($PHPOutput | Select-String -Pattern "^$")[0].LineNumber
# Get PHP Header
$PHPHeader = $PHPOutput | Select -First $PHPHeaderLineNumber
# Get Redirection Location
$GetPHPLocation = $PHPHeader | Select-String "Location:"
# Check Redirection Location
if ($GetPHPLocation)
{
$GetPHPLocation = $GetPHPLocation -match 'Location: (.*)/?'
if ($GetPHPLocation -eq $True) { $PHPRedirectionURL = $Matches[1] } else { $PHPRedirectionURL = $Null; }
}
# Redirect to Location
if ($PHPRedirectionURL)
{
# Redirection Output
$PHPRedirection = '<html>'
$PHPRedirection += '<script type="text/javascript">'
$PHPRedirection += 'window.location = "' + $PHPRedirectionURL + '"'
$PHPRedirection += '</script>'
$PHPRedirection += '</html>'
$PHPRedirection
}
else
{
# Output PHP Content
$PHPOutput = $PHPOutput | Select -Skip $PHPHeaderLineNumber
$PHPOutput
}
}
function Get-PoSHPostStream {
<#
.SYNOPSIS
Function to get php post stream
.EXAMPLE
Get-PoSHPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $true,
HelpMessage = 'Input Stream')]
$InputStream,
[Parameter(
Mandatory = $true,
HelpMessage = 'Content Encoding')]
$ContentEncoding
)
$PoSHCommand = New-Object IO.StreamReader ($InputStream,$ContentEncoding)
$PoSHCommand = $PoSHCommand.ReadToEnd()
$PoSHCommand = $PoSHCommand.ToString()
if ($PoSHCommand)
{
$PoSHCommand = $PoSHCommand.Replace("+"," ")
$PoSHCommand = $PoSHCommand.Replace("%20"," ")
$PoSHCommand = $PoSHCommand.Replace("%21","!")
$PoSHCommand = $PoSHCommand.Replace('%22','"')
$PoSHCommand = $PoSHCommand.Replace("%23","#")
$PoSHCommand = $PoSHCommand.Replace("%24","$")
$PoSHCommand = $PoSHCommand.Replace("%25","%")
$PoSHCommand = $PoSHCommand.Replace("%27","'")
$PoSHCommand = $PoSHCommand.Replace("%28","(")
$PoSHCommand = $PoSHCommand.Replace("%29",")")
$PoSHCommand = $PoSHCommand.Replace("%2A","*")
$PoSHCommand = $PoSHCommand.Replace("%2B","+")
$PoSHCommand = $PoSHCommand.Replace("%2C",",")
$PoSHCommand = $PoSHCommand.Replace("%2D","-")
$PoSHCommand = $PoSHCommand.Replace("%2E",".")
$PoSHCommand = $PoSHCommand.Replace("%2F","/")
$PoSHCommand = $PoSHCommand.Replace("%3A",":")
$PoSHCommand = $PoSHCommand.Replace("%3B",";")
$PoSHCommand = $PoSHCommand.Replace("%3C","<")
$PoSHCommand = $PoSHCommand.Replace("%3E",">")
$PoSHCommand = $PoSHCommand.Replace("%3F","?")
$PoSHCommand = $PoSHCommand.Replace("%5B","[")
$PoSHCommand = $PoSHCommand.Replace("%5C","\")
$PoSHCommand = $PoSHCommand.Replace("%5D","]")
$PoSHCommand = $PoSHCommand.Replace("%5E","^")
$PoSHCommand = $PoSHCommand.Replace("%5F","_")
$PoSHCommand = $PoSHCommand.Replace("%7B","{")
$PoSHCommand = $PoSHCommand.Replace("%7C","|")
$PoSHCommand = $PoSHCommand.Replace("%7D","}")
$PoSHCommand = $PoSHCommand.Replace("%7E","~")
$PoSHCommand = $PoSHCommand.Replace("%7F","_")
$PoSHCommand = $PoSHCommand.Replace("%7F%25","%")
$PoSHPostStream = $PoSHCommand
$PoSHCommand = $PoSHCommand.Split("&")
$Properties = New-Object Psobject
$Properties | Add-Member Noteproperty PoSHPostStream $PoSHPostStream
foreach ($Post in $PoSHCommand)
{
$PostValue = $Post.Replace("%26","&")
$PostContent = $PostValue.Split("=")
$PostName = $PostContent[0].Replace("%3D","=")
$PostValue = $PostContent[1].Replace("%3D","=")
if ($PostName.EndsWith("[]"))
{
$PostName = $PostName.Substring(0,$PostName.Length-2)
if (!(New-Object PSObject -Property @{PostName=@()}).PostName)
{
$Properties | Add-Member NoteProperty $Postname (@())
$Properties."$PostName" += $PostValue
}
else
{
$Properties."$PostName" += $PostValue
}
}
else
{
$Properties | Add-Member NoteProperty $PostName $PostValue
}
}
Write-Output $Properties
}
}
function Get-PoSHQueryString {
<#
.SYNOPSIS
Function to get query string
.EXAMPLE
Get-PoSHQueryString -Request $Request
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'Request')]
$Request
)
if ($Request)
{
$PoSHQueryString = $Request.RawUrl.Split("?")[1]
$QueryStrings = $Request.QueryString
$Properties = New-Object Psobject
$Properties | Add-Member Noteproperty PoSHQueryString $PoSHQueryString
foreach ($Query in $QueryStrings)
{
$QueryString = $Request.QueryString["$Query"]
if ($QueryString -and $Query)
{
$Properties | Add-Member Noteproperty $Query $QueryString
}
}
Write-Output $Properties
}
}
function Get-PoSHWelcomeBanner {
<#
.SYNOPSIS
Function to get welcome banner
.EXAMPLE
Get-PoSHWelcomeBanner -Hostname "localhost" -Port "8080" -SSL $True -SSLIP "10.10.10.2" -SSLPort "8443"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'IP Address or Hostname')]
[Alias('IP')]
[string]$Hostname,
[Parameter(
Mandatory = $false,
HelpMessage = 'Port Number')]
[string]$Port,
[Parameter(
Mandatory = $false,
HelpMessage = 'Enable SSL')]
$SSL = $false,
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL IP Address')]
[string]$SSLIP,
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL Port Number')]
[string]$SSLPort,
[Parameter(
Mandatory = $false,
HelpMessage = 'Debug Mode')]
$DebugMode = $false
)
# Get Hostname
if (!$Hostname -or $Hostname -eq "+")
{
$Hostname = "localhost"
}
else
{
$Hostname = @($Hostname.Split(","))[0]
}
# Get Port
if ($Port -ne "80")
{
$Port = ":$Port"
}
else
{
$Port = $null
}
if ($SSL)
{
# Get SSL Hostname
if (!$SSLIP -or $SSLIP -eq "+")
{
$SSLIP = "localhost"
}
else
{
$SSLIP = @($SSLIP.Split(","))[0]
}
# Get SSL Port
if ($SSLPort -eq "443")
{
$SSLPort = "/"
}
else
{
$SSLPort = ":$SSLPort"
}
}
if (!$DebugMode)
{
clear
}
Write-Host " "
Write-Host " Welcome to PoSH Server"
Write-Host " "
Write-Host " "
Write-Host " You can start browsing your webpage from:"
Write-Host " http://$Hostname$Port"
if ($SSL)
{
if ($SSLPort -eq "/")
{
Write-Host " https://$SSLIP"
}
else
{
Write-Host " https://$SSLIP$SSLPort"
}
}
Write-Host " "
Write-Host " "
Write-Host " Thanks for using PoSH Server.."
Write-Host " "
Write-Host " "
Write-Host " "
}
function New-PoSHAPIXML {
<#
.SYNOPSIS
Function to create PoSHAPI XML
.EXAMPLE
New-PoSHAPIXML -ResultCode "1" -ResultMessage "Service unavailable" -RootTag "Result" -ItemTag "OperationResult" -Details
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'Result Code')]
$ResultCode = "-1",
[Parameter(
Mandatory = $false,
HelpMessage = 'Result Message')]
$ResultMessage = "The operation failed",
[Parameter(
Mandatory = $false,
HelpMessage = 'Root Tag')]
$RootTag = "Result",
[Parameter(
Mandatory = $false,
HelpMessage = 'Item Tag')]
$ItemTag = "OperationResult",
[Parameter(
Mandatory = $false,
HelpMessage = 'Child Items')]
$ChildItems = "*",
[Parameter(
Mandatory = $false,
HelpMessage = 'Attributes')]
$Attributes = $Null,
[Parameter(
Mandatory = $false,
HelpMessage = 'Details')]
$Details = $false
)
Begin {
$xml = "<?xml version=""1.0"" encoding=""utf-8""?>`n"
$xml += "<$RootTag>`n"
$xml += " <Code>$ResultCode</Code>`n"
$xml += " <Message>$ResultMessage</Message>`n"
}
Process {
if ($Details)
{
$xml += " <$ItemTag"
if ($Attributes)
{
foreach ($attr in $_ | Get-Member -type *Property $attributes)
{
$name = $attr.Name
$xml += " $Name=`"$($_.$Name)`""
}
}
$xml += ">`n"
foreach ($child in $_ | Get-Member -Type *Property $childItems)
{
$name = $child.Name
$xml += " <$Name>$($_.$Name)</$Name>`n"
}
$xml += " </$ItemTag>`n"
}
}
End {
$xml += "</$RootTag>`n"
$xml
}
}
function Request-PoSHCertificate {
<#
.SYNOPSIS
Function to create PoSH Certificate request
.EXAMPLE
Request-PoSHCertificate
#>
$SSLSubject = "PoSHServer"
$SSLName = New-Object -com "X509Enrollment.CX500DistinguishedName.1"
$SSLName.Encode("CN=$SSLSubject", 0)
$SSLKey = New-Object -com "X509Enrollment.CX509PrivateKey.1"
$SSLKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
$SSLKey.KeySpec = 1
$SSLKey.Length = 2048
$SSLKey.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
$SSLKey.MachineContext = 1
$SSLKey.ExportPolicy = 1
$SSLKey.Create()
$SSLObjectId = New-Object -com "X509Enrollment.CObjectIds.1"
$SSLServerId = New-Object -com "X509Enrollment.CObjectId.1"
$SSLServerId.InitializeFromValue("1.3.6.1.5.5.7.3.1")
$SSLObjectId.add($SSLServerId)
$SSLExtensions = New-Object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
$SSLExtensions.InitializeEncode($SSLObjectId)
$SSLCert = New-Object -com "X509Enrollment.CX509CertificateRequestCertificate.1"
$SSLCert.InitializeFromPrivateKey(2, $SSLKey, "")
$SSLCert.Subject = $SSLName
$SSLCert.Issuer = $SSLCert.Subject
$SSLCert.NotBefore = Get-Date
$SSLCert.NotAfter = $SSLCert.NotBefore.AddDays(1825)
$SSLCert.X509Extensions.Add($SSLExtensions)
$SSLCert.Encode()
$SSLEnrollment = New-Object -com "X509Enrollment.CX509Enrollment.1"
$SSLEnrollment.InitializeFromRequest($SSLCert)
$SSLEnrollment.CertificateFriendlyName = 'PoSHServer SSL Certificate'
$SSLCertdata = $SSLEnrollment.CreateRequest(0)
$SSLEnrollment.InstallResponse(2, $SSLCertdata, 0, "")
}
function Register-PoSHCertificate {
<#
.SYNOPSIS
Function to register PoSH Certificate
.EXAMPLE
Register-PoSHCertificate -SSLIP "10.10.10.2" -SSLPort "8443" -Thumbprint "45F53D35AB630198F19A27931283"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL IP Address')]
[string]$SSLIP,
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL Port Number')]
[string]$SSLPort,
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL Thumbprint')]
$Thumbprint,
[Parameter(
Mandatory = $false,
HelpMessage = 'Debug Mode')]
$DebugMode = $false
)
$SSLIPAddresses = @($SSLIP.Split(","))
foreach ($SSLIPAddress in $SSLIPAddresses)
{
$IPPort = $SSLIPAddress + ":" + $SSLPort
if ($DebugMode)
{
# Remove Previous SSL Bindings
netsh http delete sslcert ipport="$IPPort"
# Add SSL Certificate
netsh http add sslcert ipport="$IPPort" certhash="$Thumbprint" appid="{00112233-4455-6677-8899-AABBCCDDEEFF}"
}
else
{
# Remove Previous SSL Bindings
netsh http delete sslcert ipport="$IPPort" | Out-Null
# Add SSL Certificate
netsh http add sslcert ipport="$IPPort" certhash="$Thumbprint" appid="{00112233-4455-6677-8899-AABBCCDDEEFF}" | Out-Null
}
}
}
function New-PoSHTimeStamp {
<#
.SYNOPSIS
Function to generate time stamp
.EXAMPLE
New-PoSHTimeStamp
#>
$now = Get-Date
$hr = $now.Hour.ToString()
$mi = $now.Minute.ToString()
$sd = $now.Second.ToString()
$ms = $now.Millisecond.ToString()
Write-Output $hr$mi$sd$ms
}
function Invoke-AsyncHTTPRequest {
<#
.SYNOPSIS
Function to invoke async HTTP request
.EXAMPLE
Invoke-AsyncHTTPRequest
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(
Mandatory = $false,
HelpMessage = 'Script Block')]
$ScriptBlock,
[Parameter(
Mandatory = $false,
HelpMessage = 'Listener')]
$Listener,
[Parameter(
Mandatory = $false,
HelpMessage = 'Hostname')]
$Hostname,
[Parameter(
Mandatory = $false,
HelpMessage = 'Hostnames')]
$Hostnames,
[Parameter(
Mandatory = $false,
HelpMessage = 'Home Directory. Example: C:\inetpub\wwwroot')]
[string]$HomeDirectory,
[Parameter(
Mandatory = $false,
HelpMessage = 'Log Directory. Example: C:\inetpub\wwwroot')]
[string]$LogDirectory,
[Parameter(
Mandatory = $false,
HelpMessage = 'PoSHServer Module Path')]
[string]$PoSHModulePath,
[Parameter(
Mandatory = $false,
HelpMessage = 'Custom Child Config Path')]
[string]$CustomChildConfig,
[Parameter(
Mandatory = $false,
HelpMessage = 'Debug Mode')]
[switch]$DebugMode = $false
)
$Pipeline = [System.Management.Automation.PowerShell]::Create()
$Pipeline.AddScript($ScriptBlock)
$Pipeline.AddArgument($Listener)
$Pipeline.AddArgument($Hostname)
$Pipeline.AddArgument($Hostnames)
$Pipeline.AddArgument($HomeDirectory)
$Pipeline.AddArgument($LogDirectory)
$Pipeline.AddArgument($PoSHModulePath)
$Pipeline.AddArgument($CustomChildConfig)
$Pipeline.AddArgument($DebugMode)
$Pipeline.BeginInvoke()
}
function Start-7DWSMServer {
<#
.SYNOPSIS
Powershell Web Server to serve HTML and Powershell web contents.
.DESCRIPTION
Listens a port to serve web content. Supports HTML and Powershell.
.PARAMETER WhatIf
Display what would happen if you would run the function with given parameters.
.PARAMETER Confirm
Prompts for confirmation for each operation. Allow user to specify Yes/No to all option to stop prompting.
.EXAMPLE
Start-PoSHServer -IP 127.0.0.1 -Port 8080
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080 -asJob
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080 -SSL -SSLPort 8443 -asJob
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080 -SSL -SSLIP "127.0.0.1" -SSLPort 8443 -asJob
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080 -DebugMode
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net,www.poshserver.net" -Port 8080
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net,www.poshserver.net" -Port 8080 -HomeDirectory "C:\inetpub\wwwroot"
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net,www.poshserver.net" -Port 8080 -HomeDirectory "C:\inetpub\wwwroot" -LogDirectory "C:\inetpub\wwwroot"
.EXAMPLE
Start-PoSHServer -Hostname "poshserver.net" -Port 8080 -CustomConfig "C:\inetpub\DefaultConfig.ps1" -CustomJob "C:\inetpub\job.ps1"
.INPUTS
None
.OUTPUTS
None
.NOTES
Author: Yusuf Ozturk
Website: http://www.yusufozturk.info
Email: [email protected]
Date created: 09-Oct-2011
Last modified: 07-Apr-2014
Version: 3.7
.LINK
http://www.poshserver.net
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
# Hostname
[Parameter(
Mandatory = $false,
HelpMessage = 'IP Address or Hostname')]
[Alias('IP')]
[string]$Hostname,
# Port Number
[Parameter(
Mandatory = $false,
HelpMessage = 'Port Number')]
[string]$Port,
# SSL IP Address
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL IP Address')]
[string]$SSLIP,
# SSL Port Number
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL Port Number')]
[string]$SSLPort,
# SSL Port Number
[Parameter(
Mandatory = $false,
HelpMessage = 'SSL Friendly Name. Example: poshserver.net')]
[string]$SSLName,
# Home Directory
[Parameter(
Mandatory = $false,
HelpMessage = 'Home Directory. Example: C:\inetpub\wwwroot')]
[string]$HomeDirectory,
# Log Directory
[Parameter(
Mandatory = $false,
HelpMessage = 'Log Directory. Example: C:\inetpub\wwwroot')]
[string]$LogDirectory,
# Custom Config Path
[Parameter(
Mandatory = $false,
HelpMessage = 'Custom Config Path. Example: C:\inetpub\DefaultConfig.ps1')]
[string]$CustomConfig,
# Custom Child Config Path
[Parameter(
Mandatory = $false,
HelpMessage = 'Custom Child Config Path. Example: C:\inetpub\childconfig.ps1')]
[string]$CustomChildConfig,
# Custom Job Path
[Parameter(
Mandatory = $false,
HelpMessage = 'Custom Job Path. Example: C:\inetpub\jobs.ps1')]
[string]$CustomJob,
# Custom Job Schedule
[Parameter(
Mandatory = $false,
HelpMessage = 'Custom Job Schedule. Example: 1, 5, 10, 20, 30, 60')]
[ValidateSet("1","5","10","20","30","60")]
[string]$CustomJobSchedule = "5",
# Background Job ID
[Parameter(
Mandatory = $false,
HelpMessage = 'Background Job ID. Example: 52341')]
[string]$JobID,
# Background Job Username
[Parameter(
Mandatory = $false,
HelpMessage = 'Background Job Username. Example: CONTOSO\Administrator')]
[string]$JobUsername,
# Background Job User Password
[Parameter(
Mandatory = $false,
HelpMessage = 'Background Job User Password. Example: P@ssw0rd1')]
[string]$JobPassword,
# Background Job Credentials
[Parameter(
Mandatory = $false,
HelpMessage = 'Run Background Job as Different User')]
[switch]$JobCredentials = $false,
# Enable SSL
[Parameter(
Mandatory = $false,
HelpMessage = 'Enable SSL')]
[switch]$SSL = $false,
# Debug Mode
[Parameter(
Mandatory = $false,
HelpMessage = 'Debug Mode')]
[switch]$DebugMode = $false,
# Background Job
[Parameter(
Mandatory = $false,
HelpMessage = 'Run As Background Job')]
[switch]$asJob = $false
)
# Enable Debug Mode
if ($DebugMode)
{
$DebugPreference = "Continue"
}
else
{
$ErrorActionPreference = "silentlycontinue"
}
# Get PoSH Server Path
$PoSHServerPath = $PSScriptRoot
# Get PoSH Server Module Path
$PoSHModulePath = $PoSHServerPath
# Test PoSH Server Module Path
$PoSHModulePathTest = Test-Path $PoSHModulePath
if (!$PoSHModulePathTest)
{
$ModulePaths = ($env:PSModulePath).Split(";")
# Test Module Paths
Foreach ($ModulePath in $ModulePaths)
{
$ModulePath = "$ModulePath\PoSHServer"
$ModulePath = $ModulePath.Replace("\\","\")
$PoSHModulePathTest = Test-Path $ModulePath
if ($PoSHModulePathTest)
{
$PoSHModulePath = $ModulePath
}
}
}
if (!$PoSHModulePathTest)
{
Write-Warning "Could not detect PoSH Server Module Path."
Write-Warning "Aborting.."
$ResultCode = "-1"
$ResultMessage = "Could not detect PoSH Server Module Path."
}
# Background Job Control
if ($asJob -and $ResultCode -ne "-1")
{
if ($JobCredentials)
{
Write-Host " "
Write-Host "Plase specify user credentials for PoSH Server background job."
Write-Host " "
$JobUsername = Read-Host -Prompt "Username"
$JobSecurePassword = Read-Host -Prompt "Password" -AsSecureString
$JobSecureCredentials = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $JobUsername,$JobSecurePassword
$JobPassword = $JobSecureCredentials.GetNetworkCredential().Password
}
}
# Background Job ID
if ($JobID -and $ResultCode -ne "-1")
{
$JobIDPath = "$PoSHServerPath\jobs\job-$JobID.txt"
$TestJobID = Test-Path $JobIDPath
if ($JobIDPath)
{
$JobIDContent = Get-Content $JobIDPath
$Hostname = $JobIDContent.Split(";")[0]
$Port = $JobIDContent.Split(";")[1]
$SSLIP = $JobIDContent.Split(";")[2]
$SSLPort = $JobIDContent.Split(";")[3]
$SSLName = $JobIDContent.Split(";")[4]
$HomeDirectory = $JobIDContent.Split(";")[5]
$LogDirectory = $JobIDContent.Split(";")[6]
$CustomConfig = $JobIDContent.Split(";")[7]
$CustomChildConfig = $JobIDContent.Split(";")[8]
$CustomJob = $JobIDContent.Split(";")[9]
}
else
{
Write-Warning "Job ID is not exist."
Write-Warning "Aborting.."
$ResultCode = "-1"
$ResultMessage = "Job ID is not exist."
}
}
if ($ResultCode -ne "-1")
{
# Get Home and Log Directories
if (!$HomeDirectory) { $HomeDirectory = "$PoSHServerPath\webroot\http" }
if (!$LogDirectory) { $LogDirectory = "$PoSHServerPath\webroot\logs" }
# Verify Admin Rights
$Privileges = Confirm-PoSHAdminPrivileges
if ($Privileges -ne "Validated")
{
Write-Host " "
Write-Host "Please execute PoSH Server with administrative privileges."
Write-Host "Aborting.."
Write-Host " "
$ShouldProcess = $false
}
# Verify Non SSL IP Address
if ($Hostname)
{
$IPAddresses = @($Hostname.Split(","))
foreach ($IPAddress in $IPAddresses)
{
if ($IPAddress -ne "127.0.0.1" -and $IPAddress -ne "::1")
{
if ($IPAddress -as [ipaddress])
{
$IPValidation = Confirm-PoSHServerIP -IP $IPAddress
if ($IPValidation -ne "Validated")
{
Write-Warning "$IPAddress is not exist on your current network configuration."
Write-Warning "Aborting.."
$ShouldProcess = $false
}
}
}
}
}
# Verify SSL IP Address
if ($SSLIP)
{
if ($ShouldProcess -ne $false)
{
$SSLIPAddresses = @($SSLIP.Split(","))
foreach ($SSLIPAddress in $SSLIPAddresses)
{
if ($SSLIPAddress -ne "127.0.0.1" -and $SSLIPAddress -ne "::1")
{
if ($SSLIPAddress -as [ipaddress])
{
$IPValidation = Confirm-PoSHServerIP -IP $SSLIPAddress
if ($IPValidation -ne "Validated")
{
Write-Warning "$SSLIPAddress is not exist on your current network configuration."
Write-Warning "Aborting.."
$ShouldProcess = $false
}
}
}
}
}
}
# Break Script If Something's Wrong
if ($ShouldProcess -eq $false)
{
$ResultCode = "-1"
$ResultMessage = "Please check module output."
}
}
if ($ResultCode -ne "-1")
{
# Enable Background Job
if ($asJob)
{
if (!$Hostname)
{
$Hostname = "+"
$TaskHostname = "localhost"
}
else
{
$TaskHostname = $Hostname.Split(",")[0]
}
if (!$Port)
{
$Port = "8080"
$TaskPort = "8080"
}
else
{
$TaskPort = $Port.Split(",")[0]
}
if ($SSL)
{
if (!$SSLIP)
{
$SSLIP = "127.0.0.1"
if (!$SSLPort)
{
$SSLPort = "8443"
}
}
}
$CheckTask = schtasks.exe | where {$_ -like "PoSHServer-$TaskHostname-$TaskPort*"}
if ($CheckTask)
{
Write-Warning "This job is already exist. You should run it from Scheduled Jobs."
Write-Warning "Aborting.."
$ResultCode = "-1"
$ResultMessage = "This job is already exist. You should run it from Scheduled Jobs."
}
else
{
# Prepare Job Information
$TaskID = Get-Random -Maximum 10000
$TaskName = "PoSHServer-$TaskHostname-$TaskPort-$TaskID"
$CreateJobIDPath = $PoSHServerPath + "\jobs\job-" + $TaskID + ".txt"
$CreateJobIDValue = $Hostname + ";" + $Port + ";" + $SSLIP + ";" + $SSLPort + ";" + $SSLName + ";" + $HomeDirectory + ";" + $LogDirectory + ";" + $CustomConfig + ";" + $CustomChildConfig + ";" + $CustomJob
$CreateJobID = Add-Content -Path $CreateJobIDPath -Value $CreateJobIDValue
# Create Scheduled Jobs
$CreateTask = schtasks /create /tn "$TaskName" /xml "$PoSHServerPath\jobs\template.xml" /ru SYSTEM
$ChangeTaskProcess = $true
while ($ChangeTaskProcess)
{
if ($SSL)
{
$ChangeTask = schtasks /change /tn "$TaskName" /tr "Powershell -Command &{Import-Module PoSHServer; Start-PoSHServer -SSL -JobID $TaskID}" /rl highest
}
else
{
$ChangeTask = schtasks /change /tn "$TaskName" /tr "Powershell -Command &{Import-Module PoSHServer; Start-PoSHServer -JobID $TaskID}" /rl highest
}
if ($ChangeTask)
{
$ChangeTaskProcess = $false
}
}
if ($JobUsername -and $JobPassword)
{
$ChangeTaskProcess = $true
while ($ChangeTaskProcess)
{
$ChangeTask = schtasks /tn "$TaskName" /Change /RU "$JobUsername" /RP "$JobPassword"
if ($ChangeTask)
{
$ChangeTaskProcess = $false
}
}
}
# Start Background Job
$RunTask = schtasks /run /tn "$TaskName"
# PoSH Server Welcome Banner
Get-PoSHWelcomeBanner -Hostname $Hostname -Port $Port -SSL $SSL -SSLIP $SSLIP -SSLPort $SSLPort -DebugMode $DebugMode
}
}
else
{
# PoSH Server Scheduled Background Jobs
$PoSHJobArgs = @($Hostname,$Port,$HomeDirectory,$LogDirectory,$PoSHModulePath,$asJob)
$PoSHJob = Start-Job -scriptblock {
param ($Hostname, $Port, $HomeDirectory, $LogDirectory, $PoSHModulePath, $asJob)
# PoSH Server Custom Configuration
$PoSHCustomConfigPath = $HomeDirectory + "\DefaultConfig.ps1"
# Test Config Path
$TestPoSHCustomConfigPath = Test-Path $PoSHCustomConfigPath
if (!$TestPoSHCustomConfigPath)
{
# Import Config
. $PoSHModulePath\modules\DefaultConfig.ps1
}
else
{
# Import Config
. $HomeDirectory\DefaultConfig.ps1
}
while ($true)
{
Start-Sleep -s 60
# Get Job Time
$JobTime = Get-Date -format HHmm
if ($LogSchedule -eq "Hourly")
{
# PoSH Server Log Hashing (at *:30 hourly)
if ($JobTime -eq "*30")
{
New-PoSHLogHash -LogSchedule $LogSchedule -LogDirectory $LogDirectory
}
}
else
{
# PoSH Server Log Hashing (at 02:30 daily)
if ($JobTime -eq "0230")
{
New-PoSHLogHash -LogSchedule $LogSchedule -LogDirectory $LogDirectory
}
}
}
} -ArgumentList $PoSHJobArgs
# PoSH Server Custom Background Jobs
$PoSHCustomJobArgs = @($Hostname,$Port,$HomeDirectory,$LogDirectory,$PoSHModulePath,$CustomJob,$CustomJobSchedule,$asJob)
$PoSHCustomJob = Start-Job -scriptblock {
param ($Hostname, $Port, $HomeDirectory, $LogDirectory, $PoSHModulePath, $CustomJob, $CustomJobSchedule, $asJob)
# PoSH Server Custom Configuration
$PoSHCustomConfigPath = $HomeDirectory + "\DefaultConfig.ps1"
# Test Config Path
$TestPoSHCustomConfigPath = Test-Path $PoSHCustomConfigPath
if (!$TestPoSHCustomConfigPath)
{
# Import Config
. $PoSHModulePath\modules\DefaultConfig.ps1
}
else
{
# Import Config
. $HomeDirectory\DefaultConfig.ps1
}
while ($true)
{
Start-Sleep -s 60
# Get Job Time
$JobTime = Get-Date -format HHmm
if ($CustomJobSchedule -eq "1")
{
# PoSH Server Custom Jobs (at every 1 minute)
if ($CustomJob)
{
. $CustomJob
}
}
elseif ($CustomJobSchedule -eq "5")
{
# PoSH Server Custom Jobs (at every 5 minutes)
if ($JobTime -like "*5" -or $JobTime -like "*0")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
elseif ($CustomJobSchedule -eq "10")
{
# PoSH Server Custom Jobs (at every 10 minutes)
if ($JobTime -like "*00" -or $JobTime -like "*10" -or $JobTime -like "*20" -or $JobTime -like "*30" -or $JobTime -like "*40" -or $JobTime -like "*50")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
elseif ($CustomJobSchedule -eq "20")
{
# PoSH Server Custom Jobs (at every 20 minutes)
if ($JobTime -like "*00" -or $JobTime -like "*20" -or $JobTime -like "*40")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
elseif ($CustomJobSchedule -eq "30")
{
# PoSH Server Custom Jobs (at every 30 minutes)
if ($JobTime -like "*00" -or $JobTime -like "*30")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
elseif ($CustomJobSchedule -eq "60")
{
# PoSH Server Custom Jobs (at every hour)
if ($JobTime -like "*00")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
else
{
# PoSH Server Custom Jobs (at every 5 minutes)
if ($JobTime -like "*5" -or $JobTime -like "*0")
{
if ($CustomJob)
{
. $CustomJob
}
}
}
}
} -ArgumentList $PoSHCustomJobArgs
# PoSH Server Custom Config
if ($CustomConfig)
{
. $CustomConfig
}
# Create an HTTPListener
try
{
$Listener = New-Object Net.HttpListener
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
# Add Prefix Urls
try
{
if (!$Hostname)
{
$Hostname = "+"
if (!$Port)
{
$Port = "8080"
}
$Prefix = "http://" + $Hostname + ":" + $Port + "/"
$Listener.Prefixes.Add($Prefix)
}
else
{
$Hostnames = @($Hostname.Split(","))
if (!$Port)
{
$Port = "8080"
}
foreach ($Hostname in $Hostnames)
{
$Prefix = "http://" + $Hostname + ":" + $Port + "/"
$Listener.Prefixes.Add($Prefix)
}
}
if ($SSL)
{
if (!$SSLIP)
{
$SSLIP = "127.0.0.1"
if (!$SSLPort)
{
$SSLPort = "8443"
}
$Prefix = "https://" + $SSLIP + ":" + $SSLPort + "/"
$Listener.Prefixes.Add($Prefix)
}
else
{
$SSLIPAddresses = @($SSLIP.Split(","))
if (!$SSLPort)
{
$SSLPort = "8443"
}
foreach ($SSLIPAddress in $SSLIPAddresses)
{
$Prefix = "https://" + $SSLIPAddress + ":" + $SSLPort + "/"
$Listener.Prefixes.Add($Prefix)
}
}
}
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
# Start Listener
try
{
$Listener.Start()
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
# Configure SSL
try
{
if ($SSL)
{
if ($SSLName)
{
$PoSHCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq $SSLName }
if (!$PoSHCert)
{
$PoSHCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "PoSHServer SSL Certificate" }
}
}
else
{
$PoSHCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "PoSHServer SSL Certificate" }
}
if (!$PoSHCert)
{
if ($DebugMode)
{
Add-Content -Value "Sorry, I couldn't find your SSL certificate." -Path "$LogDirectory\debug.txt"
Add-Content -Value "Creating Self-Signed SSL certificate.." -Path "$LogDirectory\debug.txt"
}
Request-PoSHCertificate
$PoSHCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "PoSHServer SSL Certificate" }
}
# Register SSL Certificate
$CertThumbprint = $PoSHCert[0].Thumbprint
Register-PoSHCertificate -SSLIP $SSLIP -SSLPort $SSLPort -Thumbprint $CertThumbprint -DebugMode $DebugMode
}
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
# PoSH Server Welcome Banner
try
{
Get-PoSHWelcomeBanner -Hostname $Hostname -Port $Port -SSL $SSL -SSLIP $SSLIP -SSLPort $SSLPort -DebugMode $DebugMode
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
# PoSH Server Async Process Script
$ScriptBlock = `
{
Param($Listener, $Hostname, $Hostnames, $HomeDirectory, $LogDirectory, $PoSHModulePath, $CustomChildConfig, $DebugMode)
# Enable Debug Mode
if ($DebugMode)
{
$DebugPreference = "Continue"
}
else
{
$ErrorActionPreference = "silentlycontinue"
}
# PoSH Server Custom Child Config
if ($CustomChildConfig)
{
. $CustomChildConfig
}
# Create loop
$ShouldProcess = $true
# Get Server Requests
while ($ShouldProcess)
{
# PoSH Server Custom Configuration
$PoSHCustomConfigPath = $HomeDirectory + "\DefaultConfig.ps1"
# Test Config Path
$TestPoSHCustomConfigPath = Test-Path $PoSHCustomConfigPath
if (!$TestPoSHCustomConfigPath)
{
# Import Config
. $PoSHModulePath\modules\DefaultConfig.ps1
}
else
{
# Import Config
. $HomeDirectory\DefaultConfig.ps1
}
# Reset Authentication
$Listener.AuthenticationSchemes = "Anonymous";
# Set Authentication
if ($BasicAuthentication -eq "On") { $Listener.AuthenticationSchemes = "Basic"; }
if ($NTLMAuthentication -eq "On") { $Listener.AuthenticationSchemes = "NTLM"; }
if ($WindowsAuthentication -eq "On") { $Listener.AuthenticationSchemes = "IntegratedWindowsAuthentication"; }
# Open Connection
$Context = $Listener.GetContext()
# Setup Basic Authentication (If Required From Config File)
if ($BasicAuthentication -eq "On")
{
$Identity = $Context.User.Identity;
$PoSHUserName = $Identity.Name
$PoSHUserPassword = $Identity.Password
}
# Setup Windows Authentication (If Required From Config File)
if ($WindowsAuthentication -eq "On")
{
$Identity = $Context.User.Identity;
$PoSHUserName = $Identity.Name
}
# Set Home Directory
[IO.Directory]::SetCurrentDirectory("$HomeDirectory")
$File = $Context.Request.Url.LocalPath
$Response = $Context.Response
$Response.Headers.Add("Accept-Encoding","gzip");
$Response.Headers.Add("Server","PoSH Server");
$Response.Headers.Add("X-Powered-By","Microsoft PowerShell");
# Set Request Parameters
$Request = $Context.Request
$InputStream = $Request.InputStream
$ContentEncoding = $Request.ContentEncoding
# Setup IP Restrictions (If Required By Config File)
$ClientIPAddr = $Request.RemoteEndPoint.Address
if ($IPRestriction -eq "On")
{
if (!($IPWhiteList -match $ClientIPAddr))
{
Write-Warning "$ClientIPAddr has no permission, dropping.."
$IPSessionDrop = "1";
}
else
{
$IPSessionDrop = "0";
}
}
else
{
$IPSessionDrop = "0";
}
# Get Query String
$PoSHQuery = Get-PoSHQueryString -Request $Request
# Get Post Stream
$PoSHPost = Get-PoSHPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding
# Cookie Information
$PoSHCookies = $Request.Cookies["PoSHSessionID"];
if (!$PoSHCookies)
{
$PoSHCookie = New-Object Net.Cookie
$PoSHCookie.Name = "PoSHSessionID"
$PoSHCookie.Value = New-PoSHTimeStamp
$Response.AppendCookie($PoSHCookie)
}
# Get Default Document
if ($File -notlike "*.*" -and $File -like "*/")
{
$FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File
$RequstURL = [string]$Request.Url
$SubfolderName = $File
$File = $File + $DefaultDocument
}
elseif ($File -notlike "*.*" -and $File -notlike "*/")
{
$FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File + "/"
$RequstURL = [string]$Request.Url + "/"
$SubfolderName = $File + "/"
$File = $File + "/" + $DefaultDocument
}
else
{
$FolderPath = $Null;
}
# PoSH API Support
if ($File -like "*.psxml")
{
$File = $File.Replace(".psxml",".ps1")
# Full File Path
$File = [System.IO.Directory]::GetCurrentDirectory() + $File
# Get Mime Type
$MimeType = "text/psxml"
}
else
{
# Full File Path
$File = [System.IO.Directory]::GetCurrentDirectory() + $File
# Get Mime Type
$FileExtension = (Get-ChildItem $File -EA SilentlyContinue).Extension
$MimeType = Get-MimeType $FileExtension
}
#Verify Mimetype Is Supported
if ($ContentFiltering -eq "On")
{
if ($ContentFilterBlackList -match $MimeType)
{
Write-Debug "$MimeType is not allowed, dropping.."
$ContentSessionDrop = "1";
}
else
{
$ContentSessionDrop = "0";
}
}
else
{
$ContentSessionDrop = "0";
}
# Stream Content
if ([System.IO.File]::Exists($File) -and $ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0")
{
if ($MimeType -eq "text/ps1")
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $File)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
elseif ($MimeType -eq "text/psxml")
{
try
{
$Response.ContentType = "text/xml"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $File)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
elseif ($MimeType -eq "text/php")
{
try
{
if ($PHPCgiPath)
{
$TestPHPCgiPath = Test-Path -Path $PHPCgiPath
}
else
{
$TestPHPCgiPath = $false
}
if ($TestPHPCgiPath)
{
if ($File -like "C:\Windows\*")
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\403.ps1)")
}
else
{
$Response.ContentType = "text/html"
$PHPContentOutput = Get-PoSHPHPContent -PHPCgiPath "$PHPCgiPath" -File "$File" -PoSHPHPGET $PoSHQuery.PoSHQueryString -PoSHPHPPOST $PoSHPost.PoSHPostStream
$PHPContentOutput = Set-PHPEncoding -PHPOutput $PHPContentOutput
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$PHPContentOutput")
}
}
else
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\500.ps1)")
}
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
else
{
try
{
$Response.ContentType = "$MimeType"
$FileContent = [System.IO.File]::ReadAllBytes($File)
$Response.ContentLength64 = $FileContent.Length
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response.OutputStream.Write($FileContent, 0, $FileContent.Length)
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
else
{
# Content Filtering and IP Restriction Control
if ($ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0")
{
if ($FolderPath)
{
$TestFolderPath = Test-Path -Path $FolderPath
}
else
{
$TestFolderPath = $false
}
}
else
{
$TestFolderPath = $false
}
if ($DirectoryBrowsing -eq "On" -and $TestFolderPath)
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] }
$DirectoryContent = (Get-DirectoryContent -Path "$FolderPath" -HeaderName $HeaderName -RequestURL $RequestURL -SubfolderName $SubfolderName)
$Response.WriteLine("$DirectoryContent")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
else
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\404.ps1)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
# Logging Module
. $PoSHModulePath\modules\Logging.ps1
# Close Connection
try
{
$Response.Close()
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
if ($DebugMode)
{
# Invoke PoSH Server Multithread Process - Thread 1
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null
# Invoke PoSH Server Multithread Process - Thread 2
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null
# Invoke PoSH Server Multithread Process - Thread 3
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null
}
else
{
# Invoke PoSH Server Multithread Process - Thread 1
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig | Out-Null
# Invoke PoSH Server Multithread Process - Thread 2
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig | Out-Null
# Invoke PoSH Server Multithread Process - Thread 3
Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -PoSHModulePath $PoSHModulePath -CustomChildConfig $CustomChildConfig | Out-Null
}
# Create loop
$ShouldProcess = $true
# Get Server Requests
while ($ShouldProcess)
{
# PoSH Server Custom Configuration
$PoSHCustomConfigPath = $HomeDirectory + "\DefaultConfig.ps1"
# Test Config Path
$TestPoSHCustomConfigPath = Test-Path $PoSHCustomConfigPath
if (!$TestPoSHCustomConfigPath)
{
# Import Config
. $PoSHModulePath\modules\DefaultConfig.ps1
}
else
{
# Import Config
. $HomeDirectory\DefaultConfig.ps1
}
# Reset Authentication
$Listener.AuthenticationSchemes = "Anonymous";
# Set Authentication
if ($BasicAuthentication -eq "On") { $Listener.AuthenticationSchemes = "Basic"; }
if ($NTLMAuthentication -eq "On") { $Listener.AuthenticationSchemes = "NTLM"; }
if ($WindowsAuthentication -eq "On") { $Listener.AuthenticationSchemes = "IntegratedWindowsAuthentication"; }
# Open Connection
$Context = $Listener.GetContext()
# Setup Basic Authentication (If Required From Config File)
if ($BasicAuthentication -eq "On")
{
$Identity = $Context.User.Identity;
$PoSHUserName = $Identity.Name
$PoSHUserPassword = $Identity.Password
}
# Setup Windows Authentication (If Required From Config File)
if ($WindowsAuthentication -eq "On")
{
$Identity = $Context.User.Identity;
$PoSHUserName = $Identity.Name
}
# Set Home Directory
[IO.Directory]::SetCurrentDirectory("$HomeDirectory")
$File = $Context.Request.Url.LocalPath
$Response = $Context.Response
$Response.Headers.Add("Accept-Encoding","gzip");
$Response.Headers.Add("Server","PoSH Server");
$Response.Headers.Add("X-Powered-By","Microsoft PowerShell");
# Set Request Parameters
$Request = $Context.Request
$InputStream = $Request.InputStream
$ContentEncoding = $Request.ContentEncoding
# Setup IP Restrictions (If Required By Config File)
$ClientIPAddr = $Request.RemoteEndPoint.Address
if ($IPRestriction -eq "On")
{
if (!($IPWhiteList -match $ClientIPAddr))
{
Write-Warning "$ClientIPAddr has no permission, dropping.."
$IPSessionDrop = "1";
}
else
{
$IPSessionDrop = "0";
}
}
else
{
$IPSessionDrop = "0";
}
# Get Query String
$PoSHQuery = Get-PoSHQueryString -Request $Request
# Get Post Stream
$PoSHPost = Get-PoSHPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding
# Cookie Information
$PoSHCookies = $Request.Cookies["PoSHSessionID"];
if (!$PoSHCookies)
{
$PoSHCookie = New-Object Net.Cookie
$PoSHCookie.Name = "PoSHSessionID"
$PoSHCookie.Value = New-PoSHTimeStamp
$Response.AppendCookie($PoSHCookie)
}
# Get Default Document
if ($File -notlike "*.*" -and $File -like "*/")
{
$FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File
$RequstURL = [string]$Request.Url
$SubfolderName = $File
$File = $File + $DefaultDocument
}
elseif ($File -notlike "*.*" -and $File -notlike "*/")
{
$FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File + "/"
$RequstURL = [string]$Request.Url + "/"
$SubfolderName = $File + "/"
$File = $File + "/" + $DefaultDocument
}
else
{
$FolderPath = $Null;
}
# PoSH API Support
if ($File -like "*.psxml")
{
$File = $File.Replace(".psxml",".ps1")
# Full File Path
$File = [System.IO.Directory]::GetCurrentDirectory() + $File
# Get Mime Type
$MimeType = "text/psxml"
}
else
{
# Full File Path
$File = [System.IO.Directory]::GetCurrentDirectory() + $File
# Get Mime Type
$FileExtension = (Get-ChildItem $File -EA SilentlyContinue).Extension
$MimeType = Get-MimeType $FileExtension
}
#Verify Mimetype Is Supported
if ($ContentFiltering -eq "On")
{
if ($ContentFilterBlackList -match $MimeType)
{
Write-Debug "$MimeType is not allowed, dropping.."
$ContentSessionDrop = "1";
}
else
{
$ContentSessionDrop = "0";
}
}
else
{
$ContentSessionDrop = "0";
}
# Stream Content
if ([System.IO.File]::Exists($File) -and $ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0")
{
if ($MimeType -eq "text/ps1")
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $File)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
elseif ($MimeType -eq "text/psxml")
{
try
{
$Response.ContentType = "text/xml"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $File)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
elseif ($MimeType -eq "text/php")
{
try
{
if ($PHPCgiPath)
{
$TestPHPCgiPath = Test-Path -Path $PHPCgiPath
}
else
{
$TestPHPCgiPath = $false
}
if ($TestPHPCgiPath)
{
if ($File -like "C:\Windows\*")
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\403.ps1)")
}
else
{
$Response.ContentType = "text/html"
$PHPContentOutput = Get-PoSHPHPContent -PHPCgiPath "$PHPCgiPath" -File "$File" -PoSHPHPGET $PoSHQuery.PoSHQueryString -PoSHPHPPOST $PoSHPost.PoSHPostStream
$PHPContentOutput = Set-PHPEncoding -PHPOutput $PHPContentOutput
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$PHPContentOutput")
}
}
else
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\500.ps1)")
}
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
else
{
try
{
$Response.ContentType = "$MimeType"
$FileContent = [System.IO.File]::ReadAllBytes($File)
$Response.ContentLength64 = $FileContent.Length
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response.OutputStream.Write($FileContent, 0, $FileContent.Length)
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
else
{
# Content Filtering and IP Restriction Control
if ($ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0")
{
if ($FolderPath)
{
$TestFolderPath = Test-Path -Path $FolderPath
}
else
{
$TestFolderPath = $false
}
}
else
{
$TestFolderPath = $false
}
if ($DirectoryBrowsing -eq "On" -and $TestFolderPath)
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::OK
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] }
$DirectoryContent = (Get-DirectoryContent -Path "$FolderPath" -HeaderName $HeaderName -RequestURL $RequestURL -SubfolderName $SubfolderName)
$Response.WriteLine("$DirectoryContent")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
else
{
try
{
$Response.ContentType = "text/html"
$Response.StatusCode = [System.Net.HttpStatusCode]::NotFound
$LogResponseStatus = $Response.StatusCode
$Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8)
$Response.WriteLine("$(. $PoSHModulePath\webroot\http\404.ps1)")
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
}
# Logging Module
. $PoSHModulePath\modules\Logging.ps1
# Close Connection
try
{
$Response.Close()
}
catch
{
Add-Content -Value $_ -Path "$LogDirectory\debug.txt"
}
}
# Stop Listener
$Listener.Stop()
}
}
} |
403.ps1 | 7DWSM-1.4.0 | # Copyright (C) 2014 Yusuf Ozturk
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# PoSH Server 500 Module
if ($HostName -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $HostNames[0] }
@"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PoSH Server - 500 - Internal Server Error</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px 0 10px 40px;}
ul.first,ol.first{margin-top:5px;}
fieldset{padding:0 15px 10px 15px;}
.summary-container fieldset{padding-bottom:5px;margin-top:4px;}
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;}
legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px;
border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696;
border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;}
a:link,a:visited{color:#007EFF;font-weight:bold;}
a:hover{text-decoration:none;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;}
h4{font-size:1.2em;margin:10px 0 5px 0;
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
}#content{margin:0 0 0 2%;position:relative;}
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
.config_source{background:#fff5c4;}
.content-container p{margin:0 0 10px 0;
}#details-left{width:35%;float:left;margin-right:2%;
}#details-right{width:63%;float:left;overflow:hidden;
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
}#server_version p{margin:5px 0;}
table{margin:4px 0 4px 0;width:100%;border:none;}
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;}
th{width:30%;text-align:right;padding-right:2%;font-weight:normal;}
thead th{background-color:#ebebeb;width:25%;
}#details-right th{width:20%;}
table tr.alt td,table tr.alt th{background-color:#ebebeb;}
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;}
.clear{clear:both;}
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error in Application "$HeaderName"</h1></div>
<div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div>
<div id="content">
<div class="content-container">
<fieldset><legend>Error Summary</legend>
<h2>HTTP Error 500 - Internal Server Error</h2>
<h3>The page you are requesting cannot be served because of the security restriction.</h3>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Most likely causes:</legend>
<ul> <li>You are trying to execute PHP files in C:\Windows. By default, PHP has no read access into Windows directory.</li> <li>The feature you are trying to use may not be installed.</li> <li>The appropriate MIME map is not enabled for the Web site or application.</li> <li>If PHP is not installed.</li></ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Things you can try:</legend>
<ul> <li>Ensure that the expected handler for the current page is mapped.</li> <li>Make sure you provided correct php-cgi.exe path in config file.</li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Links and More Information</legend>
This error occurs when the file extension of the requested URL is for a MIME type that is not configured on the server. You can add a MIME type for the file extension for files that are not dynamic scripting pages, database, or configuration files. Process those file types using a handler. You should not allows direct downloads of dynamic scripting pages, database or configuration files.
<p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=500,0,0x80070032,8250">View more information »</a></p>
</fieldset>
</div>
</div>
</body>
</html>
"@ |
500.ps1 | 7DWSM-1.4.0 | # Copyright (C) 2014 Yusuf Ozturk
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# PoSH Server 404 Module
if ($HostName -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $HostNames[0] }
@"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PoSH Server - 404.3 - Not found</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px 0 10px 40px;}
ul.first,ol.first{margin-top:5px;}
fieldset{padding:0 15px 10px 15px;}
.summary-container fieldset{padding-bottom:5px;margin-top:4px;}
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;}
legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px;
border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696;
border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;}
a:link,a:visited{color:#007EFF;font-weight:bold;}
a:hover{text-decoration:none;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;}
h4{font-size:1.2em;margin:10px 0 5px 0;
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
}#content{margin:0 0 0 2%;position:relative;}
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
.config_source{background:#fff5c4;}
.content-container p{margin:0 0 10px 0;
}#details-left{width:35%;float:left;margin-right:2%;
}#details-right{width:63%;float:left;overflow:hidden;
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
}#server_version p{margin:5px 0;}
table{margin:4px 0 4px 0;width:100%;border:none;}
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;}
th{width:30%;text-align:right;padding-right:2%;font-weight:normal;}
thead th{background-color:#ebebeb;width:25%;
}#details-right th{width:20%;}
table tr.alt td,table tr.alt th{background-color:#ebebeb;}
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;}
.clear{clear:both;}
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error in Application "$HeaderName"</h1></div>
<div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div>
<div id="content">
<div class="content-container">
<fieldset><legend>Error Summary</legend>
<h2>HTTP Error 404.3 - Not Found</h2>
<h3>The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.</h3>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Most likely causes:</legend>
<ul> <li>𣗏t is possible that a handler mapping is missing. By default, the static file handler processes all content.</li> <li>𥸎he feature you are trying to use may not be installed.</li> <li>𥸎he appropriate MIME map is not enabled for the Web site or application.</li> <li>𣗏f PHP is not installed.</li></ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Things you can try:</legend>
<ul> <li>Ensure that the expected handler for the current page is mapped.</li> <li>Make sure you provided correct php-cgi.exe path in config file.</li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><legend>Links and More Information</legend>
This error occurs when the file extension of the requested URL is for a MIME type that is not configured on the server. You can add a MIME type for the file extension for files that are not dynamic scripting pages, database, or configuration files. Process those file types using a handler. You should not allows direct downloads of dynamic scripting pages, database or configuration files.
<p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=404,3,0x80070032,8250">View more information »</a></p>
</fieldset>
</div>
</div>
</body>
</html>
"@ |
Subsets and Splits