full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/AddQueue.Tests.ps1
|
AddQueue.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\TestSetup.ps1"
. "$here\..\Public\Add-RabbitMQQueue.ps1"
function TearDownTest($VirtualHost = "/", $Queues) {
foreach($queue in $queues){
Remove-RabbitMQQueue -BaseUri $server -name $queue -ErrorAction Continue -Confirm:$false
}
}
Describe -Tags "Example" "Add-RabbitMQQueue" {
It "should create new Queue" {
Add-RabbitMQQueue -BaseUri $server -Name q1
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty name
$actual | Should Be "q1"
TearDownTest -Queues q1
}
## do we need a test to create a queue on a non-default vhost?
It "should create Durable new Queue" {
Add-RabbitMQQueue -BaseUri $server -Name q1 -Durable
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty durable
$actual | Should Be $true
TearDownTest -Queues q1
}
It "should create AutoDelete new Queue" {
Add-RabbitMQQueue -BaseUri $server -Name q1 -AutoDelete
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty auto_delete
$actual | Should Be $true
TearDownTest -Queues q1
}
It "should create Durable, AutoDelete new Queue" {
Add-RabbitMQQueue -BaseUri $server -Name q1 -Durable -AutoDelete
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty durable
$actual | Should Be $true
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty auto_delete
$actual | Should Be $true
TearDownTest -Queues q1
}
It "should do nothing when Queue already exists" {
Add-RabbitMQQueue -BaseUri $server -Name q1
Add-RabbitMQQueue -BaseUri $server -Name q1
$actual = Get-RabbitMQQueue -BaseUri $server -Name q1 | select -ExpandProperty name
$actual | Should Be "q1"
TearDownTest -Queues q1
}
It "should create many Queues" {
Add-RabbitMQQueue -BaseUri $server -Name q1,q2,q3
$actual = Get-RabbitMQQueue -BaseUri $server -Name "q*" | select -ExpandProperty name
$expected = $("q1", "q2", "q3")
AssertAreEqual $actual $expected
TearDownTest -Queues q1,q2,q3
}
It "should get queue names from the pipe" {
$pipe = $("q1", "q1")
$pipe| Add-RabbitMQQueue -BaseUri $server
$actual = $($pipe | Get-RabbitMQQueue -BaseUri $server) | select -ExpandProperty name
$expected = $pipe
AssertAreEqual $actual $expected
TearDownTest -Queues q1
}
It "should get queue definitions from the pipe" {
$pipe = $(
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/" ; "Name" = "q1" }
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/" ; "Name" = "q2"; "Durable" = $true }
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/" ; "Name" = "q3"; "AutoDelete" = $true }
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/" ; "Name" = "q4"; "Durable" = $true; "AutoDelete" = $true }
)
$pipe | Add-RabbitMQQueue
$actual = $pipe | Get-RabbitMQQueue -BaseUri $server
foreach ($e in $pipe)
{
$a = $actual | ? name -eq $e.Name
$a | Should Not Be $null
$a.vhost | Should Be $e.VirtualHost
if ($e.Durable) { $a.durable | Should Be $true }
if ($e.AutoDelete) { $a.auto_delete | Should Be $true }
}
TearDownTest -Queues q1,q2,q3,q4
}
}
|
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/RemoveVirtualHost.Tests.ps1
|
RemoveVirtualHost.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\TestSetup.ps1"
. "$here\..\Public\Remove-RabbitMQVirtualHost.ps1"
function SetUpTest($vhosts = ("vh1","vh2")) {
Add-RabbitMQVirtualHost -BaseUri $server -Name $vhosts
}
function TearDownTest($vhosts = ("vh1","vh2")) {
foreach($vhost in $vhosts){
Remove-RabbitMQVirtualHost -BaseUri $server -Name $vhost -ErrorAction Continue -Confirm:$false
}
}
Describe -Tags "Example" "Remove-RabbitMQVirtualHost" {
It "should remove existing Virtual Host" {
SetUpTest
Add-RabbitMQVirtualHost -BaseUri $server "vh3"
Remove-RabbitMQVirtualHost -BaseUri $server "vh3" -Confirm:$false
$actual = Get-RabbitMQVirtualHost -BaseUri $server "vh*" | select -ExpandProperty name
$actual | Should Be $("vh1", "vh2")
TearDownTest
}
}
|
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/AddVirtualHost.Tests.ps1
|
AddVirtualHost.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\TestSetup.ps1"
. "$here\..\Public\Add-RabbitMQVirtualHost.ps1"
function TearDownTest() {
$vhosts = Get-RabbitMQVirtualHost -BaseUri $server -Name vh3, vh4
($vhosts) | Remove-RabbitMQVirtualHost -BaseUri $server -ErrorAction Continue -Confirm:$false
}
Describe -Tags "Example" "Add-RabbitMQVirtualHost" {
It "should create new Virtual Host" {
Add-RabbitMQVirtualHost -BaseUri $server -Name "vh3"
$actual = Get-RabbitMQVirtualHost -BaseUri $server -Name "vh3" | select -ExpandProperty name
$actual | Should Be "vh3"
TearDownTest
}
It "should do nothing when VirtualHost already exists" {
Add-RabbitMQVirtualHost -BaseUri $server "vh3"
Add-RabbitMQVirtualHost -BaseUri $server "vh3"
$actual = Get-RabbitMQVirtualHost -BaseUri $server "vh3" | select -ExpandProperty name
$actual | Should Be "vh3"
TearDownTest
}
It "should create many Virtual Hosts" {
Add-RabbitMQVirtualHost -BaseUri $server "vh3", "vh4"
$actual = Get-RabbitMQVirtualHost -BaseUri $server "vh3", "vh4" | select -ExpandProperty name
$expected = $("vh3", "vh4")
AssertAreEqual $actual $expected
TearDownTest
}
It "should get VirtualHost to be created from the pipe" {
$("vh3", "vh4") | Add-RabbitMQVirtualHost -BaseUri $server
$actual = $($("vh3", "vh4") | Get-RabbitMQVirtualHost -BaseUri $server) | select -ExpandProperty name
$expected = $("vh3", "vh4")
AssertAreEqual $actual $expected
TearDownTest
}
It "should get VirtualHost with BaseUri to be created from the pipe" {
$pipe = $(
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "vh3" }
New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "vh4" }
)
$pipe | Add-RabbitMQVirtualHost
$actual = $($pipe | Get-RabbitMQVirtualHost -BaseUri $server) | select -ExpandProperty name
$expected = $("vh3", "vh4")
AssertAreEqual $actual $expected
TearDownTest
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Deploy/Download_MDT_Prereqs.ps1
|
Download_MDT_Prereqs.ps1
|
Configuration DownloadMDTPrereqs
{
Import-Module -Name PSDesiredStateConfiguration, cMDTBuildLab
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName cMDTBuildLab
node $AllNodes.Where{$_.Role -match "MDT Server"}.NodeName
{
LocalConfigurationManager {
RebootNodeIfNeeded = $AllNodes.RebootNodeIfNeeded
ConfigurationMode = $AllNodes.ConfigurationMode
}
cMDTBuildPreReqs MDTPreReqs {
DownloadPath = $Node.SourcePath
}
WindowsFeature DataDeduplication {
Ensure = "Present"
Name = "FS-Data-Deduplication"
}
<#
Package ADK {
Ensure = "Present"
Name = "Windows Assessment and Deployment Kit - Windows 10"
Path = "$($Node.SourcePath)\Windows Assessment and Deployment Kit\adksetup.exe"
ProductId = "cef137de-cdb9-48e2-babe-301cb8448d7b"
Arguments = "/quiet /features OptionId.DeploymentTools OptionId.WindowsPreinstallationEnvironment"
ReturnCode = 0
}
Package MDT {
Ensure = "Present"
Name = "Microsoft Deployment Toolkit (6.3.8443.1000)"
Path = "$($Node.SourcePath)\Microsoft Deployment Toolkit\MicrosoftDeploymentToolkit_x64.msi"
ProductId = "9547DE37-4A70-4194-97EA-ACC3E747254B"
ReturnCode = 0
}
#>
}
}
#Set configuration data
$ConfigurationData = @{
AllNodes =
@(
@{
#Global Settings for the configuration of Desired State Local Configuration Manager:
NodeName = "*"
RebootNodeIfNeeded = $true
ConfigurationMode = "ApplyOnly"
},
@{
#Node Settings for the configuration of an MDT Server:
NodeName = "$env:computername"
Role = "MDT Server"
#Sources for download/Prereqs
SourcePath = "E:\Source"
}
)
}
#Create DSC MOF job
DownloadMDTPrereqs -OutputPath "$PSScriptRoot\DownloadMDTPrereqs" -ConfigurationData $ConfigurationData
#Set DSC LocalConfigurationManager
Set-DscLocalConfigurationManager -Path "$PSScriptRoot\DownloadMDTPrereqs" -Verbose
#Start DSC MOF job
Start-DscConfiguration -Wait -Force -Verbose -ComputerName "$env:computername" -Path "$PSScriptRoot\DownloadMDTPrereqs"
#Set data deduplication
Enable-DedupVolume -Volume "E:"
Set-DedupVolume -Volume "E:" -MinimumFileAgeDays 1
Write-Output ""
Write-Output "Download MDT Prereqs is completed!"
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Deploy/ImageFactoryV3-Build.ps1
|
ImageFactoryV3-Build.ps1
|
<#
.Synopsis
ImageFactory 3.2
.DESCRIPTION
Run this script for build Windows Reference Images on remote Hyper-V host
.EXAMPLE
Edit config ImageFactoryV3.xml with your settings:
<Settings>
<ReportFrom>AutoBuild@build.lab</ReportFrom>
<ReportTo>AutoBuild@build.lab</ReportTo>
<ReportSmtp>smtp.build.lab</ReportSmtp>
<MDT>
<DeploymentShare>E:\MDTBuildLab</DeploymentShare>
<RefTaskSequenceFolderName>REF</RefTaskSequenceFolderName>
</MDT>
<HyperV>
<StartUpRAM>4</StartUpRAM>
<VLANID>0</VLANID>
<Computername>HV01</Computername>
<SwitchName>Network Switch</SwitchName>
<VMLocation>E:\Build</VMLocation>
<ISOLocation>E:\Build\ISO</ISOLocation>
<VHDSize>60</VHDSize>
<NoCPU>2</NoCPU>
</HyperV>
</Settings>
Run ImageFactoryV3-Build.ps1 at MDT host
.NOTES
Created: 2016-11-24
Version: 3.1
Updated: 2017-02-23
Version: 3.2
Author : Mikael Nystrom
Twitter: @mikael_nystrom
Blog : http://deploymentbunny.com
Disclaimer:
This script is provided 'AS IS' with no warranties, confers no rights and
is not supported by the author.
Modyfy : Pavel Andreev
E-mail : pvs043@outlook.com
Date : 2017-02-27
Project: cMDTBuildLab (https://github.com/pvs043/cMDTBuildLab/wiki)
Changes:
* Remove dependency for PsIni module
* Remove cleaning of MDT Captures folder: each new captured WIM is builded with timestamp date at file name for history tracking,
you can delete or move old images from external scripts
* Run Reference VMs as Job at Hyper-V host: it's faster
* Remove "ConcurrentRunningVMs" param from config: cMDTBuildLab build maximum to 8 concurrent VMs.
Tune need count with count of reference Task Sequences in the REF folder
* Remove cleaning of CustomSettings.ini after build: this is a job for DSC configuration.
Configure DSCLocalConfigurationManager on MDT server with
ConfigurationMode = "ApplyAndAutoCorrect"
ConfigurationModeFrequencyMins = 60
* Possibility of sending build results to E-mail
.LINK
http://www.deploymentbunny.com
https://github.com/pvs043/cMDTBuildLab/wiki
#>
[cmdletbinding(SupportsShouldProcess=$True)]
Param(
[parameter(mandatory=$false)]
[ValidateSet($True,$False)]
$UpdateBootImage = $False
)
Function Get-VIARefTaskSequence
{
Param(
$RefTaskSequenceFolder
)
$RefTaskSequences = Get-ChildItem $RefTaskSequenceFolder
Foreach ($RefTaskSequence in $RefTaskSequences) {
New-Object PSObject -Property @{
TaskSequenceID = $RefTaskSequence.ID
Name = $RefTaskSequence.Name
Comments = $RefTaskSequence.Comments
Version = $RefTaskSequence.Version
Enabled = $RefTaskSequence.enable
LastModified = $RefTaskSequence.LastModifiedTime
}
}
}
Function Test-VIAHypervConnection
{
Param(
$Computername,
$ISOFolder,
$VMFolder,
$VMSwitchName
)
#Verify SMB access
$Result = Test-NetConnection -ComputerName $Computername -CommonTCPPort SMB
If ($Result.TcpTestSucceeded -eq $true) {Write-Verbose "SMB Connection to $Computername is ok"} else {Write-Warning "SMB Connection to $Computername is NOT ok"; Return $False}
#Verify WinRM access
$Result = Test-NetConnection -ComputerName $Computername -CommonTCPPort WINRM
If ($Result.TcpTestSucceeded -eq $true) {Write-Verbose "WINRM Connection to $Computername is ok"} else {Write-Warning "WINRM Connection to $Computername is NOT ok"; Return $False}
#Verify that Microsoft-Hyper-V-Management-PowerShell is installed
Invoke-Command -ComputerName $Computername -ScriptBlock {
$Result = (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShell)
Write-Verbose "$($Result.DisplayName) is $($Result.State)"
If ($($Result.State) -ne "Enabled") {Write-Warning "$($Result.DisplayName) is not Enabled"; Return $False}
}
#Verify that Microsoft-Hyper-V-Management-PowerShell is installed
Invoke-Command -ComputerName $Computername -ScriptBlock {
$Result = (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V)
If ($($Result.State) -ne "Enabled") {Write-Warning "$($Result.DisplayName) is not Enabled"; Return $False}
}
#Verify that Hyper-V is running
Invoke-Command -ComputerName $Computername -ScriptBlock {
$Result = (Get-Service -Name vmms)
Write-Verbose "$($Result.DisplayName) is $($Result.Status)"
If ($($Result.Status) -ne "Running") {Write-Warning "$($Result.DisplayName) is not Running"; Return $False}
}
#Verify that the ISO Folder is created
Invoke-Command -ComputerName $Computername -ScriptBlock {
Param(
$ISOFolder
)
New-Item -Path $ISOFolder -ItemType Directory -Force | Out-Null
} -ArgumentList $ISOFolder
#Verify that the VM Folder is created
Invoke-Command -ComputerName $Computername -ScriptBlock {
Param(
$VMFolder
)
New-Item -Path $VMFolder -ItemType Directory -Force | Out-Null
} -ArgumentList $VMFolder
#Verify that the VMSwitch exists
Invoke-Command -ComputerName $Computername -ScriptBlock {
Param(
$VMSwitchName
)
if (((Get-VMSwitch | Where-Object -Property Name -EQ -Value $VMSwitchName).count) -eq "1") {Write-Verbose "Found $VMSwitchName"} else {Write-Warning "No swtch with the name $VMSwitchName found"; Return $False}
} -ArgumentList $VMSwitchName
Return $true
}
Function Update-Log
{
[cmdletbinding(SupportsShouldProcess=$True)]
Param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0
)]
[string]$Data,
[Parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0
)]
[string]$Solution = $Solution,
[Parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=1
)]
[validateset('Information','Warning','Error')]
[string]$Class = "Information"
)
$LogString = "$Solution, $Data, $Class, $(Get-Date)"
$HostString = "$Solution, $Data, $(Get-Date)"
Add-Content -Path $Log -Value $LogString
switch ($Class)
{
'Information'{
Write-Output $HostString
}
'Warning'{
Write-Warning $HostString
}
'Error'{
Write-Error $HostString
}
Default {}
}
}
#Inititial Settings
Clear-Host
$Log = "$($PSScriptRoot)\ImageFactoryV3ForHyper-V.log"
$XMLFile = "$($PSScriptRoot)\ImageFactoryV3.xml"
$Solution = "IMF32"
Update-Log -Data "Imagefactory 3.2 (Hyper-V)"
Update-Log -Data "Logfile is $Log"
Update-Log -Data "XMLfile is $XMLfile"
#Importing modules
Update-Log -Data "Importing modules"
Import-Module 'C:\Program Files\Microsoft Deployment Toolkit\Bin\MicrosoftDeploymentToolkit.psd1' -ErrorAction Stop -WarningAction Stop
#Read Settings from XML
Update-Log -Data "Reading from $XMLFile"
[xml]$Settings = Get-Content $XMLFile -ErrorAction Stop -WarningAction Stop
#Verify Connection to DeploymentRoot
Update-Log -Data "Verify Connection to DeploymentRoot"
$Result = Test-Path -Path $Settings.Settings.MDT.DeploymentShare
If ($Result -ne $true) {Update-Log -Data "Cannot access $($Settings.Settings.MDT.DeploymentShare), will break"; break}
#Connect to MDT
Update-Log -Data "Connect to MDT"
$Root = $Settings.Settings.MDT.DeploymentShare
if ( !(Get-PSDrive -Name 'MDTBuild' -ErrorAction SilentlyContinue) ) {
$MDTPSDrive = New-PSDrive -Name MDTBuild -PSProvider MDTProvider -Root $Root -ErrorAction Stop
Update-Log -Data "Connected to $($MDTPSDrive.Root)"
}
#Get MDT Settings
Update-Log -Data "Get MDT Settings"
$MDTSettings = Get-ItemProperty 'MDTBuild:'
#Check if we should update the boot image
Update-Log -Data "Check if we should update the boot image"
If($UpdateBootImage -eq $True){
#Update boot image
Update-Log -Data "Updating boot image, please wait"
Update-MDTDeploymentShare -Path MDT: -ErrorAction Stop
}
#Verify access to boot image
Update-Log -Data "Verify access to boot image"
$MDTImage = $($Settings.Settings.MDT.DeploymentShare) + "\boot\" + $($MDTSettings.'Boot.x86.LiteTouchISOName')
if((Test-Path -Path $MDTImage) -eq $true) {Update-Log -Data "Access to $MDTImage is ok"} else {Write-Warning "Could not access $MDTImage"; BREAK}
#Get TaskSequences
Update-Log -Data "Get TaskSequences"
$RefTaskSequences = Get-VIARefTaskSequence -RefTaskSequenceFolder "MDTBuild:\Task Sequences\$($Settings.Settings.MDT.RefTaskSequenceFolderName)" | where-object Enabled -eq $true
#Get TaskSequencesIDs
$RefTaskSequenceIDs = $RefTaskSequences.TasksequenceID
Update-Log -Data "Found $($RefTaskSequenceIDs.count) TaskSequences to work on"
#check task sequence count
if ($RefTaskSequenceIDs.count -eq 0) {
Update-Log -Data "Sorry, could not find any TaskSequences to work with"
BREAK
}
#Get detailed info
Update-Log -Data "Get detailed info about the task sequences"
$Result = Get-VIARefTaskSequence -RefTaskSequenceFolder "MDTBuild:\Task Sequences\$($Settings.Settings.MDT.RefTaskSequenceFolderName)" | Where-Object Enabled -eq $true
foreach($obj in ($Result | Select-Object TaskSequenceID,Name,Version)){
$data = "$($obj.TaskSequenceID) $($obj.Name) $($obj.Version)"
Update-Log -Data $data
}
#Verify Connection to Hyper-V host
Update-Log -Data "Verify Connection to Hyper-V host"
$Result = Test-VIAHypervConnection -Computername $Settings.Settings.HyperV.Computername -ISOFolder $Settings.Settings.HyperV.ISOLocation -VMFolder $Settings.Settings.HyperV.VMLocation -VMSwitchName $Settings.Settings.HyperV.SwitchName
If ($Result -ne $true) {Update-Log -Data "$($Settings.Settings.HyperV.Computername) is not ready, will break"; break}
#Upload boot image to Hyper-V host
Update-Log -Data "Upload boot image to Hyper-V host"
$DestinationFolder = "\\" + $($Settings.Settings.HyperV.Computername) + "\" + $($Settings.Settings.HyperV.ISOLocation -replace ":","$")
Copy-Item -Path $MDTImage -Destination $DestinationFolder -Force
#Create the VM's on Host
Update-Log -Data "Create the VM's on Host"
Foreach ($Ref in $RefTaskSequenceIDs) {
$VMName = $ref
$VMMemory = [int]$($Settings.Settings.HyperV.StartUpRAM) * 1GB
$VMPath = $($Settings.Settings.HyperV.VMLocation)
$VMBootimage = $($Settings.Settings.HyperV.ISOLocation) + "\" + $($MDTImage | Split-Path -Leaf)
$VMVHDSize = [int]$($Settings.Settings.HyperV.VHDSize) * 1GB
$VMVlanID = $($Settings.Settings.HyperV.VLANID)
$VMVCPU = $($Settings.Settings.HyperV.NoCPU)
$VMSwitch = $($Settings.Settings.HyperV.SwitchName)
Invoke-Command -ComputerName $($Settings.Settings.HyperV.Computername) -ScriptBlock {
Param(
$VMName,
$VMMemory,
$VMPath,
$VMBootimage,
$VMVHDSize,
$VMVlanID,
$VMVCPU,
$VMSwitch
)
Write-Verbose "Hyper-V host is $env:COMPUTERNAME"
Write-Verbose "Working on $VMName"
#Check if VM exist
if (!((Get-VM | Where-Object -Property Name -EQ -Value $VMName).count -eq 0)) {Write-Warning -Message "VM exist"; Break}
#Create VM
$VM = New-VM -Name $VMName -MemoryStartupBytes $VMMemory -Path $VMPath -NoVHD -Generation 1
Write-Verbose "$($VM.Name) is created"
#Disable dynamic memory
Set-VMMemory -VM $VM -DynamicMemoryEnabled $false
Write-Verbose "Dynamic memory is disabled on $($VM.Name)"
#Connect to VMSwitch
Connect-VMNetworkAdapter -VMNetworkAdapter (Get-VMNetworkAdapter -VM $VM) -SwitchName $VMSwitch
Write-Verbose "$($VM.Name) is connected to $VMSwitch"
#Set vCPU
if ($VMVCPU -ne "1") {
$Result = Set-VMProcessor -Count $VMVCPU -VM $VM -Passthru
Write-Verbose "$($VM.Name) has $($Result.count) vCPU"
}
#Set VLAN
If ($VMVlanID -ne "0") {
$Result = Set-VMNetworkAdapterVlan -VlanId $VMVlanID -Access -VM $VM -Passthru
Write-Verbose "$($VM.Name) is configured for VLANid $($Result.NativeVlanId)"
}
#Create empty disk
$VHD = $VMName + ".vhdx"
$result = New-VHD -Path "$VMPath\$VMName\Virtual Hard Disks\$VHD" -SizeBytes $VMVHDSize -Dynamic -ErrorAction Stop
Write-Verbose "$($result.Path) is created for $($VM.Name)"
#Add VHDx
$result = Add-VMHardDiskDrive -VMName $VMName -Path "$VMPath\$VMName\Virtual Hard Disks\$VHD" -Passthru
Write-Verbose "$($result.Path) is attached to $VMName"
#Connect ISO
$result = Set-VMDvdDrive -VMName $VMName -Path $VMBootimage -Passthru
Write-Verbose "$($result.Path) is attached to $VMName"
#Set Notes
Set-VM -VMName $VMName -Notes "REFIMAGE"
} -ArgumentList $VMName,$VMMemory,$VMPath,$VMBootimage,$VMVHDSize,$VMVlanID,$VMVCPU,$VMSwitch
}
#Get BIOS Serialnumber from each VM and update the customsettings.ini file
Update-Log -Data "Get BIOS Serialnumber from each VM and update the customsettings.ini file"
$IniFile = "$($Settings.settings.MDT.DeploymentShare)\Control\CustomSettings.ini"
Foreach($Ref in $RefTaskSequenceIDs) {
#Get BIOS Serailnumber from the VM
$BIOSSerialNumber = Invoke-Command -ComputerName $($Settings.Settings.HyperV.Computername) -ScriptBlock {
Param(
$VMName
)
#$VMObject = Get-CimInstance -Namespace root\virtualization\v2 -ClassName Msvm_ComputerSystem | Where-Object {$_.ElementName -eq $VMName}
#(Get-CimAssociatedInstance $VMObject | Where-Object {$_.Caption -eq 'BIOS'}).SerialNumber
# PSSCriptAnalyzer warning, but work
$VMObject = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter "ElementName = '$VMName'"
$VMObject.GetRelated('Msvm_VirtualSystemSettingData').BIOSSerialNumber
} -ArgumentList $Ref
#Update CustomSettings.ini
$CustomSettings = Get-Content -Path $IniFile
$CustomSettings += "
[$BIOSSerialNumber]
OSDComputerName=$Ref
TaskSequenceID=$Ref
BackupFile=#left(""$Ref"", len(""$Ref"")-3) & year(date) & right(""0"" & month(date), 2) & right(""0"" & day(date), 2)#.wim
DoCapture=YES
SkipTaskSequence=YES
SkipCapture=YES"
Set-Content -Path $IniFile -Value $CustomSettings
}
#Test for CustomSettings.ini changes
#Read-Host -Prompt "Waiting"
#Start VM's on Host
Update-Log -Data "Start VM's on Host"
Foreach ($Ref in $RefTaskSequences) {
$VMName = $Ref.TasksequenceID
$ImageName = $Ref.Name
$ReportFrom = $($Settings.Settings.ReportFrom)
$ReportTo = $($Settings.Settings.ReportTo)
$ReportSmtp = $($Settings.Settings.ReportSmtp)
Invoke-Command -ComputerName $($Settings.Settings.HyperV.Computername) -ScriptBlock {
param(
$VMName,
$ImageName,
$ReportFrom,
$ReportTo,
$ReportSmtp
)
Write-Output "Starting VM: $($VmName)"
Start-VM -Name $VMName
Start-Sleep 60
$VM = Get-VM -Name $VMName
$StartTime = Get-Date
while ($VM.State -eq "Running") {
Start-Sleep "90"
$VM = Get-VM -Name $VMName
}
$EndTime = Get-Date
$ElapsedTime = $EndTime - $StartTime
$hours = [math]::floor($ElapsedTime.TotalHours)
$mins = [int]$ElapsedTime.TotalMinutes - $hours*60
$report = "Image [$ImageName] was builded at $hours h. $mins min."
Write-Output $report
# Send Report
If ($ReportFrom -and $ReportTo -and $ReportSmtp) {
$subject = "Image $ImageName"
$encoding = [System.Text.Encoding]::UTF8
Send-MailMessage -From $ReportFrom -To $ReportTo -Subject $subject -SmtpServer $ReportSmtp -Encoding $encoding -BodyAsHtml $report
}
# Remove reference VM
Write-Output "Deleting $($VM.Name) on $($VM.Computername) at $($VM.ConfigurationLocation)"
Remove-VM -VM $VM -Force
Remove-Item -Path $VM.ConfigurationLocation -Recurse -Force
} -ArgumentList $VMName,$ImageName,$ReportFrom,$ReportTo,$ReportSmtp -AsJob -JobName $VMName
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Deploy/Deploy_MDT_Server.ps1
|
Deploy_MDT_Server.ps1
|
Configuration DeployMDTServerContract
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments')]
Param(
[Parameter(Mandatory=$true, HelpMessage = "Enter password for MDT Local Account")]
[PSCredential]$Credentials
)
Import-Module -Name PSDesiredStateConfiguration, xSmbShare, cNtfsAccessControl, cMDTBuildLab
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName xSmbShare
Import-DscResource -ModuleName cNtfsAccessControl
Import-DscResource -ModuleName cMDTBuildLab
node $AllNodes.Where{$_.Role -match "MDT Server"}.NodeName
{
LocalConfigurationManager {
RebootNodeIfNeeded = $AllNodes.RebootNodeIfNeeded
ConfigurationMode = $AllNodes.ConfigurationMode
ConfigurationModeFrequencyMins = $AllNodes.ConfigurationModeFrequencyMins
RefreshFrequencyMins = $AllNodes.RefreshFrequencyMins
}
cMDTBuildPreReqs MDTPreReqs {
DownloadPath = $Node.SourcePath
}
User MDTAccessAccount {
Ensure = "Present"
UserName = $Credentials.UserName
FullName = $Credentials.UserName
Password = $Credentials
PasswordChangeRequired = $false
PasswordNeverExpires = $true
Description = "Managed Client Administrator Account"
Disabled = $false
}
WindowsFeature DataDeduplication {
Ensure = "Present"
Name = "FS-Data-Deduplication"
}
Package ADK {
Ensure = "Present"
Name = "Windows Assessment and Deployment Kit - Windows 10"
Path = "$($Node.SourcePath)\Windows Assessment and Deployment Kit\adksetup.exe"
ProductId = "cef137de-cdb9-48e2-babe-301cb8448d7b"
Arguments = "/quiet /features OptionId.DeploymentTools OptionId.WindowsPreinstallationEnvironment"
ReturnCode = 0
}
Package MDT {
Ensure = "Present"
Name = "Microsoft Deployment Toolkit (6.3.8443.1000)"
Path = "$($Node.SourcePath)\Microsoft Deployment Toolkit\MicrosoftDeploymentToolkit_x64.msi"
ProductId = "9547DE37-4A70-4194-97EA-ACC3E747254B"
ReturnCode = 0
}
cMDTBuildDirectory DeploymentFolder {
Name = $Node.PSDrivePath.Replace("$($Node.PSDrivePath.Substring(0,2))\","")
Path = $Node.PSDrivePath.Substring(0,2)
DependsOn = "[Package]MDT"
}
xSmbShare FolderDeploymentShare {
Ensure = "Present"
Name = $Node.PSDriveShareName
Path = $Node.PSDrivePath
#FullAccess = "$($Node.NodeName)\$($Credentials.UserName)"
FullAccess = "Everyone"
FolderEnumerationMode = "AccessBased"
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
cMDTBuildPersistentDrive DeploymentPSDrive {
Name = $Node.PSDriveName
Path = $Node.PSDrivePath
Description = $Node.PSDrivePath.Replace("$($Node.PSDrivePath.Substring(0,2))\","")
NetworkPath = "\\$($Node.NodeName)\$($Node.PSDriveShareName)"
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
ForEach ($OSDirectory in $Node.OSDirectories) {
[string]$OSVersion = ""
$OSDirectory.GetEnumerator() | % {
If ($_.key -eq "OperatingSystem") { $OSVersion = $_.value }
}
cMDTBuildDirectory $OSVersion.Replace(' ','') {
Name = $OSVersion
Path = "$($Node.PSDriveName):\Operating Systems"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
cMDTBuildDirectory "TS$($OSVersion.Replace(' ',''))" {
Name = $OSVersion
Path = "$($Node.PSDriveName):\Task Sequences"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
# Task Sequence folder for autobuild
cMDTBuildDirectory "TSREF" {
Name = "REF"
Path = "$($Node.PSDriveName):\Task Sequences"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
ForEach ($PkgFolder in $Node.PackagesFolderStructure) {
[string]$Folder = ""
$PkgFolder.GetEnumerator() | % {
If ($_.key -eq "Folder") { $Folder = $_.value }
}
cMDTBuildDirectory "PKG$($Folder.Replace(' ',''))" {
Name = $Folder
Path = "$($Node.PSDriveName):\Packages"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($CurrentApplicationFolder in $Node.ApplicationFolderStructure) {
[string]$ApplicationFolder = ""
$CurrentApplicationFolder.GetEnumerator() | % {
If ($_.key -eq "Folder") { $ApplicationFolder = $_.value }
}
cMDTBuildDirectory "AF$($ApplicationFolder.Replace(' ',''))" {
Name = $ApplicationFolder
Path = "$($Node.PSDriveName):\Applications"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
ForEach ($CurrentApplicationSubFolder in $CurrentApplicationFolder.SubFolders) {
[string]$ApplicationSubFolder = ""
$CurrentApplicationSubFolder.GetEnumerator() | % {
If ($_.key -eq "SubFolder") { $ApplicationSubFolder = $_.value }
}
cMDTBuildDirectory "ASF$($ApplicationSubFolder.Replace(' ',''))" {
Name = $ApplicationSubFolder
Path = "$($Node.PSDriveName):\Applications\$ApplicationFolder"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
}
ForEach ($SelectionProfile in $Node.SelectionProfiles) {
[string]$Name = ""
[string]$Comments = ""
[string]$IncludePath = ""
$SelectionProfile.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Comments") { $Comments = $_.value }
If ($_.key -eq "IncludePath") { $IncludePath = $_.value }
}
cMDTBuildSelectionProfile $Name.Replace(' ','') {
Name = $Name
Comments = $Comments
IncludePath = $IncludePath
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($OperatingSystem in $Node.OperatingSystems) {
[string]$Name = ""
[string]$Path = ""
[string]$SourcePath = ""
$OperatingSystem.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Path") { $Path = "$($Node.PSDriveName):\Operating Systems\$($_.value)" }
If ($_.key -eq "SourcePath") { $SourcePath = "$($Node.SourcePath)\$($_.value)" }
}
cMDTBuildOperatingSystem $Name.Replace(' ','') {
Name = $Name
Path = $Path
SourcePath = $SourcePath
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($Application in $Node.Applications) {
[string]$Name = ""
[string]$Path = ""
[string]$CommandLine = ""
[string]$ApplicationSourcePath = ""
$Application.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Path") { $Path = "$($Node.PSDriveName):$($_.value)" }
If ($_.key -eq "CommandLine") { $CommandLine = $_.value }
If ($_.key -eq "ApplicationSourcePath") { $ApplicationSourcePath = "$($Node.SourcePath)\$($_.value)" }
}
cMDTBuildApplication $Name.Replace(' ','') {
Name = $Name
Path = $Path
CommandLine = $CommandLine
ApplicationSourcePath = $ApplicationSourcePath
Enabled = "True"
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($Package in $Node.Packages) {
[string]$Name = ""
[string]$Path = ""
[string]$PackageSourcePath = ""
$Package.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Path") { $Path = "$($Node.PSDriveName):$($_.value)" }
If ($_.key -eq "PackageSourcePath") { $PackageSourcePath = "$($Node.SourcePath)\$($_.value)" }
}
cMDTBuildPackage $Name.Replace(' ','') {
Name = $Name
Path = $Path
PackageSourcePath = $PackageSourcePath
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($TaskSequence in $Node.TaskSequences) {
[string]$Name = ""
[string]$Path = ""
[string]$OSName = ""
[string]$Template = ""
[string]$ID = ""
[string]$OrgName = ""
$TaskSequence.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Path") { $Path = "$($Node.PSDriveName):\Task Sequences\$($_.value)" }
If ($_.key -eq "OSName") { $OSName = "$($Node.PSDriveName):\Operating Systems\$($_.value)" }
If ($_.key -eq "Template") { $Template = $_.value }
If ($_.key -eq "ID") { $ID = $_.value }
If ($_.key -eq "OrgName") { $OrgName = $_.value }
}
# Create Task Sequence for one OS image
cMDTBuildTaskSequence $Name.Replace(' ','') {
Name = $Name
Path = $Path
OSName = $OSName
Template = $Template
ID = $ID
OrgName = $OrgName
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
# Customize Task Sequence for one OS image
ForEach ($TSCustomize in $TaskSequence.Customize) {
[string]$Name = ""
[string]$NewName = ""
[string]$Type = ""
[string]$GroupName = ""
[string]$SubGroup = ""
[string]$Disable = ""
[string]$AddAfter = ""
[string]$Description = ""
[string]$TSVarName = "" # for MDT variable only
[string]$TSVarValue = "" # for MDT variable only
[string]$OSName = "" # for OS features only
[string]$OSFeatures = "" # for OS features only
[string]$Command = "" # for Run Command line only
[string]$StartIn = "" # for Run Command line only
[string]$SelectionProfile = "" # for Install Updates Offline only
$TSCustomize.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "NewName") { $NewName = $_.value }
If ($_.key -eq "Type") { $Type = $_.value }
If ($_.key -eq "GroupName") { $GroupName = $_.value }
If ($_.key -eq "SubGroup") { $SubGroup = $_.value }
If ($_.key -eq "Disable") { $Disable = $_.value }
If ($_.key -eq "AddAfter") { $AddAfter = $_.value }
if ($_.key -eq "Description") { $Description = $_.value }
if ($_.key -eq "TSVarName") { $TSVarName = $_.value }
if ($_.key -eq "TSVarValue") { $TSVarValue = $_.value }
If ($_.key -eq "OSName") { $OSName = $_.value }
If ($_.key -eq "OSFeatures") { $OSFeatures = $_.value }
If ($_.key -eq "Command") { $Command = $_.value }
If ($_.key -eq "StartIn") { $StartIn = $_.value }
If ($_.key -eq "SelectionProfile") { $SelectionProfile = $_.value }
}
# Current TS XML file name
$TSFile = "$($Node.PSDrivePath)\Control\$($ID)\ts.xml"
$CustomResource = $ID + '-' + $Name.Replace(' ','')
cMDTBuildTaskSequenceCustomize $CustomResource {
TSFile = $TSFile
Name = $Name
NewName = $NewName
Type = $Type
GroupName = $GroupName
SubGroup = $SubGroup
Disable = $Disable
AddAfter = $AddAfter
Description = $Description
TSVarName = $TSVarName
TSVarValue = $TSVarValue
OSName = $OSName
OSFeatures = $OSFeatures
Command = $Command
StartIn = $StartIn
SelectionProfile = $SelectionProfile
PSDriveName = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
}
}
}
ForEach ($CustomSetting in $Node.CustomSettings) {
[string]$Name = ""
[string]$SourcePath = ""
[string[]]$TestFiles = ""
$CustomSetting.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "SourcePath") { $SourcePath = "$($Node.SourcePath)\$($_.value)" }
If ($_.key -eq "TestFiles") { $TestFiles = $_.value }
}
cMDTBuildCustomize $Name.Replace(' ','') {
Name = $Name
SourcePath = $SourcePath
Path = $Node.PSDrivePath
TestFiles = $TestFiles
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
ForEach ($IniFile in $Node.CustomizeIniFiles) {
[string]$Name = ""
[string]$Path = ""
[string]$Company = ""
[string]$TimeZomeName = ""
[string]$WSUSServer = ""
[string]$UserLocale = ""
[string]$KeyboardLocale = ""
$IniFile.GetEnumerator() | % {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Path") { $Path = "$($Node.PSDrivePath)$($_.value)" }
If ($_.key -eq "Company") { $Company = $_.value }
If ($_.key -eq "TimeZoneName") { $TimeZoneName = $_.value }
If ($_.key -eq "WSUSServer") { $WSUSServer = $_.value }
If ($_.key -eq "UserLocale") { $UserLocale = $_.value }
If ($_.key -eq "KeyboardLocale") { $KeyboardLocale = $_.value }
}
If ($Company) { $Company = "_SMSTSORGNAME=$($Company)" } Else { $Company = ";_SMSTSORGNAME=" }
If ($TimeZoneName) { $TimeZoneName = "TimeZoneName=$($TimeZoneName)" } Else { $TimeZoneName = ";TimeZoneName=" }
If ($WSUSServer) { $WSUSServer = "WSUSServer=$($WSUSServer)" } Else { $WSUSServer = ";WSUSServer=" }
If ($UserLocale) { $UserLocale = "UserLocale=$($UserLocale)" } Else { $UserLocale = ";UserLocale=" }
If ($KeyboardLocale) { $KeyboardLocale = "KeyboardLocale=$($KeyboardLocale)" } Else { $KeyboardLocale = ";KeyboardLocale=" }
If ($Name -eq "CustomSettingsIni") {
cMDTBuildCustomSettingsIni ini {
Path = $Path
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
Content = @"
[Settings]
Priority=Serialnumber,Default
[Default]
$($Company)
OSInstall=Y
HideShell=YES
ApplyGPOPack=NO
UserDataLocation=NONE
DoNotCreateExtraPartition=YES
JoinWorkgroup=WORKGROUP
$($TimeZoneName)
$($WSUSServer)
;SLShare=%DeployRoot%\Logs
FinishAction=SHUTDOWN
;Set keyboard layout
$($UserLocale)
$($KeyboardLocale)
;Exclude updates that are already included in W7 Convenience update, but flagged incorrectly on Microsoft Update
WUMU_ExcludeKB1=2965788
WUMU_ExcludeKB2=2984976
WUMU_ExcludeKB3=3126446
WUMU_ExcludeKB4=3075222
WUMU_ExcludeKB5=3069762
WUMU_ExcludeKB6=3036493
WUMU_ExcludeKB7=3067904
WUMU_ExcludeKB8=3035017
WUMU_ExcludeKB9=3003743
WUMU_ExcludeKB10=3039976
WUMU_ExcludeKB11=2862330
WUMU_ExcludeKB12=2529073
ComputerBackupLocation=NETWORK
BackupShare=\\$($Node.NodeName)\$($Node.PSDriveShareName)
BackupDir=Captures
;BackupFile=#left("%TaskSequenceID%", len("%TaskSequenceID%")-3) & year(date) & right("0" & month(date), 2) & right("0" & day(date), 2)#.wim
;DoCapture=YES
;Disable all wizard pages
SkipAdminPassword=YES
SkipApplications=YES
SkipBitLocker=YES
SkipComputerBackup=YES
SkipComputerName=YES
SkipDomainMembership=YES
SkipFinalSummary=YES
SkipLocaleSelection=YES
SkipPackageDisplay=YES
SkipProductKey=YES
SkipRoles=YES
SkipSummary=YES
SkipTimeZone=YES
SkipUserData=YES
SkipTaskSequence=NO
SkipCapture=NO
"@
}
}
If ($Name -eq "BootstrapIni") {
cMDTBuildBootstrapIni ini {
Path = $Path
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
Content = @"
[Settings]
Priority=Default
[Default]
DeployRoot=\\$($Node.NodeName)\$($Node.PSDriveShareName)
SkipBDDWelcome=YES
;MDT Connect Account
UserID=$($Credentials.UserName)
UserPassword=$($Credentials.GetNetworkCredential().password)
UserDomain=$($Node.NodeName)
"@
}
}
}
ForEach ($Image in $Node.BootImage) {
[string]$Version = ""
[string]$ExtraDirectory = ""
[string]$BackgroundFile = ""
[string]$LiteTouchWIMDescription = ""
$Image.GetEnumerator() | % {
If ($_.key -eq "Version") { $Version = $_.value }
If ($_.key -eq "ExtraDirectory") { $ExtraDirectory = $_.value }
If ($_.key -eq "BackgroundFile") { $BackgroundFile = $_.value }
If ($_.key -eq "LiteTouchWIMDescription") { $LiteTouchWIMDescription = $_.value }
}
cMDTBuildUpdateBootImage updateBootImage {
Version = $Version
PSDeploymentShare = $Node.PSDriveName
PSDrivePath = $Node.PSDrivePath
ExtraDirectory = $ExtraDirectory
BackgroundFile = $BackgroundFile
LiteTouchWIMDescription = $LiteTouchWIMDescription
DependsOn = "[cMDTBuildDirectory]DeploymentFolder"
}
}
cNtfsPermissionEntry AssignPermissionsMDT {
Ensure = "Present"
Path = $Node.PSDrivePath
Principal = "$($Node.NodeName)\$($Credentials.UserName)"
AccessControlInformation = @(
cNtfsAccessControlInformation {
AccessControlType = "Allow"
FileSystemRights = "ReadAndExecute"
Inheritance = "ThisFolderSubfoldersAndFiles"
NoPropagateInherit = $false
}
)
DependsOn = "[cMDTBuildPersistentDrive]DeploymentPSDrive"
}
cNtfsPermissionEntry AssignPermissionsCaptures {
Ensure = "Present"
Path = "$($Node.PSDrivePath)\Captures"
Principal = "$($Node.NodeName)\$($Credentials.UserName)"
AccessControlInformation = @(
cNtfsAccessControlInformation {
AccessControlType = "Allow"
FileSystemRights = "Modify"
Inheritance = "ThisFolderSubfoldersAndFiles"
NoPropagateInherit = $false
}
)
DependsOn = "[cMDTBuildPersistentDrive]DeploymentPSDrive"
}
}
}
#Get password for MDT Local Account
$Cred = Get-Credential -UserName SVCMDTConnect001 -Message "Enter password for Local MDT Account"
#Get configuration data
#[hashtable]$ConfigurationData = Get-ConfigurationData -ConfigurationData "$PSScriptRoot\Deploy_MDT_Server_ConfigurationData_Lite.psd1" # Only Windows 10 x86 Evaluation
[hashtable]$ConfigurationData = Get-ConfigurationData -ConfigurationData "$PSScriptRoot\Deploy_MDT_Server_ConfigurationData.psd1"
#Create DSC MOF job
DeployMDTServerContract -OutputPath "$PSScriptRoot\MDT-Deploy_MDT_Server" -ConfigurationData $ConfigurationData -Credentials $Cred
#Set DSC LocalConfigurationManager
$winrmArgs = 'set winrm/config @{MaxEnvelopeSizekb="8192"}'
start-process "winrm" -ArgumentList $winrmArgs -NoNewWindow
Set-DscLocalConfigurationManager -Path "$PSScriptRoot\MDT-Deploy_MDT_Server" -Verbose
#Start DSC MOF job
Start-DscConfiguration -Wait -Force -Verbose -ComputerName "$env:computername" -Path "$PSScriptRoot\MDT-Deploy_MDT_Server"
#Set data deduplication
#Enable-DedupVolume -Volume "E:"
#Set-DedupVolume -Volume "E:" -MinimumFileAgeDays 1
Write-Output ""
Write-Output "Deploy MDT Server Builder completed!"
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Deploy/Import-ISO.ps1
|
Import-ISO.ps1
|
###
# Script for prepare Windows distributives
#
# 1. Download source Windows ISO from VLSC, MSDN on Evaluation portals
# 2. Save to folders on MDT server or File server:
# \\server\ISO
# + Windows 10
# + 14393.0.160715-1616.RS1_RELEASE_CLIENTENTERPRISEEVAL_OEMRET_X86FRE_EN-US.ISO
# + Windows 2016
# + en_windows_server_2016_x64_dvd_9718492.iso
# [...]
# 3. Run this script as Administrator and get info of the images:
# Import-ISO.ps1 -ISOPath '\\server\ISO' -Verbose
# 4. Edit parameters at TaskSequences section of the Deploy_MDT_Server_ConfigurationData.psd1:
# TaskSequences = @(
# @{
# Ensure = "Present"
# Name = "Windows 7 x86"
# Path = "Windows 7"
# OSName = "Windows 7\Windows 7 ENTERPRISE in Windows 7 x86 install.wim"
# [...]
# 5. Select needed images for your Build Lab ($destinations)
# 6. Import Windows sources from ISO:
# Import-ISO.ps1 -ISOPath '\\server\ISO' -Unpack -Verbose
#
# Author: @sundmoon (https://github.com/sundmoon)
#
###
[CmdletBinding()]
param(
[parameter(Mandatory = $true, HelpMessage="Enter Source path for ISO files directory tree (local folder or file share name)")]
[String]$ISOPath,
[parameter(Mandatory = $false)]
[String]$dstPath = 'E:\Source',
[switch]$Unpack
)
$destinations = @(
@{
Name = "Windows 7 ENTERPRISE"
Lang = "Russian"
Arch = "x32"
Build = "59024"
Dest = "Windows7x86"
}
@{
Name = "Windows 7 ENTERPRISE"
Lang = "Russian"
Arch = "x64"
Build = "59028"
Dest = "Windows7x64"
}
@{
Name = "Windows 8.1 Enterprise"
Lang = "Russian"
Arch = "x32"
Build = "84253"
Dest = "Windows81x86"
}
@{
Name = "Windows 8.1 Enterprise"
Lang = "Russian"
Arch = "x64"
Build = "84254"
Dest = "Windows81x64"
}
@{
Name = "Windows 10 Enterprise"
Lang = "Russian"
Arch = "x32"
Build = "27096"
Dest = "Windows10x86"
}
@{
Name = "Windows 10 Enterprise"
Lang = "Russian"
Arch = "x64"
Build = "27097"
Dest = "Windows10x64"
}
@{
Name = "Windows Server 2012 R2 SERVERSTANDARD"
Lang = "English"
Arch = "x64"
Build = "82891"
Dest = "Windows2012R2"
}
@{
Name = "Windows Server 2016 SERVERSTANDARD"
Lang = "English"
Arch = "x64"
Build = "30350"
Dest = "Windows2016"
}
)
if (!(Test-Path -Path $ISOPath)) {
Write-Warning -Message "Could not find ISO store at $ISOPath. Aborting..."
Break
}
#best effort to parse conventional iso names for meaningful tokens, may not match all possible iso names
function Get-ISOToken {
param (
[string]$FullName
)
#you may add your languages here or amend the logic to encompass more complex variants
$Lang = switch -regex ($FullName) {
'\\en_windows_|_English_' {'English'}
'\\ru_windows_|_Russian_' {'Russian'}
default {'Unknown/Custom'}
}
#extracting 5 or more sequential digits
[regex]$rx='\d{5,}'
$Build = $rx.Match($FullName).value
#mining for Arch
$x64 = $FullName -match 'x64' -or $FullName -match '64BIT'
$x32 = $FullName -match 'x32' -or $FullName -match 'x86' -or $FullName -match '32BIT'
If ($x64 -and $x32) { $Arch = 'x32_x64' }
elseif ($x64) { $Arch = 'x64' }
elseif ($x32) { $Arch = 'x32' }
@{
Lang = $Lang
Arch = $Arch
Build = $Build
}
}
function Get-ISO
{
[cmdletbinding()]
param (
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[System.IO.FileInfo[]]$ISO,
[switch]$Unpack
)
process {
Mount-DiskImage -ImagePath $PSItem.FullName
$ISOImage = Get-DiskImage -ImagePath $PSItem.fullname | Get-Volume
$ISODrive = [string]$ISOImage.DriveLetter+':'
$InstallImage = "$ISODrive\sources\install.wim"
if (!(Test-Path -Path $InstallImage ))
{
Write-Warning -Message "Could not find install.wim in $($PSItem.FullName)"
}
else
{
Write-Verbose -Message "Processing $PSItem"
#assuming wim image format, don't mess with esd, swm etc. for now
$images = Get-WindowsImage -ImagePath $ISODrive\sources\install.wim
Write-Verbose -Message "Images count: $($images.count)"
foreach ($image in $images)
{
$tokens = Get-ISOToken $PSItem.FullName
[PSCustomObject]@{
'FullName' = $PSItem.FullName
'Name' = $image.ImageName
'Language' = $tokens['Lang']
'Arch' = $tokens['Arch']
'Build' = $tokens['Build']
'ImageIndex' = $image.ImageIndex
'ImageSize' = "{0:N2}" -f ($image.ImageSize / 1GB) + " Gb"
}
#unpack images to MDT source folder
if ($Unpack)
{
foreach ($dst in $destinations) {
$dst.GetEnumerator() | ForEach-Object {
If ($_.key -eq "Name") { $Name = $_.value }
If ($_.key -eq "Lang") { $Lang = $_.value }
If ($_.key -eq "Arch") { $Arch = $_.value }
If ($_.key -eq "Build") { $Build = $_.value }
If ($_.key -eq "Dest") { $Dest = $_.value }
}
if ($Name -eq $image.ImageName -and $Lang -eq $tokens['Lang'] -and $Arch -eq $tokens['Arch'] -and $Build -eq $tokens['Build'])
{
Write-Output "Unpack $Name from $($PSItem.FullName) to $dstPath\$Dest"
if (Test-Path $dstPath\$Dest)
{
Write-Warning "Remove directory $dstPath\$Dest"
Remove-Item $dstPath\$Dest -Recurse -Force
}
New-Item $dstPath\$Dest -ItemType Directory
Copy-Item -Path "$ISODrive\*" -Destination $dstPath\$Dest -Recurse
Write-Output "Done!"
}
}
}
}
}
Dismount-DiskImage -ImagePath $PSItem.fullname
}
}
$ISO = Get-ChildItem $ISOPath -Recurse -Filter *.iso
$ISO | Get-ISO -Unpack:$Unpack -Verbose
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildUpdateBootImage.ps1
|
Example-cMDTBuildUpdateBootImage.ps1
|
#
# cMDTBuildUpdateBootImage Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildUpdateBootImage updateBootImage {
Version = "1.0"
PSDeploymentShare = $PSDriveName
PsDrivePath = $PSDrivePath
ExtraDirectory = "Extra"
BackgroundFile = "%INSTALLDIR%\Samples\Background.bmp"
LiteTouchWIMDescription = "MDT Build Lab"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildBootstrapIni.ps1
|
Example-cMDTBuildBootstrapIni.ps1
|
#
# cMDTBuildBootstrapIni Example
#
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildBootstrapIni ini {
Ensure = "Present"
Path = "$($PSDrivePath)\Control\Bootstrap.ini"
Content = @"
[Settings]
Priority=Default
[Default]
DeployRoot=\\$($ComputerName)\DeploymentShare$
SkipBDDWelcome=YES
;MDT Connect Account
UserID=$($UserName)
UserPassword=$($Password)
UserDomain=$($env:COMPUTERNAME)
"@
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildPersistentDrive.ps1
|
Example-cMDTBuildPersistentDrive.ps1
|
#
# cMDTBuildPersistentDrive Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
$ComputerName = "$env:computername"
Configuration MDTServer
{
cMDTBuildPersistentDrive DeploymentPSDrive {
Ensure = "Present"
Name = $PSDriveName
Path = $PSDrivePath
Description = "MDT Build Share"
NetworkPath = "\\$ComputerName\DeploymentShare$"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildCustomize.ps1
|
Example-cMDTBuildCustomize.ps1
|
#
# cMDTBuildCustomize Example
#
$PSDrivePath = "E:\MDTBuildLab"
$SourcePath = "E:\Source"
Configuration MDTServer
{
cMDTBuildCustomize PEExtraFiles {
Ensure = "Present"
Name = "PEExtraFiles"
Path = $PSDrivePath
SourcePath = "$($SourcePath)/PEExtraFiles"
TestFiles = @("Script1.vbs", "Script2.vbs")
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildCustomSettingsIni.ps1
|
Example-cMDTBuildCustomSettingsIni.ps1
|
#
# cMDTBuildCustomSettingsIni Example
#
$ComputerName = "$env:computername"
$PSDrivePath = "E:\MDTBuildLab"
$Company = "MDT Build Lab"
$TimeZoneName = "Ekaterinburg Standard Time"
$WSUSServer = "http://fqdn:port"
$UserLocale = "en-US"
$KeyboardLocale = "en-US;ru-RU"
Configuration MDTServer
{
cMDTBuildCustomSettingsIni ini {
Ensure = "Present"
Path = "$($PSDrivePath)\Control\CustomSettings.ini"
Content = @"
[Settings]
Priority=Init,Default
Properties=VMNameAlias
[Init]
UserExit=ReadKVPData.vbs
VMNameAlias=#SetVMNameAlias()#
[Default]
$($Company)
OSInstall=Y
HideShell=YES
ApplyGPOPack=NO
UserDataLocation=NONE
DoNotCreateExtraPartition=YES
JoinWorkgroup=WORKGROUP
$($TimeZoneName)
$($WSUSServer)
;SLShare=%DeployRoot%\Logs
TaskSequenceID=%VMNameAlias%
FinishAction=SHUTDOWN
;Set keyboard layout
$($UserLocale)
$($KeyboardLocale)
ComputerBackupLocation=NETWORK
BackupShare=\\$($ComputerName)\DeploymentShare$
BackupDir=Captures
BackupFile=#left("%TaskSequenceID%", len("%TaskSequenceID%")-3) & year(date) & right("0" & month(date), 2) & right("0" & day(date), 2)#.wim
DoCapture=YES
;Disable all wizard pages
SkipAdminPassword=YES
SkipApplications=YES
SkipBitLocker=YES
SkipCapture=YES
SkipComputerBackup=YES
SkipComputerName=YES
SkipDomainMembership=YES
SkipFinalSummary=YES
SkipLocaleSelection=YES
SkipPackageDisplay=YES
SkipProductKey=YES
SkipRoles=YES
SkipSummary=YES
SkipTimeZone=YES
SkipUserData=YES
SkipTaskSequence=YES
"@
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildApplication.ps1
|
Example-cMDTBuildApplication.ps1
|
#
# cMDTBuildApplication Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildApplication WMF5 {
Ensure = "Present"
Name = "Install - Windows Management Framework 5.0 - x64"
Path = "\Applications\Core\Microsoft"
CommandLine = "wusa.exe Win8.1AndW2K12R2-KB3134758-x64.msu /quiet /norestart"
ApplicationSourcePath = "WMF50x64"
Enabled = "True"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildPackage.ps1
|
Example-cMDTBuildPackage.ps1
|
#
# cMDTBuildPackage Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildPackage KB3125574_x64 {
Ensure = "Present"
Name = "Package_for_KB3125574 neutral amd64 6.1.4.4"
Path = "Packages\Windows 7"
PackageSourcePath = "Update for Windows 7 for x64-based Systems (KB3125574)"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildSelectionProfile.ps1
|
Example-cMDTBuildSelectionProfile.ps1
|
#
# cMDTBuildSelectionProfile Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildSelectionProfile Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Comments = "Packages for Windows 10 x64"
IncludePath = "Packages\Windows 10 x64"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildDirectory.ps1
|
Example-cMDTBuildDirectory.ps1
|
#
# cMDTBuildDirectory Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildDirectory Windows10 {
Ensure = "Present"
Name = "Windows 10"
Path = "$($PSDriveName):\Operating Systems"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildTaskSequenceCustomize.ps1
|
Example-cMDTBuildTaskSequenceCustomize.ps1
|
#
# cMDTBuildTaskSequenceCustomize Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
$TSID = "REFW10X64-001"
$TSFile = "$($PSDrivePath)\Control\$($TSID)\ts.xml"
Configuration MDTServer
{
cMDTBuildTaskSequenceCustomize AddFeatures {
TSFile = $TSFile
Name = "Install - Microsoft NET Framework 3.5.1"
Type = "Install Roles and Features"
GroupName = "State Restore"
SubGroup = "Custom Tasks (Pre-Windows Update)"
OSName = "Windows 10"
OSFeatures = "NetFx3,TelnetClient"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildPreReqs.ps1
|
Example-cMDTBuildPreReqs.ps1
|
#
# cMDTBuildPreReqs Example
#
$SourcePath = "E:\Source"
Configuration MDTServer
{
cMDTBuildPreReqs MDTPreReqs {
Ensure = "Present"
DownloadPath = "$SourcePath"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildOperatingSystem.ps1
|
Example-cMDTBuildOperatingSystem.ps1
|
#
# cMDTBuildOperatingSystem Example
#
$SourcePath = "E:\Source"
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildOperatingSystem Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Path = "Windows 10"
SourcePath = "$SourcePath\Windows10x64"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Examples/Example-cMDTBuildTaskSequence.ps1
|
Example-cMDTBuildTaskSequence.ps1
|
#
# cMDTBuildTaskSequence Example
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildTaskSequence Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Path = "Windows 10"
OSName = "Windows 10\Windows 10 Enterprise in Windows 10 x64 install.wim"
OrgName = "BuildLab"
Template = "Client.xml"
ID = "REFW10X64-001"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildTaskSequenceCustomize.ps1
|
Test-cMDTBuildTaskSequenceCustomize.ps1
|
#
# cMDTBuildTaskSequenceCustomize Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
$TSID = "REFW10X64-001"
$TSFile = "$($PSDrivePath)\Control\$($TSID)\ts.xml"
Configuration MDTServer
{
cMDTBuildTaskSequenceCustomize AddFeatures {
TSFile = $TSFile
Name = "Install - Microsoft NET Framework 3.5.1"
Type = "Install Roles and Features"
GroupName = "State Restore"
SubGroup = "Custom Tasks (Pre-Windows Update)"
OSName = "Windows 10"
OSFeatures = "NetFx3,TelnetClient"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildPersistentDrive.ps1
|
Test-cMDTBuildPersistentDrive.ps1
|
#
# cMDTBuildPersistentDrive Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
$ComputerName = "$env:computername"
Configuration MDTServer
{
cMDTBuildPersistentDrive DeploymentPSDrive {
Ensure = "Present"
Name = $PSDriveName
Path = $PSDrivePath
Description = "MDT Build Share"
NetworkPath = "\\$ComputerName\DeploymentShare$"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildUpdateBootImage.ps1
|
Test-cMDTBuildUpdateBootImage.ps1
|
#
# cMDTBuildUpdateBootImage Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildUpdateBootImage updateBootImage {
Version = "1.0"
PSDeploymentShare = $PSDriveName
PsDrivePath = $PSDrivePath
ExtraDirectory = "Extra"
BackgroundFile = "%INSTALLDIR%\Samples\Background.bmp"
LiteTouchWIMDescription = "MDT Build Lab"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildBootstrapIni.ps1
|
Test-cMDTBuildBootstrapIni.ps1
|
#
# cMDTBuildBootstrapIni Test
#
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildBootstrapIni ini {
Ensure = "Present"
Path = "$($PSDrivePath)\Control\Bootstrap.ini"
Content = @"
[Settings]
Priority=Default
[Default]
DeployRoot=\\$($ComputerName)\DeploymentShare$
SkipBDDWelcome=YES
;MDT Connect Account
UserID=$($UserName)
UserPassword=$($Password)
UserDomain=$($env:COMPUTERNAME)
"@
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildDirectory.ps1
|
Test-cMDTBuildDirectory.ps1
|
#
# cMDTBuildDirectory Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildDirectory Windows10 {
Ensure = "Present"
Name = "Windows 10"
Path = "$($PSDriveName):\Operating Systems"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildPackage.ps1
|
Test-cMDTBuildPackage.ps1
|
#
# cMDTBuildPackage Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildPackage KB3125574_x64 {
Ensure = "Present"
Name = "Package_for_KB3125574 neutral amd64 6.1.4.4"
Path = "Packages\Windows 7"
PackageSourcePath = "Update for Windows 7 for x64-based Systems (KB3125574)"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildOperatingSystem.ps1
|
Test-cMDTBuildOperatingSystem.ps1
|
#
# cMDTBuildOperatingSystem Test
#
$SourcePath = "E:\Source"
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildOperatingSystem Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Path = "Windows 10"
SourcePath = "$SourcePath\Windows10x64"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildTaskSequence.ps1
|
Test-cMDTBuildTaskSequence.ps1
|
#
# cMDTBuildTaskSequence Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildTaskSequence Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Path = "Windows 10"
OSName = "Windows 10\Windows 10 Enterprise in Windows 10 x64 install.wim"
OrgName = "BuildLab"
Template = "Client.xml"
ID = "REFW10X64-001"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildPreReqs.ps1
|
Test-cMDTBuildPreReqs.ps1
|
#
# cMDTBuildPreReqs Test
#
$SourcePath = "E:\Source"
Configuration MDTServer
{
cMDTBuildPreReqs MDTPreReqs {
Ensure = "Present"
DownloadPath = "$SourcePath"
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildApplication.ps1
|
Test-cMDTBuildApplication.ps1
|
#
# cMDTBuildApplication Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildApplication WMF5 {
Ensure = "Present"
Name = "Install - Windows Management Framework 5.0 - x64"
Path = "\Applications\Core\Microsoft"
CommandLine = "wusa.exe Win8.1AndW2K12R2-KB3134758-x64.msu /quiet /norestart"
ApplicationSourcePath = "WMF50x64"
Enabled = "True"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildCustomize.ps1
|
Test-cMDTBuildCustomize.ps1
|
#
# cMDTBuildCustomize Test
#
$PSDrivePath = "E:\MDTBuildLab"
$SourcePath = "E:\Source"
Configuration MDTServer
{
cMDTBuildCustomize PEExtraFiles {
Ensure = "Present"
Name = "PEExtraFiles"
Path = $PSDrivePath
SourcePath = "$($SourcePath)/PEExtraFiles"
TestFiles = @("Script1.vbs", "Script2.vbs")
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildCustomSettingsIni.ps1
|
Test-cMDTBuildCustomSettingsIni.ps1
|
#
# cMDTBuildCustomSettingsIni Test
#
$ComputerName = "$env:computername"
$PSDrivePath = "E:\MDTBuildLab"
$Company = "MDT Build Lab"
$TimeZoneName = "Ekaterinburg Standard Time"
$WSUSServer = "http://fqdn:port"
$UserLocale = "en-US"
$KeyboardLocale = "en-US;ru-RU"
Configuration MDTServer
{
cMDTBuildCustomSettingsIni ini {
Ensure = "Present"
Path = "$($PSDrivePath)\Control\CustomSettings.ini"
Content = @"
[Settings]
Priority=Init,Default
Properties=VMNameAlias
[Init]
UserExit=ReadKVPData.vbs
VMNameAlias=#SetVMNameAlias()#
[Default]
$($Company)
OSInstall=Y
HideShell=YES
ApplyGPOPack=NO
UserDataLocation=NONE
DoNotCreateExtraPartition=YES
JoinWorkgroup=WORKGROUP
$($TimeZoneName)
$($WSUSServer)
;SLShare=%DeployRoot%\Logs
TaskSequenceID=%VMNameAlias%
FinishAction=SHUTDOWN
;Set keyboard layout
$($UserLocale)
$($KeyboardLocale)
ComputerBackupLocation=NETWORK
BackupShare=\\$($ComputerName)\DeploymentShare$
BackupDir=Captures
BackupFile=#left("%TaskSequenceID%", len("%TaskSequenceID%")-3) & year(date) & right("0" & month(date), 2) & right("0" & day(date), 2)#.wim
DoCapture=YES
;Disable all wizard pages
SkipAdminPassword=YES
SkipApplications=YES
SkipBitLocker=YES
SkipCapture=YES
SkipComputerBackup=YES
SkipComputerName=YES
SkipDomainMembership=YES
SkipFinalSummary=YES
SkipLocaleSelection=YES
SkipPackageDisplay=YES
SkipProductKey=YES
SkipRoles=YES
SkipSummary=YES
SkipTimeZone=YES
SkipUserData=YES
SkipTaskSequence=YES
"@
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Tests/Test-cMDTBuildSelectionProfile.ps1
|
Test-cMDTBuildSelectionProfile.ps1
|
#
# cMDTBuildSelectionProfile Test
#
$PSDriveName = "MDT001"
$PSDrivePath = "E:\MDTBuildLab"
Configuration MDTServer
{
cMDTBuildSelectionProfile Win10x64 {
Ensure = "Present"
Name = "Windows 10 x64"
Comments = "Packages for Windows 10 x64"
IncludePath = "Packages\Windows 10 x64"
PSDriveName = $PSDriveName
PSDrivePath = $PSDrivePath
}
}
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Sources/Config-NetFwRules.ps1
|
Config-NetFwRules.ps1
|
Enable-NetFirewallRule -DisplayGroup “File and Printer Sharing” -Verbose
Enable-NetFirewallRule -DisplayGroup “File and Printer Sharing over SMBDirect” -Verbose
Enable-NetFirewallRule -DisplayGroup “Remote Desktop” -Verbose
Enable-NetFirewallRule -DisplayGroup “Remote Shutdown” -Verbose
Enable-NetFirewallRule -DisplayGroup “Windows Management Instrumentation (WMI)” -Verbose
|
PowerShellCorpus/PowerShellGallery/cMDTBuildLab/1.3.0/Sources/Customize-DefaultProfile.ps1
|
Customize-DefaultProfile.ps1
|
$winVer = (Get-CimInstance -ClassName win32_operatingsystem).version
if ($winVer -like '6.3*') {
# Windows 8.1 / Windows 2012 R2
Invoke-Item "Z:\Applications\Configure - Set Start Layout\Theme01.deskthemepack"
Import-StartLayout -LayoutPath "Z:\Applications\Configure - Set Start Layout\Default_Start_Screen_Layout.bin" -MountPath $env:SystemDrive\
}
elseif ($winVer -like '10.0*') {
# Windows 10
Import-StartLayout -LayoutPath "Z:\Applications\Configure - Set Start Layout\Default_Start_Screen_Layout_10.bin" -MountPath $env:SystemDrive\
}
|
PowerShellCorpus/PowerShellGallery/Posh-SSH/1.7.7/PortForward.ps1
|
PortForward.ps1
|
##############################################################################################
# SSH Port Forwarding
<#
.Synopsis
Redirects traffic from a local port to a remote host and port via a SSH Session.
.DESCRIPTION
Redirects TCP traffic from a local port to a remote host and port via a SSH Session.
.EXAMPLE
Forward traffic from 0.0.0.0:8081 to 10.10.10.1:80 thru a SSH Session
PS C:\> New-SSHLocalPortForward -Index 0 -LocalAdress 0.0.0.0 -LocalPort 8081 -RemoteAddress 10.10.10.1 -RemotePort 80 -Verbose
VERBOSE: Finding session with Index 0
VERBOSE: 0
VERBOSE: Adding Forward Port Configuration to session 0
VERBOSE: Starting the Port Forward.
VERBOSE: Forwarding has been started.
PS C:\> Invoke-WebRequest -Uri http://localhost:8081
StatusCode : 200
StatusDescription : OK
Content :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="/javascript/scri...
RawContent : HTTP/1.1 200 OK
Expires: Tue, 16 Apr 2013 03:43:18 GMT,Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: max-age=180000,no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Set-Cookie: PHPSESS...
Forms : {iform}
Headers : {[Expires, Tue, 16 Apr 2013 03:43:18 GMT,Thu, 19 Nov 1981 08:52:00 GMT], [Cache-Control, max-age=180000,no-store, no-cache,
must-revalidate, post-check=0, pre-check=0], [Set-Cookie, PHPSESSID=d53d3dc62ffac241112bcfd16af36bb8; path=/], [Pragma, no-cache]...}
Images : {}
InputFields : {@{innerHTML=; innerText=; outerHTML=<INPUT onchange=clearError(); onclick=clearError(); tabIndex=1 id=usernamefld class="formfld user"
name=usernamefld>; outerText=; tagName=INPUT; onchange=clearError();; onclick=clearError();; tabIndex=1; id=usernamefld; class=formfld
user; name=usernamefld}, @{innerHTML=; innerText=; outerHTML=<INPUT onchange=clearError(); onclick=clearError(); tabIndex=2
id=passwordfld class="formfld pwd" type=password value="" name=passwordfld>; outerText=; tagName=INPUT; onchange=clearError();;
onclick=clearError();; tabIndex=2; id=passwordfld; class=formfld pwd; type=password; value=; name=passwordfld}, @{innerHTML=;
innerText=; outerHTML=<INPUT tabIndex=3 class=formbtn type=submit value=Login name=login>; outerText=; tagName=INPUT; tabIndex=3;
class=formbtn; type=submit; value=Login; name=login}}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 5932
#>
function New-SSHLocalPortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true,
Position=1)]
[String]
$BoundHost,
[Parameter(Mandatory=$true,
Position=2)]
[Int32]
$BoundPort,
[Parameter(Mandatory=$true,
Position=3)]
[String]
$RemoteAddress,
[Parameter(Mandatory=$true,
Position=4)]
[Int32]
$RemotePort,
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true,
Position=0)]
[Alias("Session")]
[SSH.SSHSession]
$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SSHSession
}
'Index'
{
$sess = Get-SSHSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
}
Process
{
$ports = $ToProcess.Session.ForwardedPorts
foreach($p in $ports)
{
if (($p.BoundPort -eq $BoundPort) -and ($p.BoundHost -eq $BoundHost))
{
Write-Error -Message "A forward port already exists for port $($BoundPort) with address $($LocalAdress)"
return
}
}
# Initialize the ForwardPort Object
$SSHFWP = New-Object Renci.SshNet.ForwardedPortLocal($BoundHost, $BoundPort, $RemoteAddress, $RemotePort)
# Add the forward port object to the session
Write-Verbose -message "Adding Forward Port Configuration to session $($ToProcess.Index)"
$ToProcess.session.AddForwardedPort($SSHFWP)
Write-Verbose -message "Starting the Port Forward."
$SSHFWP.start()
Write-Verbose -message "Forwarding has been started."
}
End{}
}
<#function New-SSHRemotePortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true)]
[String]$LocalAdress = '127.0.0.1',
[Parameter(Mandatory=$true)]
[Int32]$LocalPort,
[Parameter(Mandatory=$true)]
[String]$RemoteAddress,
[Parameter(Mandatory=$true)]
[Int32]$RemotePort,
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true)]
[Alias("Session")]
[SSH.SSHSession]$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true)]
[Int32]$Index = $null
)
Begin
{
# Initialize the ForwardPort Object
$SSHFWP = New-Object Renci.SshNet.ForwardedPortRemote($LocalAdress, $LocalPort, $RemoteAddress, $RemotePort)
}
Process
{
if ($PSCmdlet.ParameterSetName -eq 'Index')
{
Write-Verbose "Finding session with Index $Index"
foreach($session in $Global:SshSessions)
{
Write-Verbose $session.index
if ($session.index -eq $Index)
{
# Add the forward port object to the session
Write-Verbose "Adding Forward Port Configuration to session $Index"
$session.session.AddForwardedPort($SSHFWP)
Write-Verbose "Starting the Port Forward."
$SSHFWP.start()
Write-Verbose "Forwarding has been started."
}
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'Session')
{
if ($SSHSession -in $Global:SshSessions)
{
# Add the forward port object to the session
Write-Verbose "Adding Forward Port Configuration to session $($SSHSession.index)"
$SSHSession.session.AddForwardedPort($SSHFWP)
Write-Verbose "Starting the Port Forward."
$SSHFWP.start()
Write-Verbose "Forwarding has been started."
}
else
{
Write-Error "The Session does not appear in the list of created sessions."
}
}
}
End{}
}
#>
<#
.Synopsis
Establishes a Dynamic Port Forward thru a stablished SSH Session.
.DESCRIPTION
Dynamic port forwarding is a transparent mechanism available for applications, which
support the SOCKS4 or SOCKS5 client protoco. In windows for best results the local address
to bind to should be the IP of the network interface.
.EXAMPLE
New-SSHDynamicPortForward -LocalAdress 192.168.28.131 -LocalPort 8081 -Index 0 -Verbose
VERBOSE: Finding session with Index 0
VERBOSE: 0
VERBOSE: Adding Forward Port Configuration to session 0
VERBOSE: Starting the Port Forward.
VERBOSE: Forwarding has been started.
#>
function New-SSHDynamicPortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true,
Position=1)]
[String]
$BoundHost = 'localhost',
[Parameter(Mandatory=$true,
Position=2)]
[Int32]
$BoundPort,
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true,
Position=0)]
[Alias("Session")]
[SSH.SSHSession]
$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SSHSession
}
'Index'
{
$sess = Get-SSHSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
}
Process
{
$ports = $ToProcess.Session.ForwardedPorts
foreach($p in $ports)
{
if ($p.BoundHost -eq $BoundHost -and $p.BoundPort -eq $BoundPort)
{
throw "A forward port already exists for port $($BoundPort) with address $($BoundHost)"
}
}
# Initialize the ForwardPort Object
$SSHFWP = New-Object Renci.SshNet.ForwardedPortDynamic($BoundHost, $BoundPort)
# Add the forward port object to the session
Write-Verbose -message "Adding Forward Port Configuration to session $($ToProcess.Index)"
$ToProcess.session.AddForwardedPort($SSHFWP)
$ToProcess.session.KeepAliveInterval = New-TimeSpan -Seconds 30
$ToProcess.session.ConnectionInfo.Timeout = New-TimeSpan -Seconds 20
$ToProcess.session.SendKeepAlive()
[System.Threading.Thread]::Sleep(500)
Write-Verbose -message "Starting the Port Forward."
$SSHFWP.start()
Write-Verbose -message "Forwarding has been started."
}
End{}
}
<#
.Synopsis
Get a list of forwarded TCP Ports for a SSH Session
.DESCRIPTION
Get a list of forwarded TCP Ports for a SSH Session
.EXAMPLE
Get list of configured forwarded ports
PS C:\> Get-SSHPortForward -Index 0
BoundHost : 0.0.0.0
BoundPort : 8081
Host : 10.10.10.1
Port : 80
IsStarted : True
#>
function Get-SSHPortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true,
Position=0)]
[Alias("Session")]
[SSH.SSHSession]
$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SSHSession
}
'Index'
{
$sess = Get-SSHSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
}
Process
{
$ToProcess.Session.ForwardedPorts
}
End{}
}
<#
.Synopsis
Stops a configured port forward configured for a SSH Session
.DESCRIPTION
Stops a configured port forward configured for a SSH Session given the session and port number
.EXAMPLE
Stop a currently working port forward thru a SSH Session
C:\Users\Carlos> Get-SSHPortForward -Index 0
BoundHost : 192.168.1.158
BoundPort : 8081
Host : 10.10.10.1
Port : 80
IsStarted : True
C:\Users\Carlos> Stop-SSHPortForward -Index 0 -BoundPort 8081
BoundHost : 192.168.1.158
BoundPort : 8081
Host : 10.10.10.1
Port : 80
IsStarted : False
#>
function Stop-SSHPortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true,
Position=0)]
[Alias("Session")]
[SSH.SSHSession]
$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId,
[Parameter(Mandatory=$true,
Position=2)]
[Int32]
$BoundPort,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$BoundHost
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SSHSession
}
'Index'
{
$sess = Get-SSHSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
}
Process
{
$ports = $ToProcess.Session.ForwardedPorts
foreach($p in $ports)
{
if ($p.BoundPort -eq $BoundPort -and $p.BoundHost -eq $BoundHost)
{
$p.Stop()
$p
}
}
}
End{}
}#>
<#
.Synopsis
Start a configured port forward configured for a SSH Session
.DESCRIPTION
Stops a configured port forward configured for a SSH Session given the session and port number
.EXAMPLE
Stop a currently working port forward thru a SSH Session
C:\Users\Carlos> Get-SSHPortForward -Index 0
BoundHost : 192.168.1.158
BoundPort : 8081
Host : 10.10.10.1
Port : 80
IsStarted : False
C:\Users\Carlos> Start-SSHPortForward -Index 0 -BoundPort 8081
BoundHost : 192.168.1.158
BoundPort : 8081
Host : 10.10.10.1
Port : 80
IsStarted : True
#>
function Start-SSHPortForward
{
[CmdletBinding(DefaultParameterSetName="Index")]
param(
[Parameter(Mandatory=$true,
ParameterSetName = "Session",
ValueFromPipeline=$true,
Position=0)]
[Alias("Session")]
[SSH.SSHSession]
$SSHSession,
[Parameter(Mandatory=$true,
ParameterSetName = "Index",
ValueFromPipeline=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId,
[Parameter(Mandatory=$true,
Position=2)]
[Int32]
$BoundPort,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$BoundHost
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SSHSession
}
'Index'
{
$sess = Get-SSHSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
}
Process
{
$ports = $ToProcess.Session.ForwardedPorts
foreach($p in $ports)
{
if ($p.BoundPort -eq $BoundPort -and $p.BoundHost -eq $BoundHost)
{
$p.Start()
$p
}
}
}
End{}
}
|
PowerShellCorpus/PowerShellGallery/Posh-SSH/1.7.7/Sftp.ps1
|
Sftp.ps1
|
########################################################################################
# SFTP Functions
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SFTPSession
{
param(
[Parameter(Mandatory=$false,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId
)
Begin{}
Process
{
if ($SessionId.Length -gt 0)
{
foreach($i in $SessionId)
{
foreach($session in $global:SFTPSessions)
{
if ($session.SessionId -eq $i)
{
$session
}
}
}
}
else
{
# Can not reference SFTPSessions directly so as to be able
# to remove the sessions when Remove-Sftpession is used
$return_sessions = @()
foreach($s in $Global:SFTPSessions){$return_sessions += $s}
$return_sessions
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Remove-SFTPSession
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$false,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession
)
Begin{}
Process
{
if ($PSCmdlet.ParameterSetName -eq 'Index')
{
$sessions2remove = @()
foreach($i in $SessionId)
{
Write-Verbose $i
foreach($session in $Global:SFTPSessions)
{
if ($session.SessionId -eq $i)
{
$sessions2remove += $session
}
}
}
foreach($badsession in $sessions2remove)
{
Write-Verbose "Removing session $($badsession.SessionId)"
if ($badsession.session.IsConnected)
{
$badsession.session.Disconnect()
}
$badsession.session.Dispose()
$Global:SFTPSessions.Remove($badsession)
Write-Verbose "Session $($badsession.SessionId) Removed"
}
}
if ($PSCmdlet.ParameterSetName -eq 'Session')
{
$sessions2remove = @()
foreach($i in $SFTPSession)
{
foreach($ssh in $global:SFTPSessions)
{
if ($ssh -eq $i)
{
$sessions2remove += $ssh
}
}
}
foreach($badsession in $sessions2remove)
{
Write-Verbose "Removing session $($badsession.SessionId)"
if ($badsession.session.IsConnected)
{
$badsession.session.Disconnect()
}
$badsession.session.Dispose()
$Global:SFTPSessions.Remove($badsession)
Write-Verbose "Session $($badsession.SessionId) Removed"
}
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SFTPChildItem
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$false,
Position=1)]
[string]
$Path,
[Parameter(Mandatory=$false,
Position=2)]
[switch]
$Recursive
)
Begin
{
function Get-SFTPDirectoryRecursive
{
param($Path,$SFTPSession)
$total = $Sess.Session.ListDirectory($Path)
#List Files
$total | ? {$_.IsDirectory -eq $false}
#List non filtered directories
$total | ? {$_.IsDirectory -eq $true -and @('.','..') -contains $_.name}
#Get items in a path
$total | ? {$_.IsDirectory -eq $true -and @('.','..') -notcontains $_.Name } |
% {Get-SFTPDirectoryRecursive -Path $_.FullName -SFTPSession $sess}
}
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($Sess in $ToProcess)
{
if ($Path.Length -eq 0)
{
$Path = $Sess.Session.WorkingDirectory
}
else
{
$Attribs = Get-SFTPPathAttribute -SFTPSession $Sess -Path $Path
if (!$Attribs.IsDirectory)
{
throw "Specified path of $($Path) is not a directory."
}
}
if($Recursive)
{
Get-SFTPDirectoryRecursive -Path $Path -SFTPSession $Sess
}
else
{
$Sess.Session.ListDirectory($Path)
}
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Test-SFTPPath
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$Path
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
$session.Session.Exists($Path)
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Remove-SFTPItem
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$Path,
# Force the deletion of a none empty directory by recursively deleting all files in it.
[Parameter(Mandatory=$false)]
[switch]
$Force
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
if (Test-SFTPPath -SFTPSession $session -Path $Path)
{
$attr = Get-SFTPPathAttribute -SFTPSession $session -Path $Path
if ($attr.IsDirectory)
{
$content = Get-SFTPChildItem -SFTPSession $session -Path $Path
if ($content.count -gt 2 -and !$Force)
{
throw "Specified path of $($Path) is not an empty directory."
}
elseif ($Force)
{
Write-Verbose -Message "Recursively deleting $($Path)."
[SSH.SshModHelper]::DeleteDirectoryRecursive($Path, $session.Session)
return
}
}
Write-Verbose -Message "Removing $($Path)."
$session.Session.Delete($Path)
Write-Verbose -Message "$($Path) removed."
}
else
{
throw "Specified path of $($Path) does not exist."
}
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Set-SFTPLocation
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$Path
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
$Attribs = Get-SFTPPathAttribute -SFTPSession $session -Path $Path
if ($Attribs.IsDirectory)
{
Write-Verbose -Message "Changing current directory to $($Path)"
$session.Session.ChangeDirectory($Path)
Write-Verbose -Message 'Current directory changed.'
}
else
{
throw "Specified path of $($Path) is not a directory."
}
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SFTPLocation
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
$session.Session.WorkingDirectory
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Rename-SFTPFile
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
# Full path to file to rename
[Parameter(Mandatory=$true,
Position=1)]
[string]
$Path,
# New name for file.
[Parameter(Mandatory=$true,
Position=2)]
[string]
$NewName
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
$attrib = Get-SFTPPathAttribute -SFTPSession $session -Path $Path
if ($attrib.IsRegularFile)
{
$ContainerPath = Split-Path -Path $Path |ForEach-Object {$_ -replace '\\','/'}
Write-Verbose "Renaming $($Path) to $($NewName)"
$session.Session.RenameFile($Path, "$($ContainerPath)/$($NewName)")
Write-Verbose 'File renamed'
}
else
{
Write-Error -Message "The specified path $($Path) is not to a file."
}
}
}
End{}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SFTPPathAttribute
{
[CmdletBinding()]
[OutputType([Renci.SshNet.Sftp.SftpFileAttributes])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=1)]
[string]
$Path
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
if (Test-SFTPPath -SFTPSession $session -Path $Path)
{
$session.Session.GetAttributes($Path)
}
else
{
throw "Path $($Path) does not exist on the target host."
}
}
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Set-SFTPPathAttribute
{
[CmdletBinding()]
[OutputType([Renci.SshNet.Sftp.SftpFileAttributes])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=1)]
[string]
$Path,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[datetime]
$LastAccessTime,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[datetime]
$LastWriteTime,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[int]
$GroupId,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[int]
$UserId,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$GroupCanExecute,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$GroupCanRead,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$GroupCanWrite,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OthersCanExecute,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OthersCanRead,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OthersCanWrite,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OwnerCanExecute,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OwnerCanRead,
[Parameter(Mandatory=$false,
ValueFromPipeline=$true)]
[bool]
$OwnerCanWrite
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
if (Test-SFTPPath -SFTPSession $session -Path $Path)
{
$currentAttrib = $session.Session.GetAttributes($Path)
if($PSBoundParameters.ContainsKey("OwnerCanWrite"))
{
$currentAttrib.OwnerCanWrite = $OwnerCanWrite
}
if($PSBoundParameters.ContainsKey("OwnerCanRead"))
{
$currentAttrib.OwnerCanRead = $OwnerCanRead
}
if($PSBoundParameters.ContainsKey("OwnerCanExecute"))
{
$currentAttrib.OwnerCanExecute = $OwnerCanExecute
}
if($PSBoundParameters.ContainsKey("OthersCanWrite"))
{
$currentAttrib.OthersCanWrite = $OthersCanWrite
}
if($PSBoundParameters.ContainsKey("OthersCanRead"))
{
$currentAttrib.OthersCanRead = $OthersCanRead
}
if($PSBoundParameters.ContainsKey("OthersCanExecute"))
{
$currentAttrib.OthersCanExecute = $OthersCanExecute
}
if($PSBoundParameters.ContainsKey("GroupCanWrite"))
{
$currentAttrib.GroupCanWrite = $GroupCanWrite
}
if($PSBoundParameters.ContainsKey("GroupCanRead"))
{
$currentAttrib.GroupCanRead = $GroupCanRead
}
if($PSBoundParameters.ContainsKey("OwnerCanWrite"))
{
$currentAttrib.GroupCanExecute = $GroupCanExecute
}
if($PSBoundParameters.ContainsKey("UserId"))
{
$currentAttrib.UserId = $UserId
}
if($PSBoundParameters.ContainsKey("GroupId"))
{
$currentAttrib.GroupId = $GroupId
}
if($PSBoundParameters.ContainsKey("LastWriteTime"))
{
$currentAttrib.LastWriteTime = $LastWriteTime
}
if($PSBoundParameters.ContainsKey("LastAccessTime"))
{
$currentAttrib.LastAccessTime = $LastAccessTime
}
$session.Session.SetAttributes($Path, $currentAttrib)
}
else
{
throw "Path $($Path) does not exist on the target host."
}
}
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function New-SFTPSymlink
{
[CmdletBinding(DefaultParameterSetName='Index')]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[String]
$Path,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[String]
$LinkPath
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($session in $ToProcess)
{
$filepath = Test-SFTPPath -SFTPSession $session -Path $Path
$linkstatus = Test-SFTPPath -SFTPSession $session -path $LinkPath`
if (($filepath) -and (!$linkstatus))
{
try
{
Write-Verbose -Message "Creating symlink for $($Path) to $($LinkPath)"
$session.session.SymbolicLink($Path, $LinkPath)
$session.session.Get($LinkPath)
}
catch
{
Write-Error -Exception $_.Exception
}
}
else
{
if ($linkstatus)
{
Write-Error -Message "A file already exists in the path of the link $($linkstatus)"
}
if (!$filepath)
{
Write-Error -Message "The path $($Path) to link does not exist"
}
}
}
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SFTPContent
{
[CmdletBinding(DefaultParameterSetName='Index')]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[String]
$Path,
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('String', 'Byte', 'MultiLine')]
[string]
$ContentType = 'String',
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true)]
[ValidateSet('ASCII','Unicode', 'UTF7', 'UTF8', 'UTF32', 'BigEndianUnicode')]
[string]
$Encoding='UTF8'
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
# Set encoding.
switch ($Encoding)
{
'ASCII' {
$ContentEncoding = [System.Text.Encoding]::ASCII
}
'Unicode' {
$ContentEncoding = [System.Text.Encoding]::Unicode
}
'UTF7' {
$ContentEncoding = [System.Text.Encoding]::UTF7
}
'UTF8' {
$ContentEncoding = [System.Text.Encoding]::UTF8
}
'UTF32' {
$ContentEncoding = [System.Text.Encoding]::UTF32
}
'BigEndianUnicode'{
$ContentEncoding = [System.Text.Encoding]::BigEndianUnicode
}
}
}
Process
{
foreach($session in $ToProcess)
{
$attrib = Get-SFTPPathAttribute -SFTPSession $session -Path $Path
if ($attrib.IsRegularFile)
{
try
{
switch ($ContentType)
{
'String' {
$session.session.ReadAllText($Path, $ContentEncoding)
}
'Byte' {
$session.session.ReadAllBytes($Path)
}
'MultiLine' {
$session.session.ReadAllLines($Path, $Value, $ContentEncoding)
}
Default {$session.session.ReadAllBytes($Path)}
}
}
catch
{
Write-Error -Exception $_.Exception -Message "Failed to get content to file $($Path)"
}
}
else
{
Write-Error -Message "The specified path $($Path) is not to a file."
}
}
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Set-SFTPContent
{
[CmdletBinding(DefaultParameterSetName='Index')]
[OutputType([Renci.SshNet.Sftp.SftpFile])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[String]
$Path,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
$Value,
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true)]
[ValidateSet('ASCII','Unicode', 'UTF7', 'UTF8', 'UTF32', 'BigEndianUnicode')]
[string]
$Encoding='UTF8',
[switch]
$Append
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
# Set encoding.
switch ($Encoding)
{
'ASCII' {
$ContentEncoding = [System.Text.Encoding]::ASCII
}
'Unicode' {
$ContentEncoding = [System.Text.Encoding]::Unicode
}
'UTF7' {
$ContentEncoding = [System.Text.Encoding]::UTF7
}
'UTF8' {
$ContentEncoding = [System.Text.Encoding]::UTF8
}
'UTF32' {
$ContentEncoding = [System.Text.Encoding]::UTF32
}
'BigEndianUnicode'{
$ContentEncoding = [System.Text.Encoding]::BigEndianUnicode
}
}
}
Process
{
foreach($session in $ToProcess)
{
$ValueType = $Value.GetType().Name
write-verbose -message "Saving a $($ValueType) to $($Path)."
try
{
switch ($ValueType)
{
'string[]' {
if ($Append)
{
$session.session.AppendAllLines($Path, $Value, $ContentEncoding)
}
else
{
$session.session.WriteAllLines($Path, $Value, $ContentEncoding)
}
$session.session.Get($Path)
}
'byte[]' {
if ($Append)
{
$session.session.WriteAllBytes($Path, $Value)
}
else
{
$session.session.WriteAllBytes($Path, $Value)
}
$session.session.Get($Path)
}
'string' {
if ($Append)
{
$session.session.AppendAllText($Path, $Value, $ContentEncoding)
}
else
{
$session.session.WriteAllText($Path, $Value, $ContentEncoding)
}
$session.session.Get($Path)
}
Default {Write-Error -Message "The value of type $($ValueType) is not supported."}
}
}
catch
{
Write-Error -Exception $_.Exception -Message "Failed to write content to file $($Path)"
}
}
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function New-SFTPFileStream
{
[CmdletBinding(DefaultParameterSetName='Index')]
[OutputType([Renci.SshNet.Sftp.SftpFileStream])]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession]
$SFTPSession,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[String]
$Path,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Append', 'Create', 'CreateNew', 'Open', 'OpenOrCreate', 'Truncate')]
[string]
$FileMode,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('Read', 'ReadWrite', 'Write')]
[string]
$FileAccess
)
Begin
{
$ToProcess = $null
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
$sess = Get-SFTPSession -Index $SessionId
if ($sess)
{
$ToProcess = $sess
}
else
{
Write-Error -Message "Session specified with Index $($SessionId) was not found"
return
}
}
}
# Set FileAccess.
switch ($FileAccess)
{
'Read' {
$StreamFileAccess = [System.IO.FileAccess]::Read
}
'ReadWrite' {
$StreamFileAccess = [System.IO.FileAccess]::ReadWrite
}
'Write' {
$StreamFileAccess = [System.IO.FileAccess]::Write
}
}
# Set FileMode.
switch ($FileMode)
{
'Append' {
$StreamFileMode = [System.IO.FileMode]::Append
}
'Create' {
$StreamFileMode = [System.IO.FileMode]::Create
}
'CreateNew' {
$StreamFileMode = [System.IO.FileMode]::CreateNew
}
'Open' {
$StreamFileMode = [System.IO.FileMode]::Open
}
'OpenOrCreate' {
$StreamFileMode = [System.IO.FileMode]::OpenOrCreate
}
'Truncate' {
$StreamFileMode = [System.IO.FileMode]::Truncate
}
}
}
Process
{
$ToProcess.Session.Open($Path, $StreamFileMode, $StreamFileAccess)
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function New-SFTPItem
{
[CmdletBinding(DefaultParameterSetName='Index')]
param(
[Parameter(Mandatory=$true,
ParameterSetName = 'Index',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('Index')]
[Int32[]]
$SessionId,
[Parameter(Mandatory=$true,
ParameterSetName = 'Session',
ValueFromPipeline=$true,
Position=0)]
[Alias('Session')]
[SSH.SFTPSession[]]
$SFTPSession,
[Parameter(Mandatory=$true,
Position=1)]
[string]
$Path,
[Parameter(Mandatory=$false,
Position=2)]
[ValidateSet('File', 'Directory')]
[string]
$ItemType = 'File',
[Parameter(Mandatory=$false)]
[switch]
$Recurse
)
Begin
{
$ToProcess = @()
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
$ToProcess = $SFTPSession
}
'Index'
{
foreach($session in $Global:SFTPSessions)
{
if ($SessionId -contains $session.SessionId)
{
$ToProcess += $session
}
}
}
}
}
Process
{
foreach($sess in $ToProcess)
{
if (!$sess.Session.Exists($Path))
{
switch($ItemType)
{
'Directory' {
Write-Verbose -Message "Creating directory $($Path)"
if ($Recurse) {
$components = $Path.Split('/')
$level = 0
$newPath = ''
if($Path[0] -eq '.') {
$newPath = '.'
$level = 1
} elseif ($Path[0] -eq '/') {
$level = 1
} else {
$level = 0
}
for ($level; $level -le ($components.Count -1); $level++ )
{
if ($level -gt 0)
{
$newpath = $newPath + '/' + $components[$level]
}
else
{
$newpath = $newPath + $components[$level]
}
Write-Verbose -message "Checking if $($newPath) exists."
if ($sess.Session.Exists($newPath)) {
write-Verbose -message "$($newPath) exist."
$attr = $sess.Session.GetAttributes($newPath)
if (!$attr.IsDirectory) {
throw "Path in recursive creation is not a directory."
} else {
write-Verbose -message "$($newPath) is directory"
}
} else {
Write-Verbose -Message "Creating $($newPath)"
try {
$sess.Session.CreateDirectory($newPath)
} catch {
$_
$return
}
}
}
$sess.Session.Get($Path)
} else {
$sess.Session.CreateDirectory($Path)
Write-Verbose -Message 'Directory succesfully created.'
$sess.Session.Get($Path)
}
}
'File' {
Write-Verbose -Message "Creating file $($Path)"
$sess.Session.Create($Path).close()
Write-Verbose -Message 'File succesfully created.'
$sess.Session.Get($Path)
}
}
}
else
{
Write-Error -Message "Specified path of $($Path) already exists."
}
}
}
End
{
}
}
|
PowerShellCorpus/PowerShellGallery/Posh-SSH/1.7.7/Trust.ps1
|
Trust.ps1
|
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Get-SSHTrustedHost
{
[CmdletBinding()]
[OutputType([int])]
Param()
Begin{}
Process
{
$Test_Path_Result = Test-Path -Path "hkcu:\Software\PoshSSH"
if ($Test_Path_Result -eq $false)
{
Write-Verbose -Message 'No previous trusted keys have been configured on this system.'
New-Item -Path HKCU:\Software -Name PoshSSH | Out-Null
return
}
$poshsshkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\PoshSSH', $true)
$hostnames = $poshsshkey.GetValueNames()
$TrustedHosts = @()
foreach($h in $hostnames)
{
$TrustedHost = @{
SSHHost = $h
Fingerprint = $poshsshkey.GetValue($h)
}
$TrustedHosts += New-Object -TypeName psobject -Property $TrustedHost
}
}
End
{
$TrustedHosts
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function New-SSHTrustedHost
{
[CmdletBinding()]
Param
(
# IP Address of FQDN of host to add to trusted list.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$SSHHost,
# SSH Server Fingerprint.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
$FingerPrint
)
Begin
{
}
Process
{
$softkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software', $true)
if ( $softkey.GetSubKeyNames() -contains 'PoshSSH')
{
$poshsshkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\PoshSSH', $true)
}
else
{
Write-Verbose 'PoshSSH Registry key is not present for this user.'
New-Item -Path HKCU:\Software -Name PoshSSH | Out-Null
Write-Verbose 'PoshSSH Key created.'
$poshsshkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\PoshSSH', $true)
}
Write-Verbose "Adding to trusted SSH Host list $($SSHHost) with a fingerprint of $($FingerPrint)"
$poshsshkey.SetValue($SSHHost, $FingerPrint)
Write-Verbose 'SSH Host has been added.'
}
End
{
}
}
# .ExternalHelp Posh-SSH.psm1-Help.xml
function Remove-SSHTrustedHost
{
[CmdletBinding()]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]
$SSHHost
)
Begin
{
}
Process
{
$softkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software', $true)
if ($softkey.GetSubKeyNames() -contains 'PoshSSH' )
{
$poshsshkey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\PoshSSH', $true)
}
else
{
Write-warning 'PoshSSH Registry key is not present for this user.'
return
}
Write-Verbose "Removing SSH Host $($SSHHost) from the list of trusted hosts."
if ($poshsshkey.GetValueNames() -contains $SSHHost)
{
$poshsshkey.DeleteValue($SSHHost)
Write-Verbose 'SSH Host has been removed.'
}
else
{
Write-Warning "SSH Hosts $($SSHHost) was not present in the list of trusted hosts."
}
}
End{}
}
|
PowerShellCorpus/PowerShellGallery/Posh-SSH/1.7.7/tests/Remove-SSHSession.Tests.ps1
|
Remove-SSHSession.Tests.ps1
|
Import-Module .\Posh-SSH.psd1
Describe "Remove-SSHSession" {
Context "Parameters" {
}
Context "Action" {
$Global:SshSessions = New-Object System.Collections.ArrayList
$session = New-Object SSH.SshSession
$session.host = "dummy"
$session.SessionId = 0
$session.Session = New-Object Renci.SshNet.SshClient -ArgumentList "localhost","user","pass"
$Global:SshSessions.Add($session)
It "Should remove a session by index" {
Remove-SSHSession -Index 0
$sessions = Get-SSHSession
$sessions | should be $null
}
It "Removing a non-existing session should not throw" {
{ Remove-SSHSession -SessionId 0 } | Should not throw
}
$Global:SshSessions.Add($session)
It "Should remove a session submitted through the pipeline" {
$session | Remove-SSHSession
$sessions = Get-SSHSession
$sessions | Should be $null
}
$Global:SshSessions.Add($session)
It "Should remove a session by parameter" {
Remove-SSHSession -SSHSession $session
$sessions = Get-SSHSession
$sessions | Should be $null
}
}
}
Remove-Module Posh-SSH -ErrorAction SilentlyContinue
Remove-Variable sshsessions -Scope Global -ErrorAction SilentlyContinue
|
PowerShellCorpus/PowerShellGallery/Posh-SSH/1.7.7/tests/Get-SSHSession.Tests.ps1
|
Get-SSHSession.Tests.ps1
|
Import-Module .\Posh-SSH.psd1
Describe "Get-SSHSession" {
Context "Parameters" {
It "should not throw if no parameter is given" {
{ Get-SSHSession } | Should not throw
}
It "Should not throw if index parameter is given" {
{ Get-SSHSession -SessionId 0 } | should not throw
}
}
Context "ReturnData" {
$Global:SshSessions = New-Object System.Collections.ArrayList
$session = New-Object SSH.SshSession
$session.host = "dummy"
$session.SessionID = 0
$Global:SshSessions.Add($session)
$Global:session = New-Object SSH.SshSession
$session.host = "dummy"
$session.SessionID = 1
$SshSessions.Add($session)
$Allsessions = Get-SSHSession
It "Should return data with no parameters" {
{ $Allsessions } | should not be null
}
It "Should have 2 session objects" {
($Allsessions | Measure-Object).count | should be 2
}
$OneSession = Get-SSHSession -SessionId 1
It "Should return the object of the specified index" {
$OneSession.SessionId | should be 1
}
It "Should return an object of type sshSession" {
{ $OneSession -is [SSH.SshSession] } | should be $true
}
}
}
Remove-Module Posh-SSH -ErrorAction SilentlyContinue
Remove-Variable sshsessions -Scope Global -ErrorAction SilentlyContinue
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/ExampleConfig.ps1
|
ExampleConfig.ps1
|
Configuration myChocoConfig
{
Import-DscResource -Module cChoco
Node "localhost"
{
LocalConfigurationManager
{
DebugMode = 'ForceModuleImport'
}
cChocoInstaller installChoco
{
InstallDir = "c:\choco"
}
cChocoPackageInstaller installChrome
{
Name = "googlechrome"
DependsOn = "[cChocoInstaller]installChoco"
#This will automatically try to upgrade if available, only if a version is not explicitly specified.
AutoUpgrade = $True
}
cChocoPackageInstaller installAtomSpecificVersion
{
Name = "atom"
Version = "0.155.0"
DependsOn = "[cChocoInstaller]installChoco"
}
cChocoPackageInstaller installGit
{
Ensure = 'Present'
Name = "git"
Params = "/Someparam "
DependsOn = "[cChocoInstaller]installChoco"
}
cChocoPackageInstaller noFlashAllowed
{
Ensure = 'Absent'
Name = "flashplayerplugin"
DependsOn = "[cChocoInstaller]installChoco"
}
cChocoPackageInstallerSet installSomeStuff
{
Ensure = 'Present'
Name = @(
"git"
"skype"
"7zip"
)
DependsOn = "[cChocoInstaller]installChoco"
}
cChocoPackageInstallerSet stuffToBeRemoved
{
Ensure = 'Absent'
Name = @(
"vlc"
"ruby"
"adobeair"
)
DependsOn = "[cChocoInstaller]installChoco"
}
}
}
myChocoConfig
Start-DscConfiguration .\myChocoConfig -wait -Verbose -force
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1
|
cChocoInstaller_cChocoPackageInstallExample.ps1
|
Configuration InstallChoco
{
Import-DscResource -Module cChoco
Node "localhost"
{
cChocoPackageInstaller installSkypeWithChocoParams
{
Name = 'skype'
Ensure = 'Present'
AutoUpgrade = $True
}
}
}
$config = InstallChoco
Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Examples/cChocoInstaller_cChocoInstallerExample.ps1
|
cChocoInstaller_cChocoInstallerExample.ps1
|
Configuration InstallChoco
{
Import-DscResource -Module cChoco
Node "localhost"
{
cChocoInstaller InstallChoco
{
InstallDir = "c:\choco"
}
cChocoPackageInstaller installSkypeWithChocoParams
{
Name = 'skype'
Ensure = 'Present'
DependsOn = '[cChocoInstaller]installChoco'
}
}
}
$config = InstallChoco
Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/AppVeyor/AppVeyorBuild.ps1
|
AppVeyorBuild.ps1
|
#---------------------------------#
# Header #
#---------------------------------#
Write-Host 'Running AppVeyor build script' -ForegroundColor Yellow
Write-Host "ModuleName : $env:ModuleName"
Write-Host "Build version : $env:APPVEYOR_BUILD_VERSION"
Write-Host "Author : $env:APPVEYOR_REPO_COMMIT_AUTHOR"
Write-Host "Branch : $env:APPVEYOR_REPO_BRANCH"
Write-Host "Repo : $env:APPVEYOR_REPO_NAME"
Write-Host "PSModulePath :"
$env:PSModulePath -split ';'
#---------------------------------#
# BuildScript #
#---------------------------------#
Write-Host 'Nothing to build, skipping.....'
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/AppVeyor/AppVeyorInstall.ps1
|
AppVeyorInstall.ps1
|
#---------------------------------#
# Header #
#---------------------------------#
Write-Host 'Running AppVeyor install script' -ForegroundColor Yellow
#---------------------------------#
# Install NuGet #
#---------------------------------#
Write-Host 'Installing NuGet PackageProvide'
$pkg = Install-PackageProvider -Name NuGet -Force -ErrorAction Stop
Write-Host "Installed NuGet version '$($pkg.version)'"
#---------------------------------#
# Install Modules #
#---------------------------------#
[version]$ScriptAnalyzerVersion = '1.8.1'
Install-Module -Name 'PSScriptAnalyzer' -Repository PSGallery -Force -ErrorAction Stop -MaximumVersion $ScriptAnalyzerVersion
Install-Module -Name 'Pester','xDSCResourceDesigner' -Repository PSGallery -Force -ErrorAction Stop
#---------------------------------#
# Update PSModulePath #
#---------------------------------#
Write-Host 'Updating PSModulePath for DSC resource testing'
$env:PSModulePath = $env:PSModulePath + ";" + "C:\projects"
#---------------------------------#
# Validate #
#---------------------------------#
$RequiredModules = 'PSScriptAnalyzer','Pester','xDSCResourceDesigner'
$InstalledModules = Get-Module -Name $RequiredModules -ListAvailable
if ( ($InstalledModules.count -lt $RequiredModules.Count) -or ($Null -eq $InstalledModules)) {
throw "Required modules are missing."
} else {
Write-Host 'All modules required found' -ForegroundColor Green
}
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/AppVeyor/AppVeyorDeploy.ps1
|
AppVeyorDeploy.ps1
|
#---------------------------------#
# Header #
#---------------------------------#
Write-Host 'Running AppVeyor deploy script' -ForegroundColor Yellow
#---------------------------------#
# Update module manifest #
#---------------------------------#
Write-Host 'Creating new module manifest'
$ModuleManifestPath = Join-Path -path "$pwd" -ChildPath ("$env:ModuleName"+'.psd1')
$ModuleManifest = Get-Content $ModuleManifestPath -Raw
Write-Host "Updating module manifest to version: $env:APPVEYOR_BUILD_VERSION"
[regex]::replace($ModuleManifest,'(ModuleVersion = )(.*)',"`$1'$env:APPVEYOR_BUILD_VERSION'") | Out-File -LiteralPath $ModuleManifestPath
#---------------------------------#
# Publish to PS Gallery #
#---------------------------------#
if ( ($env:APPVEYOR_REPO_NAME -notmatch 'chocolatey') -or ($env:APPVEYOR_REPO_BRANCH -notmatch 'master') )
{
Write-Host "Finished testing of branch: $env:APPVEYOR_REPO_BRANCH - Exiting"
exit;
}
Write-Host "Publishing module to Powershell Gallery: "
Publish-Module -Name $env:ModuleName -NuGetApiKey $env:nugetKey
Write-Host 'Done!' -ForegroundColor Green
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/AppVeyor/AppVeyorTest.ps1
|
AppVeyorTest.ps1
|
#---------------------------------#
# Header #
#---------------------------------#
Write-Host 'Running AppVeyor test script' -ForegroundColor Yellow
Write-Host "Current working directory: $pwd"
#---------------------------------#
# Run Pester Tests #
#---------------------------------#
$resultsFile = '.\TestsResults.xml'
$testFiles = Get-ChildItem "$pwd\tests" | Where-Object {$_.FullName -match 'Tests.ps1$'} | Select-Object -ExpandProperty FullName
$results = Invoke-Pester -Script $testFiles -OutputFormat NUnitXml -OutputFile $resultsFile -PassThru
Write-Host 'Uploading results'
try {
(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $resultsFile))
} catch {
throw "Upload failed."
}
#---------------------------------#
# Validate #
#---------------------------------#
if (($results.FailedCount -gt 0) -or ($results.PassedCount -eq 0) -or ($null -eq $results)) {
throw "$($results.FailedCount) tests failed."
} else {
Write-Host 'All tests passed' -ForegroundColor Green
}
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Tests/cChocoInstaller_Tests.ps1
|
cChocoInstaller_Tests.ps1
|
#---------------------------------#
# Pester tests for cChocoInstall #
#---------------------------------#
$ResourceName = ((Split-Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0]
$ResourceFile = (Get-DscResource -Name $ResourceName).Path
Describe "Testing $ResourceName loaded from $ResourceFile" {
Context “Testing 'Get-TargetResource'” {
It 'DummyTest $true should be $true' {
$true | Should Be $true
}
}
}
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Tests/cChoco_ScriptAnalyzerTests.ps1
|
cChoco_ScriptAnalyzerTests.ps1
|
#---------------------------------#
# PSScriptAnalyzer tests #
#---------------------------------#
$Rules = Get-ScriptAnalyzerRule
#Only run on cChocoInstaller.psm1 for now as this is the only resource that has had code adjustments for PSScriptAnalyzer rules.
$Modules = Get-ChildItem “$PSScriptRoot\..\” -Filter ‘*.psm1’ -Recurse | Where-Object {$_.FullName -match '(cChocoInstaller|cChocoPackageInstall)\.psm1$'}
#---------------------------------#
# Run Module tests (psm1) #
#---------------------------------#
if ($Modules.count -gt 0) {
Describe ‘Testing all Modules against default PSScriptAnalyzer rule-set’ {
foreach ($module in $modules) {
Context “Testing Module '$($module.FullName)'” {
foreach ($rule in $rules) {
It “passes the PSScriptAnalyzer Rule $rule“ {
(Invoke-ScriptAnalyzer -Path $module.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0
}
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Tests/cChoco_xDscResourceTests.ps1
|
cChoco_xDscResourceTests.ps1
|
#---------------------------------#
# xDscResourceTests Pester #
#---------------------------------#
$DSC = Get-DscResource | Where-Object {$_.Module.Name -eq 'cChoco'}
Describe 'Testing all DSC resources using xDscResource designer.' {
foreach ($Resource in $DSC)
{
if (-not ($Resource.ImplementedAs -eq 'Composite') ) {
$ResourceName = $Resource.ResourceType
$Mof = Get-ChildItem “$PSScriptRoot\..\” -Filter "$resourcename.schema.mof" -Recurse
Context “Testing DscResource '$ResourceName' using Test-xDscResource” {
It 'Test-xDscResource should return $true' {
Test-xDscResource -Name $ResourceName | Should Be $true
}
}
Context “Testing DscSchema '$ResourceName' using Test-xDscSchema” {
It 'Test-xDscSchema should return true' {
Test-xDscSchema -Path $Mof.FullName | Should Be $true
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/cChoco/2.3.1.0/Tests/cChocoPackageInstall_Tests.ps1
|
cChocoPackageInstall_Tests.ps1
|
#----------------------------------------#
# Pester tests for cChocoPackageInstall #
#----------------------------------------#
$ResourceName = ((Split-Path -Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0]
$ResourceFile = (Get-DscResource -Name $ResourceName).Path
$TestsPath = (split-path -path $MyInvocation.MyCommand.Path -Parent)
$ResourceFile = Get-ChildItem -Recurse $TestsPath\.. -File | Where-Object {$_.name -eq "$ResourceName.psm1"}
Import-Module -Name $ResourceFile.FullName
Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture {
Context -Name "Package is not installed" -Fixture {
Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith {
return [pscustomobject]@{
'Name' = 'NotGoogleChrome'
'Version' = '1.0.0'
}
}
$Scenario1 = @{
Name = 'GoogleChrome'
Ensure = 'Present'
}
It -name "Test-TargetResource -ensure 'Present' should return False" -test {
Test-TargetResource @Scenario1 | Should Be $False
}
$Scenario2 = @{
Name = 'GoogleChrome'
Ensure = 'Absent'
}
It -name "Test-TargetResource -ensure 'Absent' should return True" -test {
Test-TargetResource @Scenario2 | Should Be $True
}
$Scenario3 = @{
Name = 'GoogleChrome'
Ensure = 'Absent'
Version = '1.0.0'
}
It -name "Test-TargetResource -ensure 'Absent' -version '1.0.0' should return True" -test {
Test-TargetResource @Scenario3 | Should Be $True
}
$Scenario4 = @{
Name = 'GoogleChrome'
Ensure = 'Absent'
AutoUpgrade = $True
}
It -name "Test-TargetResource -ensure 'Absent' -AutoUpgrade should return True" -test {
Test-TargetResource @Scenario4 | Should Be $True
}
$Scenario5 = @{
Name = 'GoogleChrome'
Ensure = 'Absent'
Version = '1.0'
AutoUpgrade = $True
}
It -name "Test-TargetResource -ensure 'Absent' -version '1.0.0' -AutoUpgrade should return True" -test {
Test-TargetResource @Scenario5 | Should Be $True
}
}
Context -Name "Package is installed with version 1.0.0" -Fixture {
Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith {
return [pscustomobject]@{
'Name' = 'GoogleChrome'
'Version' = '1.0.0'
}
}
$Scenario1 = @{
Name = 'GoogleChrome'
Ensure = 'Present'
}
It -name "Test-TargetResource -ensure 'Present' should return True" -test {
Test-TargetResource @Scenario1 | Should Be $True
}
$Scenario2 = @{
Name = 'GoogleChrome'
Ensure = 'Absent'
}
It -name "Test-TargetResource -ensure 'Absent' should return False" -test {
Test-TargetResource @Scenario2 | Should Be $False
}
$Scenario3 = @{
Name = 'GoogleChrome'
Ensure = 'Present'
Version = '1.0.0'
}
It -name "Test-TargetResource -ensure 'Present' -version '1.0.0' should return True" -test {
Test-TargetResource @Scenario3 | Should Be $True
}
$Scenario4 = @{
Name = 'GoogleChrome'
Ensure = 'Present'
Version = '1.0.1'
}
It -name "Test-TargetResource -ensure 'Present' -version '1.0.1' should return False" -test {
Test-TargetResource @Scenario4 | Should Be $False
}
}
}
#Clean-up
Remove-Module cChocoPackageInstall
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/repository.ps1
|
repository.ps1
|
Function Get-GithubOrgRepository {
param (
[Parameter(mandatory=$true)]
[string]$OrganisationName
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
try {
$json = Invoke-WebRequest -Uri https://api.github.com/orgs/$OrganisationName/repos -Method Get -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
[System.Collections.ArrayList]$orgrepos = @()
$con_json = ConvertFrom-Json -InputObject $json.Content
foreach ($obj in $con_json) {
$orgrepo = New-Object -TypeName PSObject
Add-Member -InputObject $orgrepo -MemberType NoteProperty -Name 'Repository Name' -Value $obj.name
Add-Member -InputObject $orgrepo -MemberType NoteProperty -Name 'Repository Owner' -Value $obj.owner.login
Add-Member -InputObject $orgrepo -MemberType NoteProperty -Name 'Repository Description' -Value $obj.description
$orgrepos += $orgrepo
}
$orgrepos
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name orgrepos -Force
Remove-Variable -Name orgrepo -Force
}
}
Function Get-GithubOwnRepositories {
param (
[Parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/user/repos -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/user/repos -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
[System.Collections.ArrayList]$repos = @()
$con_json = ConvertFrom-Json -InputObject $json.Content
foreach ($obj in $con_json) {
$repo = New-Object -TypeName PSObject
Add-Member -InputObject $repo -MemberType NoteProperty -Name 'Name' -Value $obj.name
Add-Member -InputObject $repo -MemberType NoteProperty -Name 'Description' -Value $obj.description
$repos += $repo
}
$repos
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name repos -Force
Remove-Variable -Name repo -Force
}
}
Function Get-GithubPublicRepositories {
param (
[parameter(mandatory=$false)]
[string] $githubusername
)
Begin {}
Process {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/users/$githubusername/repos -Method Get -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
[System.Collections.ArrayList]$repos = @()
$con_json = ConvertFrom-Json -InputObject $json.Content
foreach ($obj in $con_json) {
$repo = New-Object -TypeName PSObject
Add-Member -InputObject $repo -MemberType NoteProperty -Name 'Name' -Value $obj.name
Add-Member -InputObject $repo -MemberType NoteProperty -Name 'Description' -Value $obj.description
$repos += $repo
}
$repos
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name repos -Force
Remove-Variable -Name repo -Force
}
}
Function Remove-GithubRepository {
param (
[Parameter(Mandatory=$true)]
[string]$githubusername,
[Parameter(Mandatory=$true)]
[string]$Repository_Name,
[Parameter(Mandatory=$true)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
Invoke-WebRequest -Uri https://api.github.com/repos/$githubusername/$Repository_Name -Method Delete -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Uri https://api.github.com/repos/$githubusername/$Repository_Name -Method Delete -Headers @{"Authorization"="Basic $BasicCreds"} -Verbose -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End {}
}
Function New-GithubRepository {
<#
.Synopsis
Create a new Github repository
.DESCRIPTION
This function will create a new Github repository via the Github REST API.
.EXAMPLE
New-GithubRepository -repository_name Demo -repository_description 'This is a demo repo' -repository_homepage 'http://www.david-obrien.net' -repository_private true -repository_has_issues false -repository_has_wiki false -repository_has_downloads true
#>
param (
[Parameter(Mandatory= $true)]
[string]$repository_name,
[Parameter(Mandatory= $true)]
[string]$repository_description,
[Parameter(Mandatory= $true)]
[string]$repository_homepage,
[Parameter(Mandatory= $true)]
[string]$repository_private,
[Parameter(Mandatory= $true)]
[string]$repository_has_issues,
[Parameter(Mandatory= $true)]
[string]$repository_has_wiki,
[Parameter(Mandatory= $true)]
[string]$repository_has_downloads,
[Parameter(Mandatory= $false)]
[string]$OneTimePassword
)
Begin {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
}
Process {
$newrepo = @"
{
"name": "$repository_name",
"description": "$repository_description",
"homepage": "$repository_homepage",
"private": $repository_private,
"has_issues": $repository_has_issues,
"has_wiki": $repository_has_wiki,
"has_downloads": $repository_has_downloads
}
"@
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
Invoke-WebRequest -Body $newrepo -Uri https://api.github.com/user/repos -Method Post -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Body $newrepo -Uri https://api.github.com/user/repos -Method Post -Headers @{"Authorization"="Basic $BasicCreds"} -Verbose -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End {
Remove-Variable -Name newrepo -Force
}
}
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/authentication.ps1
|
authentication.ps1
|
Function Connect-Github {
<#
.Synopsis
Connects PowerShell to the Github API
.DESCRIPTION
This function will connect the current PowerShell session to the Github API via Basic Authentication. Also supports 2 Factor Authentication via One Time Password.
The user name and password have to be provided on the command line as Github is not following RFC standards to the full extent: https://developer.github.com/v3/auth/
If you don't want to provide the password on the command line, don't provide it and enter it in the prompt.
.PARAMETER GithubCredentials
Optional. PSCredential object that holds the User's Github Credentials. If not provided, Function will prompt.
.PARAMETER OneTimePassword
Optional. If your Github user is enabled for Multi-Factor Authentication (MFA or 2FA) you need to provide an OneTimePassword in order to authenticate.
.EXAMPLE
Connect-Github
.EXAMPLE
Connect-Github -GithubCredentials $(Get-Credential)
.EXAMPLE
Connect-Github -OneTimePassword 123456
.EXAMPLE
$creds = Get-Credential
Connect-Github -GithubCredentials $creds -OneTimePassword 123456
#>
param (
[Parameter(Mandatory=$false)]
[PSCredential]$GithubCredentials,
[Parameter(Mandatory=$false)]
[string]$OneTimePassword
)
Begin
{
}
Process
{
if (-not $GithubCredentials) {
$GithubCredentials = (Get-Credential -Message 'Please enter the Github User credentials')
}
$githubusername = $GithubCredentials.UserName
$githubpassword = $GithubCredentials.GetNetworkCredential().Password
$AuthString = '{0}:{1}' -f $githubusername,$githubpassword
$AuthBytes = [System.Text.Encoding]::Ascii.GetBytes($AuthString)
$global:BasicCreds = [Convert]::ToBase64String($AuthBytes)
$githuburi = 'https://api.github.com/user'
if ($OneTimePassword) {
try {
Invoke-WebRequest -Uri $GitHubUri -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -Verbose -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Uri $GitHubUri -Headers @{"Authorization"="Basic $BasicCreds"} -Verbose -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End
{
}
}
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/webhook.ps1
|
webhook.ps1
|
Function Get-GithubWebhook {
param
(
[Parameter(Mandatory=$true)]
[string]$githubuser,
[Parameter(Mandatory=$false)]
[string]$githubrepository,
[Parameter(Mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/repos/$githubuser/$githubrepository/hooks -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/repos/$githubuser/$githubrepository/hooks -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
$con_json = ConvertFrom-Json -InputObject $json.Content
$con_json
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
}
}
Function New-GithubWebhook {
param (
[Parameter(Mandatory=$true)]
[string]$githubuser,
[Parameter(Mandatory=$true)]
[string]$githubrepository,
[Parameter(Mandatory=$true)]
[string]$webhookurl,
[Parameter(Mandatory=$false)]
[string]$webhooktype='web',
[Parameter(Mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
$json = @"
{
"name": "$webhooktype",
"active": true,
"events": ["push"],
"config": {
"url": "$webhookurl",
"content_type": "json"
}
}
"@
if ($OneTimePassword) {
try {
Invoke-WebRequest -Body $json -Uri https://api.github.com/repos/$githubuser/$githubrepository/hooks -Method Post -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Body $json -Uri https://api.github.com/repos/$githubuser/$githubrepository/hooks -Method Post -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End {
Remove-Variable -Name json -Force
}
}
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/teams.ps1
|
teams.ps1
|
Function Get-GithubTeams {
param (
[Parameter(mandatory=$true)]
[string]$OrganisationName,
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/orgs/$OrganisationName/teams -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/orgs/$OrganisationName/teams -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
$con_json = ConvertFrom-Json -InputObject $json.Content
$con_json
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
}
}
Function Get-GithubTeamFromId {
param (
[Parameter(mandatory=$true)]
[string]$TeamId,
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/teams/$TeamId -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/teams/$TeamId -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
$con_json = ConvertFrom-Json -InputObject $json.Content
$con_json
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
}
}
Function Get-GithubTeamMembership {
param (
[Parameter(mandatory=$true)]
[string]$TeamId,
[Parameter(mandatory=$true)]
[string]$githubusername,
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/teams/$TeamId/memberships/$githubusername -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Uri https://api.github.com/teams/$TeamId/memberships/$githubusername -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
$con_json = ConvertFrom-Json -InputObject $json.Content
$con_json
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
}
}
<#
Function Add-GithubUserToTeam {
param (
[Parameter(mandatory=$true)]
[string]$TeamId,
[Parameter(mandatory=$true)]
[string]$githubusername,
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
}
#>
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/branch.ps1
|
branch.ps1
|
Function List-GithubBranches {
param (
[parameter(mandatory=$true)]
[string]$githubuser,
[parameter(mandatory=$true)]
[string]$githubrepository
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
try {
$json = Invoke-WebRequest -Uri https://api.github.com/repos/$githubuser/$githubrepository/branches -Method Get -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
[System.Collections.ArrayList]$branches = @()
$con_json = ConvertFrom-Json -InputObject $json.Content
foreach ($obj in $con_json) {
$branch = New-Object -TypeName PSObject
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'Name' -Value $obj.name
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'Last Commit URL' -Value $obj.commit.url
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'SHA of last Commit' -Value $obj.commit.sha
$branches += $branch
}
$branches
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name branch -Force
Remove-Variable -Name branches -Force
}
}
Function Get-GithubBranch {
param (
[parameter(mandatory=$true)]
[string]$githubuser,
[parameter(mandatory=$true)]
[string]$githubrepository,
[parameter(mandatory=$false)]
[string]$githubbranch='master'
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
try {
$json = Invoke-WebRequest -Uri https://api.github.com/repos/$githubuser/$githubrepository/branches/$githubbranch -Method Get -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
$con_json = ConvertFrom-Json -InputObject $json.Content
$branch = New-Object -TypeName PSObject
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'Branch Name' -Value $con_json.name
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'Last Commit Author' -Value $con_json.commit.author.login
Add-Member -InputObject $branch -MemberType NoteProperty -Name 'Last Commit Message' -Value $con_json.commit.commit.message
$branch
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name branch -Force
}
}
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/organisation.ps1
|
organisation.ps1
|
Function Add-GithubUserToOrganisation {
param (
[Parameter(mandatory=$true)]
[string]$OrganisationName,
[Parameter(mandatory=$true)]
[string]$githubusername,
[ValidateSet('admin','member')]
[Parameter(mandatory=$false)]
[string]$role='member',
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
$body = @{'role'="$role"}
if ($OneTimePassword) {
try {
Invoke-WebRequest -Body $body -Uri https://api.github.com/orgs/$OrganisationName/memberships/$githubusername -Method Put -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Body $body -Uri https://api.github.com/orgs/$OrganisationName/memberships/$githubusername -Method Put -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End {
Remove-Variable -Name body -Force
Remove-Variable -Name OrganisationName -Force
Remove-Variable -Name githubusername -Force
}
}
Function Remove-GithubUserFromOrganisation {
param (
[Parameter(mandatory=$true)]
[string]$OrganisationName,
[Parameter(mandatory=$true)]
[string]$githubusername,
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
if ($OneTimePassword) {
try {
Invoke-WebRequest -Body $body -Uri https://api.github.com/orgs/$OrganisationName/memberships/$githubusername -Method Delete -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
Invoke-WebRequest -Body $body -Uri https://api.github.com/orgs/$OrganisationName/memberships/$githubusername -Method Delete -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
}
End {
Remove-Variable -Name OrganisationName -Force
Remove-Variable -Name githubusername -Force
}
}
|
PowerShellCorpus/PowerShellGallery/GithubConnect/0.8/Public/pullrequest.ps1
|
pullrequest.ps1
|
Function Get-GithubPullRequests {
<#
.Synopsis
Gets Pull Requests for a repository
.DESCRIPTION
This function will list all Pull Requests for a given Repository. For now only the last 30 Pull Requests will be returned.
Parsing all PRs is quite time consuming via the API and is only possible via pagination. Not sure yet whether this will be implemented.
.PARAMETER githubuser
Mandatory.
.PARAMETER githubrepository
Mandatory.
.PARAMETER state
Optional. Defaults to open. Accepts open and closed.
.PARAMETER OneTimePassword
Optional. If your Github user is enabled for Multi-Factor Authentication (MFA or 2FA) you need to provide an OneTimePassword in order to authenticate.
.EXAMPLE
Get-GithubPullRequest -githubuser davidobrien1985 -githubrepository demos
.EXAMPLE
Get-GithubPullRequest -githubuser davidobrien1985 -githubrepository demos -state closed
.EXAMPLE
Get-GithubPullRequest -githubuser davidobrien1985 -githubrepository demos -state open -OneTimePassword 123456
#>
param (
[parameter(mandatory=$true)]
[string]$githubuser,
[parameter(mandatory=$true)]
[string]$githubrepository,
[parameter(mandatory=$false)]
[ValidateSet('open','closed')]
[string]$state='open',
[parameter(mandatory=$false)]
[string]$OneTimePassword
)
Begin {}
Process {
if (-not ($BasicCreds)) {
throw 'Please run Connect-Github first to get an authentication token for Github'
}
$RequestBody = @{'state' = "$state"}
if ($OneTimePassword) {
try {
$json = Invoke-WebRequest -Body $RequestBody -Uri https://api.github.com/repos/$githubuser/$githubrepository/pulls -Method Get -Headers @{"Authorization"="Basic $BasicCreds"; "X-Github-OTP" = $OneTimePassword} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
else {
try {
$json = Invoke-WebRequest -Body $RequestBody -Uri https://api.github.com/repos/$githubuser/$githubrepository/pulls -Method Get -Headers @{"Authorization"="Basic $BasicCreds"} -ErrorAction Stop
}
catch {
Write-Error -Message $_
}
}
$con_json = ConvertFrom-Json -InputObject $json.Content
[System.Collections.ArrayList]$PRs = @()
foreach ($obj in $con_json) {
$PR = New-Object -TypeName PSObject
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'PR Title' -Value $obj.title
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'PR Id' -Value $obj.id
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'PR URL' -Value $obj.url
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'created by' -Value $obj.user.login
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'PR State' -Value $obj.state
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'IsLocked' -Value $obj.locked
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'Created at' -Value $obj.created_at
Add-Member -InputObject $PR -MemberType NoteProperty -Name 'Updated at' -Value $obj.updated_at
$PRs += $PR
}
$PRs
}
End {
Remove-Variable -Name json -Force
Remove-Variable -Name con_json -Force
Remove-Variable -Name PR -Force
Remove-Variable -Name PRs -Force
Remove-Variable -Name con_json -Force
}
}
<#
Function Get-GithubSinglePullRequest {
param (
)
}
#>
<#
Function New-GithubPullRequest {
param (
)
}
#>
<#
Function Update-GithubPullRequest {
param (
)
}
#>
<#
Function Start-GithubPRMerge {
param (
)
}
#>
|
PowerShellCorpus/PowerShellGallery/AzureAutomationVsoGitSync/1.2.1/Public/Sync-VsoGitRmRunbooks.ps1
|
Sync-VsoGitRmRunbooks.ps1
|
<#
.SYNOPSIS
Syncs all runbooks in a VSO git repository to an Azure Automation account.
.DESCRIPTION
Syncs all runbooks in a VSO git repository to an Azure Automation account starting with dependent (child)
runbooks and followed by parent runbooks to an existing Automation Account. This runbook will recursively
treat all sub directories within the VSORunbookFolderPath as dependent (child) runbooks and publish these
first
With the -FlatFilesMode parameter, syncs all runbooks in the specified folder in a VSO git repository to
an Azure Automation Account by building a dependency graph and publishing bottom-up.
Requires a VSO Alternate Authentication Credential for connecting with VSO-Git repository, stored
in a Automation credential asset.
.PARAMETER VSOCredentialName
Name of the credential asset containing the VSO Alternate Authentication Credential name
and password configured from VSO Profile dialog.
.PARAMETER VSOAccount
Name of the account name for VSO Online. Ex. https://accountname.visualstudio.com
.PARAMETER VSOProject
Name of the VSO project that contains the repository
.PARAMETER VSORepository
Name of the repository that contains the runbook project
.PARAMETER VSORunbookFolderPath
Project path to the root where the runbooks are located. Ex. /Project1/ProjectRoot
where ProjectRoot contains the parent runbooks
.PARAMETER TargetSubscriptionId
The Id of the Azure Subscription where the Automation Assets will be deployed.
.PARAMETER TargetResourceGroup
Name of the Resource Group that contains the TargetAutomationAccount.
.PARAMETER TargetAutomationAccount
Name of the Automation Account to where the runbooks should be synced.
.PARAMETER TargetCredentialName
Name of the Azure Credential asset that was created in the Automation service.
This credential asset contains represents a user with permission to manage the TargetAutomationAccount.
.PARAMETER VSOBranch
Optional name of the Git branch to retrieve the runbooks from. Defaults to "master"
.PARAMETER FlatFilesMode
Optional. Defaults to "$false"
Flag enables forced-publishing of runbooks to satisfy parent/child caveats - without resorting to cumbersome source folder structures.
1. The runbook will loop through the flat list of runbooks, attempting to Import & Publish each, in the order they are enumerated from VSO.
2. If a runbook fails import, it's assumed that's because the Automation Account is missing a required child runbook.
3. The code will continue attempting to import the remaining runbooks.
4. If errors occured, steps 1-3 are repeated.
5. Successfully synced runbooks will not be imported on subsequent tries.
6. If errors occured and no runbooks are synced in a given try, the process gives up, assuming the issue is not a parent/child dependency.
.EXAMPLE
Sync-VsoGitRmRunbook -VSOCredentialName "VSOCredentialAsset" -VSOAccount "AccountName"
-VSOProject "Project" -VSORepository "Repository" -VSORunbookFolderPath "/Project1/ProjectRoot"
-TargetAutomationAccount "AccountName" -AzureConnectionName "ConnectionAssetName" -VSOBranch "master"
#>
function Sync-VsoGitRmRunbooks
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$True)]
[string] $VSOCredentialName,
[Parameter(Mandatory=$True)]
[string] $VSOAccount,
[Parameter(Mandatory=$True)]
[string] $VSOProject,
[Parameter(Mandatory=$True)]
[string] $VSORepository,
[Parameter(Mandatory=$True)]
[string] $VSOBranch,
[Parameter(Mandatory=$True)]
[string] $VSORunbookFolderPath,
[Parameter(Mandatory=$True)]
[string] $TargetCredentialName,
[Parameter(Mandatory=$True)]
[string] $TargetSubscriptionId,
[Parameter(Mandatory=$True)]
[string] $TargetResourceGroup,
[Parameter(Mandatory=$True)]
[string] $TargetAutomationAccount,
[Parameter(Mandatory=$False)]
[bool] $FlatFilesMode = $true
)
$psExtension = ".ps1"
$grExtension = ".graphrunbook"
$vsoApiVersion = "1.0-preview"
#Getting Credentail asset for VSO alternate authentication credentail
$VSOCred = Get-AutomationPSCredential -Name $VSOCredentialName
if ($VSOCred -eq $null)
{
throw "Could not retrieve '$VSOCredentialName' credential asset. Check that you created this asset in the Automation service."
}
$VSOAuthUserName = $VSOCred.UserName
$VSOAuthPassword = $VSOCred.GetNetworkCredential().Password
#Creating authorization header
$basicAuth = ("{0}:{1}" -f $VSOAuthUserName,$VSOAuthPassword)
$basicAuth = [System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth = [System.Convert]::ToBase64String($basicAuth)
$headers = @{Authorization=("Basic {0}" -f $basicAuth)}
#ex. "https://gkeong.visualstudio.com/defaultcollection/_apis/git/automation-git-test2-proj/repositories/automation-git-test2-proj/items?scopepath=/Project1/Project1/&recursionlevel=full&includecontentmetadata=true&versionType=branch&version=production&api-version=1.0-preview"
$VSOURL = "https://" + $VSOAccount + ".visualstudio.com/defaultcollection/_apis/git/" +
$VSOProject + "/repositories/" + $VSORepository + "/items?scopepath=" + $VSORunbookFolderPath +
"&recursionlevel=full&includecontentmetadata=true&versionType=branch&version=" + $VSOBranch +
"&api-version=" + $vsoApiVersion
Write-Verbose("Connecting to VSO using URL: $VSOURL")
$results = Invoke-RestMethod -Uri $VSOURL -Method Get -Headers $headers
$VerbosePreference = "Continue"
#$results | ConvertTo-Json | Write-Verbose
$allRunbooks = [AzureAutomationVsoGitSync.Models.SortedRunbookCollection]@{}
#grab folders & files
$folderObj = @()
foreach ($item in $results.value)
{
if ($item.gitObjectType -eq "tree")
{
$folderObj += $item
}
elseif (($item.gitObjectType -eq "blob") -and ($item.path -match $psExtension -or $item.path -match $grExtension))
{
# get runbook file name
$path = $item.path;
$fileName = [AzureAutomationVsoGitSync.Models.Runbook]::GetRunbookFileName($path);
# local temp path for runbook
$tempPath = Join-Path -Path $env:SystemDrive -ChildPath "temp"
$outFile = Join-Path -Path $tempPath -ChildPath $fileName
# download the runbook
$fileUrl = $item.url
Write-Verbose "`tGET $fileName"
$VerbosePreference = "SilentlyContinue"
Invoke-RestMethod -Uri $fileUrl -Method Get -Headers $headers -OutFile $outFile
$VerbosePreference = "Continue"
$new = $allRunbooks.Add($outFile, $fileUrl)
}
}
# Select the Azure Subscription
$VerbosePreference = "SilentlyContinue"
$azCred = Get-AutomationPSCredential -Name $TargetCredentialName
$azAcct = Add-AzureRmAccount -Credential $azCred -SubscriptionId $TargetSubscriptionId
$azSub = Select-AzureRmSubscription -SubscriptionId $TargetSubscriptionId
$VerbosePreference = "Continue"
# enumerate existing automation accounts & runbooks
#Get-AzureRmAutomationAccount -ResourceGroupName $TargetResourceGroup | ConvertTo-Json | Write-Verbose
#Get-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount | ConvertTo-Json | Write-Verbose
if ($FlatFilesMode)
{
$sysDrive = $env:SystemDrive
# [SortedRunbookCollection].Result will be the topologically-sorted list of runbooks
# (Leaf nodes first)
$vsoApiVersion = $true
$haveSynced = @{}
$errorSync = @{}
Write-Verbose "Publish Order (by dependency):"
$sorted = $allRunbooks.Result
$sorted | Select Name | ConvertTo-Json | Write-Verbose
foreach($rb in $sorted)
{
$outFile = $rb.FilePath
$runbookName = $rb.Name
$rbType = $rb.Type
try
{
# if not yet synced .. import & add to synced collection
if (!$haveSynced.ContainsKey($runbookName))
{
if ($rbType -eq [AzureAutomationVsoGitSync.Models.RunbookType]::Graph)
{
Write-Verbose "Importing $runbookName as Graph."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type Graph
}
elseif ($rbType -eq [AzureAutomationVsoGitSync.Models.RunbookType]::PowerShellWorkflow)
{
Write-Verbose "Importing $runbookName as PowerShellWorkflow."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type PowerShellWorkflow
}
elseif ($rbType -eq [AzureAutomationVsoGitSync.Models.RunbookType]::PowerShell)
{
Write-Verbose "Importing $runbookName as PowerShell."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type PowerShell
}
else
{
throw "Could not determine type of runbook $($rb.FileName) from $rbType"
}
#Write-Verbose "Publishing.."
#$rb = Publish-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Name $runbookName -ErrorAction Continue | Write-Verbose
$haveSynced.Add($runbookName, $rb.FileUrl)
}
else
{
Write-Verbose("Runbook $runbookName already synced. Duplicate?")
}
}
catch [System.Exception]
{
$ex = ConvertTo-Json $_
if (!$errorSync.ContainsKey($runbookName))
{
$errorsync.add( $runbookname, $ex )
}
Write-Verbose $ex
Write-Error $_
}
}
Write-Verbose "Done.`n"
Write-Verbose "Synced $($haveSynced.Count) of $($sorted.Count)"
#Write-Verbose "Errors $($errorSync.Count)"
if ($errorSync.Count > 0)
{
Write-Verbose "Errors:"
$errorSync | ConvertTo-Json | Write-Verbose
}
if ($haveSynced.Count -eq $sorted.Count)
{
Write-Verbose "All runbooks synced."
}
}
else
{
$haveSynced = @{}
$errorSync = @{}
#recursively go through most inner child folders first, then their parents, parents parents, etc.
for ($i = $folderObj.count - 1; $i -ge 0; $i--)
{
Write-Verbose("Processing files in $($folderObj[$i].path)")
$folderURL = "https://" + $VSOAccount + ".visualstudio.com/defaultcollection/_apis/git/" +
$VSOProject + "/repositories/" + $VSORepository + "/items?scopepath=" + $folderObj[$i].path +
"&recursionLevel=OneLevel&includecontentmetadata=true&versionType=branch&version=" +
$VSOBranch + "&api-version=" + $vsoApiVersion
$results = Invoke-RestMethod -Uri $folderURL -Method Get -Headers $headers
foreach ($item in $results.value)
{
try
{
$pathsplit = $item.path.Split("/")
$filename = $pathsplit[$pathsplit.Count - 1]
$tempPath = Join-Path -Path $env:SystemDrive -ChildPath "temp"
$outFile = Join-Path -Path $tempPath -ChildPath $filename
#Get the runbook name
$fname = $filename
$tempPathSplit = $fname.Split(".")
$runbookName = $tempPathSplit[0]
$rbType = $rb.Type
# if not yet synced .. import & add to synced collection
if (!$haveSynced.ContainsKey($runbookName))
{
if ($rbType -eq [RunbookType]::Graph)
{
Write-Verbose "Importing $runbookName as Graph."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type Graph
}
elseif ($rbType -eq [RunbookType]::PowerShellWorkflow)
{
Write-Verbose "Importing $runbookName as PowerShellWorkflow."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type PowerShellWorkflow
}
elseif ($rbType -eq [RunbookType]::PowerShell)
{
Write-Verbose "Importing $runbookName as PowerShell."
Import-AzureRmAutomationRunbook -ResourceGroupName $TargetResourceGroup -AutomationAccountName $TargetAutomationAccount -Path $outFile -Force -Published -Type PowerShell
}
else
{
throw "Could not determine type of runbook $($rb.FileName) from $rbType"
}
$haveSynced.Add($runbookName, $rb.FileUrl)
}
else
{
Write-Verbose("Runbook $runbookName already synced. Duplicate?")
}
}
catch [System.Exception]
{
$ex = ConvertTo-Json $_
if (!$errorSync.ContainsKey($runbookName))
{
$errorsync.add( $runbookname, $ex )
}
Write-Verbose $ex
Write-Error $_
}
}
}
Write-Verbose "Done.`n"
Write-Verbose "Synced $($haveSynced.Count) of $($allRunbooks.Results.Count)"
if ($errorSync.Count > 0)
{
Write-Verbose "Errors:"
$errorSync | ConvertTo-Json | Write-Verbose
}
if ($haveSynced.Count -gt 0 -and $haveSynced.Count -eq $results.Count)
{
Write-Verbose "All runbooks synced."
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzureAutomationVsoGitSync/1.2.1/Public/Sync-VsoGitSmRunbooks.ps1
|
Sync-VsoGitSmRunbooks.ps1
|
<#
.SYNOPSIS
Syncs all runbooks in a VSO git repository to an Azure Automation account.
.DESCRIPTION
Syncs all runbooks in a VSO git repository to an Azure Automation account starting with dependent (child)
runbooks and followed by parent runbooks to an existing Automation Account. This runbook will recursively
treat all sub directories within the VSORunbookFolderPath as dependent (child) runbooks and publish these
first
Requires a VSO Alternate Authentication Credential for connecting with VSO-Git repository, stored
in a Automation credential asset.
This runbook has a dependency on Azure-Connect, which you can download from
http://gallery.technet.microsoft.com/scriptcenter/Connect-to-an-Azure-f27a81bb
The Azure-Connect runbook must be published for this runbook to run correctly
.PARAMETER VSOCredentialName
Name of the credential asset containing the VSO Alternate Authentication Credential name
and password configured from VSO Profile dialog.
.PARAMETER VSOAccount
Name of the account name for VSO Online. Ex. https://accountname.visualstudio.com
.PARAMETER VSOProject
Name of the VSO project that contains the repository
.PARAMETER VSORepository
Name of the repository that contains the runbook project
.PARAMETER VSORunbookFolderPath
Project path to the root where the runbooks are located. Ex. /Project1/ProjectRoot
where ProjectRoot contains the parent runbooks
.PARAMETER AutomationAccount
Name of the Automation Account where the runbooks should be synced to
.PARAMETER AzureConnectionName
Name of the Azure connection asset that was created in the Automation service.
This connection asset contains the subscription id and the name of the certificate
setting that holds the management certificate.
.PARAMETER VSOBranch
Optional name of the Git branch to retrieve the runbooks from. Defaults to "master"
.EXAMPLE
Publish-From-GitVSO -VSOCredentialName "VSOCredentialAsset" -VSOAccount "AccountName"
-VSOProject "Project" -VSORepository "Repository" -VSORunbookFolderPath "/Project1/ProjectRoot"
-AutomationAccount "AccountName" -AzureConnectionName "ConnectionAssetName" -VSOBranch "master"
#>
function Sync-VsoGitSmRunbooks
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$True)]
[string] $VSOCredentialName,
[Parameter(Mandatory=$True)]
[string] $VSOAccount,
[Parameter(Mandatory=$True)]
[string] $VSOProject,
[Parameter(Mandatory=$True)]
[string] $VSORepository,
[Parameter(Mandatory=$True)]
[string] $VSOBranch,
[Parameter(Mandatory=$True)]
[string] $VSORunbookFolderPath,
[Parameter(Mandatory=$True)]
[string] $TargetCredentialName,
[Parameter(Mandatory=$True)]
[string] $TargetSubscriptionId,
[Parameter(Mandatory=$True)]
[string] $TargetAutomationAccount,
[Parameter(Mandatory=$False)]
[bool] $FlatFilesMode = $true
)
$psExtension = ".ps1"
$grExtension = ".graphrunbook"
$apiVersion = "1.0-preview"
#Getting Credentail asset for VSO alternate authentication credentail
$VSOCred = Get-AutomationPSCredential -Name $VSOCredentialName
if ($VSOCred -eq $null)
{
throw "Could not retrieve '$VSOCredentialName' credential asset. Check that you created this asset in the Automation service."
}
$VSOAuthUserName = $VSOCred.UserName
$VSOAuthPassword = $VSOCred.GetNetworkCredential().Password
#Creating authorization header using
$basicAuth = ("{0}:{1}" -f $VSOAuthUserName,$VSOAuthPassword)
$basicAuth = [System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth = [System.Convert]::ToBase64String($basicAuth)
$headers = @{Authorization=("Basic {0}" -f $basicAuth)}
#ex. "https://gkeong.visualstudio.com/defaultcollection/_apis/git/automation-git-test2-proj/repositories/automation-git-test2-proj/items?scopepath=/Project1/Project1/&recursionlevel=full&includecontentmetadata=true&versionType=branch&version=production&api-version=1.0-preview"
$VSOURL = "https://" + $VSOAccount + ".visualstudio.com/defaultcollection/_apis/git/" +
$VSOProject + "/repositories/" + $VSORepository + "/items?scopepath=" + $VSORunbookFolderPath +
"&recursionlevel=full&includecontentmetadata=true&versionType=branch&version=" + $VSOBranch +
"&api-version=" + $apiVersion
Write-Verbose("Connecting to VSO using URL: $VSOURL")
$results = Invoke-RestMethod -Uri $VSOURL -Method Get -Headers $headers
$VerbosePreference = "Continue"
#$results | ConvertTo-Json | Write-Verbose
$allRunbooks = [AzureAutomationVsoGitSync.Models.SortedRunbookCollection]@{}
#grab folders & files
$folderObj = @()
foreach ($item in $results.value)
{
if ($item.gitObjectType -eq "tree")
{
$folderObj += $item
}
elseif (($item.gitObjectType -eq "blob") -and ($item.path -match $psExtension -or $item.path -match $grExtension))
{
# get runbook file name
$path = $item.path;
$fileName = [AzureAutomationVsoGitSync.Models.Runbook]::GetRunbookFileName($path);
# local temp path for runbook
$tempPath = Join-Path -Path $env:SystemDrive -ChildPath "temp"
$outFile = Join-Path -Path $tempPath -ChildPath $fileName
# download the runbook
$fileUrl = $item.url
Write-Verbose "`tGET $fileName"
$VerbosePreference = "SilentlyContinue"
Invoke-RestMethod -Uri $fileUrl -Method Get -Headers $headers -OutFile $outFile
$VerbosePreference = "Continue"
$new = $allRunbooks.Add($outFile, $fileUrl)
}
}
# Select the Azure Subscription
$VerbosePreference = "SilentlyContinue"
$azCred = Get-AutomationPSCredential -Name $TargetCredentialName
$azAcct = Add-AzureAccount -Credential $azCred
$azSub = Select-AzureSubscription -SubscriptionId $TargetSubscriptionId
$VerbosePreference = "Continue"
if ($FlatFilesMode)
{
$sysDrive = $env:SystemDrive
# [SortedRunbookCollection].Result will be the topologically-sorted list of runbooks
# (Leaf nodes first)
$vsoApiVersion = $true
$haveSynced = @{}
$errorSync = @{}
Write-Verbose "Publish Order (by dependency):"
$sorted = $allRunbooks.Result
$sorted | Select Name | ConvertTo-Json | Write-Verbose
foreach($rb in $sorted)
{
$outFile = $rb.FilePath
$runbookName = $rb.Name
$rbType = $rb.Type
try
{
# if not yet synced .. import & add to synced collection
if (!$haveSynced.ContainsKey($runbookName))
{
$fileName = $rb.FileName
$tempPath = Join-Path -Path $env:SystemDrive -ChildPath "temp"
$outFile = Join-Path -Path $tempPath -ChildPath $fileName
$runbookName = $rb.Name
# if not yet synced .. import & add to synced collection
if (!$haveSynced.ContainsKey($runbookName))
{
#Import ps1 files into Automation, create one if doesn't exist
Write-Verbose("Importing runbook $runbookName into Automation Account...")
$arb = Get-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName -ErrorAction "SilentlyContinue"
if ($arb -eq $null)
{
Write-Verbose("`tRunbook $runbookName doesn't exist, creating it...")
New-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName
}
#Update the runbook, overwrite if existing
Write-Verbose("`tUpdating $runbookName ...")
Set-AzureAutomationRunbookDefinition -AutomationAccountName $TargetAutomationAccount -Name $runbookName -Path $outFile -Overwrite
#Publish the updated runbook
Write-Verbose("`tPublishing $runbookName ...")
Publish-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName
$haveSynced.Add($runbookName, $rb.FileUrl)
}
else
{
Write-Verbose("Runbook $runbookName already synced. Duplicate?")
}
$haveSynced.Add($runbookName, $rb.FileUrl)
}
else
{
Write-Verbose("Runbook $runbookName already synced. Duplicate?")
}
}
catch [System.Exception]
{
$ex = ConvertTo-Json $_
if (!$errorSync.ContainsKey($runbookName))
{
$errorsync.add( $runbookname, $ex )
}
Write-Verbose $ex
Write-Error $_
}
}
Write-Verbose "Done.`n"
Write-Verbose "Synced $($haveSynced.Count) of $($sorted.Count)"
#Write-Verbose "Errors $($errorSync.Count)"
if ($errorSync.Count > 0)
{
Write-Verbose "Errors:"
$errorSync | ConvertTo-Json | Write-Verbose
}
if ($haveSynced.Count -eq $sorted.Count)
{
Write-Verbose "All runbooks synced."
}
}
else
{
$haveSynced = @{}
$errorSync = @{}
#recursively go through most inner child folders first, then their parents, grand-parents, etc.
for ($i = $folderObj.count - 1; $i -ge 0; $i--)
{
Write-Verbose("Processing files in $folderObj[$i]")
$folderURL = "https://" + $VSOAccount + ".visualstudio.com/defaultcollection/_apis/git/" +
$VSOProject + "/repositories/" + $VSORepository + "/items?scopepath=" + $folderObj[$i].path +
"&recursionLevel=OneLevel&includecontentmetadata=true&versionType=branch&version=" +
$VSOBranch + "&api-version=" + $apiVersion
$results = Invoke-RestMethod -Uri $folderURL -Method Get -Headers $headers
foreach ($item in $results.value)
{
try
{
$rb = $allRunbooks.FindByUrl($item.url)
if ($rb -ne $null)
{
$fileName = $rb.FileName
$tempPath = Join-Path -Path $env:SystemDrive -ChildPath "temp"
$outFile = Join-Path -Path $tempPath -ChildPath $fileName
$runbookName = $rb.Name
# if not yet synced .. import & add to synced collection
if (!$haveSynced.ContainsKey($runbookName))
{
#Import ps1 files into Automation, create one if doesn't exist
Write-Verbose("Importing runbook $runbookName into Automation Account...")
$arb = Get-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName -ErrorAction "SilentlyContinue"
if ($arb -eq $null)
{
Write-Verbose("`tRunbook $runbookName doesn't exist, creating it...")
New-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName
}
#Update the runbook, overwrite if existing
Write-Verbose("`tUpdating $runbookName ...")
Set-AzureAutomationRunbookDefinition -AutomationAccountName $TargetAutomationAccount -Name $runbookName -Path $outFile -Overwrite
#Publish the updated runbook
Write-Verbose("`tPublishing $runbookName ...")
Publish-AzureAutomationRunbook -AutomationAccountName $TargetAutomationAccount -Name $runbookName
$haveSynced.Add($runbookName, $rb.FileUrl)
}
else
{
Write-Verbose("Runbook $runbookName already synced. Duplicate?")
}
}
}
catch [System.Exception]
{
$ex = ConvertTo-Json $_
if (!$errorSync.ContainsKey($runbookName))
{
$errorsync.add( $runbookname, $ex )
}
Write-Verbose $ex
Write-Error $_
}
}
}
Write-Verbose "Done.`n"
Write-Verbose "Synced $($haveSynced.Count) of $($allRunbooks.Results.Count)"
if ($errorSync.Count > 0)
{
Write-Verbose "Errors:"
$errorSync | ConvertTo-Json | Write-Verbose
}
if ($haveSynced.Count -gt 0 -and $haveSynced.Count -eq $results.Count)
{
Write-Verbose "All runbooks synced."
}
}
}
|
PowerShellCorpus/PowerShellGallery/InvokeTwitterAPIs/2.4/InvokeTwitterAPIs.ps1
|
InvokeTwitterAPIs.ps1
|
Publish-Module -Name InvokeTwitterAPIs -NuGetApiKey 4204f47b-136d-447d-b839-5b48634f0344
|
PowerShellCorpus/PowerShellGallery/psservicenow/0.1.13/MAKE.ps1
|
MAKE.ps1
|
function ZipFiles
{
param( $zipfilename, $sourcedir )
Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
$zipfilename, $compressionLevel, $true)
}
function New-MakePackage{
param(
[string[]]$PackageFilePatternExclusions,
[string]$PackageName,
[string]$ModuleName
)
@($FilePatternExclusions | %{"MAKE.zip" -match $_}).contains($true)
$FilesToInclude = Get-ChildItem -Path $here | ?{
$File=$_;
!$_.PSIsContainer -and
!($PackageFilePatternExclusions | %{$File.Name -match $_}).contains($true)
}
# Create temporary folder and copy the files we want into it
New-Item $here\$ModuleName -ItemType Container -Force | Out-Null
$FilesToInclude | %{Copy-Item -Path $_.FullName -Destination $here\$ModuleName\$_ -Force}
# Create a zip based on that folder (overwriting it if it already exists)
$ZipFile = "$here\$PackageName"
Remove-Item $ZipFile -Force -ErrorAction SilentlyContinue | Out-Null
ZipFiles $ZipFile $here\$ModuleName
Remove-Item $here\$ModuleName -Recurse| Out-Null
}
Function Update-CodeCoveragePercent{
param(
[int]$CodeCoverage=0,
[string]$TextFilePath="$here\Readme.md"
)
$ReadmeContent = Get-Content $TextFilePath
$ReadmeContent = $ReadmeContent | %{$_-replace "!\[Test Coverage\].+\)", ""}
Set-Content -Path $TextFilePath -Value $ReadmeContent
}
Function UpdateManifest{
param(
[string]$ManifestPath,
[string]$Version
)
Write-Verbose "Updating $ManifestPath to version $Version"
$ManifestContent = Get-Content $ManifestPath
$ManifestContent = $ManifestContent | %{$_ -replace "ModuleVersion = '(\d|\.)+'", "ModuleVersion = '$Version'"}
Set-Content -path $ManifestPath -Value $ManifestContent
}
$PackageFilePatternExclusions = @(
"MAKE\.ps1",
".+\.zip",
".+\.md"
".+\.Tests\.ps1",
"\.gitignore",
"LICENSE",
".+\.Pester.Defaults.json"
)
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$Version = "0.1.13"
$ModuleName = "PSServiceNow"
$PackageName = "$ModuleName-v$($version).zip";
# Perform Pester tests
$TestResult = Invoke-Pester -CodeCoverage '*.psm1' -PassThru
$CoveragePercent = 100-(($testResult.CodeCoverage.NumberOfCommandsMissed/$testResult.CodeCoverage.NumberOfCommandsAnalyzed)*100)
# Update/Create the package and
if($TestResult.FailedCount -eq 0){
New-MakePackage -PackageFilePatternExclusions $PackageFilePatternExclusions -PackageName $PackageName -ModuleName $ModuleName
Update-CodeCoveragePercent -CodeCoverage $CoveragePercent
UpdateManifest -ManifestPath "$here\$ModuleName.psd1" -Version $Version
}
|
PowerShellCorpus/PowerShellGallery/psservicenow/0.1.13/PSServiceNow.Tests.ps1
|
PSServiceNow.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$DefaultsFile = "$here\PSServiceNow.Pester.Defaults.json"
# Load defaults from file (merging into $global:ServiceNowPesterTestDefaults
if(Test-Path $DefaultsFile){
$defaults = if($global:ServiceNowPesterTestDefaults){$global:ServiceNowPesterTestDefaults}else{@{}};
(Get-Content $DefaultsFile | Out-String | ConvertFrom-Json).psobject.properties | %{$defaults."$($_.Name)" = $_.Value}
# Prompt for credentials
$defaults.Creds = if($defaults.Creds){$defaults.Creds}else{Get-Credential}
$global:ServiceNowPesterTestDefaults = $defaults
}else{
Write-Error "$DefaultsFile does not exist. Created example file. Please populate with your values";
# Write example file
@{
ServiceNowURL = 'testingurl.service-now.com'
TestCategory = 'Internal'
TestUserGroup = 'e9e9a2406f4c35001855fa0dba3ee4f3'
TestUser = "7a4b573a6f3725001855fa0dba3ee485"
} | ConvertTo-Json | Set-Content $DefaultsFile
return;
}
# Load the module (unload it first in case we've made changes since loading it previously)
Remove-Module PSServiceNow -ErrorAction SilentlyContinue
Import-Module $here\PSServiceNow.psd1
Describe "ServiceNow-Module" {
It "Set-ServiceNowAuth works" {
Set-ServiceNowAuth -url $defaults.ServiceNowURL -Credentials $defaults.Creds | Should be $true
}
It "New-ServiceNowIncident (and by extension New-ServiceNowTableEntry) works" {
$TestTicket = New-ServiceNowIncident -ShortDescription "Testing with Pester" `
-Description "Long description" -AssignmentGroup $defaults.TestUserGroup `
-Category $defaults.TestCategory -SubCategory $Defaults.TestSubcategory `
-Comment "Comment" -ConfigurationItem $defaults.TestConfigurationItem `
-Caller $defaults.TestUser `
$TestTicket.short_description | Should be "Testing with Pester"
}
It "Get-ServiceNowTable works" {
# There should be one or more incidents returned
(Get-ServiceNowTable -Table 'incident' -Query 'ORDERBYDESCopened_at').Count -gt 0 | Should Match $true
}
It "Get-ServiceNowIncident works" {
# There should be one or more incidents returned
(Get-ServiceNowIncident).Count -gt 0 | Should Match $true
}
It "Update-ServiceNowIncident works" {
$TestTicket = New-ServiceNowIncident -ShortDescription "Testing Ticket Update with Pester" `
-Description "Long description" -AssignmentGroup $defaults.TestUserGroup `
-Category $defaults.TestCategory -SubCategory $Defaults.TestSubcategory `
-Comment "Comment" -ConfigurationItem $defaults.TestConfigurationItem `
-Caller $defaults.TestUser `
$TestTicket.short_description | Should be "Testing Ticket Update with Pester"
$Values =
@{
'short_description' = 'Ticket Updated with Pester'
'description' = 'Even Longer Description'
}
Update-ServiceNowIncident -SysId $TestTicket.sys_id -Values $Values
$TestTicket = Get-ServiceNowIncident -MatchExact @{sys_id=$TestTicket.sys_id}
$TestTicket.short_description | Should be "Ticket Updated with Pester"
$TestTicket.description | Should be "Even Longer Description"
}
It "Get-ServiceNowUserGroup works" {
# There should be one or more user groups returned
(Get-ServiceNowUserGroup).Count -gt 0 | Should Match $true
}
It "Get-ServiceNowUser works" {
# There should be one or more user groups returned
(Get-ServiceNowUser).Count -gt 0 | Should Match $true
}
It "Get-ServiceNowConfigurationItem works" {
# There should be one or more configuration items returned
(Get-ServiceNowConfigurationItem).Count -gt 0 | Should Match $true
}
It "Get-ServiceNowChangeRequest works" {
(Get-ServiceNowChangeRequest).Count -gt 0 | Should Match $true
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Write-RGB.ps1
|
Write-RGB.ps1
|
function Write-RGB {
<#
.SYNOPSIS
Write to the console in 24-bit colors!
.DESCRIPTION
This function lets you write to the console using 24-bit color depth.
You can specify colors using its RGB values.
.EXAMPLE
Write-RGB 'PowerShell rocks!'
Will write the text using the default colors.
.EXAMPLE
Write-RGB 'PowerShell rocks!' -ForegroundColor ([rgb]::new(255,192,203))
Will write the text in a pink foreground color.
.EXAMPLE
Write-RGB 'PowerShell rocks!' -ForegroundColor ([rgb]::new(255,192,203)) -BackgroundColor ([rgb]::new(128,128,0))
Will write the text in a pink foreground color and an olive background color.
.NOTES
Author: Øyvind Kallstad
Version: 1.0
Date: 23.09.2016
.LINK
https://communary.net/
#>
[CmdletBinding()]
param (
# The text you want to write.
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty()]
[string] $Text,
# The foreground color of the text. Defaults to white.
[Parameter(Position = 1)]
[rgb] $ForegroundColor = [rgb]::new(255,255,255),
# The background color of the text. Defaults to PowerShell Blue.
[Parameter(Position = 2)]
[rgb] $BackgroundColor = [rgb]::new(1,36,86),
# No newline after the text.
[Parameter()]
[switch] $NoNewLine
)
if ($PSVersionTable.PSVersion.Build -ge 14931) {
$escape = [char]27 + '['
$resetAttributes = "$($escape)0m"
$foreground = "$($escape)38;2;$($ForegroundColor.Red);$($ForegroundColor.Green);$($ForegroundColor.Blue)m"
$background = "$($escape)48;2;$($BackgroundColor.Red);$($BackgroundColor.Green);$($BackgroundColor.Blue)m"
Write-Host ($foreground + $background + $Text + $resetAttributes) -NoNewline:$NoNewLine
}
else {
Write-Warning "This function will only work with build 14931 or above. Your build version is $($PSVersionTable.PSVersion.Build)"
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Invoke-PathShortener.ps1
|
Invoke-PathShortener.ps1
|
function Invoke-PathShortener {
<#
.SYNOPSIS
Path Shortener
.EXAMPLE
Invoke-PathShortener
Will take the current path and shortened it using default values.
.EXAMPLE
Invoke-PathShortener -KeepBefore 3
Will shorten the current path and keep the first 3 parts and last 1.
.EXAMPLE
Invoke-PathShortener -KeepBefore 3 -KeepAfter 2
Will shorten the current path and keep the first 3 parts and the last 2 parts.
.EXAMPLE
'C:\Windows\System32\WindowsPowerShell\v1.0\Modules' | Invoke-PathShortener -TruncateChar ([char]8230)
Will shorten the path piped in from the pipeline, using a custom truncate character.
.NOTES
Author: Øyvind Kallstad
Date: 10.09.2016
Version: 2.1
#>
[CmdletBinding()]
param (
# Path to shorten.
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullorEmpty()]
[string] $Path = (Get-Location),
# Number of parts to keep before truncating. Default value is 2.
[Parameter()]
[ValidateRange(0, [int32]::MaxValue)]
[int] $KeepBefore = 2,
# Number of parts to keep after truncating. Default value is 1.
[Parameter()]
[ValidateRange(1, [int32]::MaxValue)]
[int] $KeepAfter = 1,
# Path separator character.
[Parameter()]
[string] $Separator = [System.IO.Path]::DirectorySeparatorChar,
# Truncate character(s). Default is '...'
# Use '[char]8230' to use the horizontal ellipsis character instead.
[Parameter()]
[string] $TruncateChar = '...'
)
$Path = (Resolve-Path -Path $Path).Path
$splitPath = $Path.Split($Separator, [System.StringSplitOptions]::RemoveEmptyEntries)
if ($splitPath.Count -gt ($KeepBefore + $KeepAfter)) {
$outPath = [string]::Empty
for ($i = 0; $i -lt $KeepBefore; $i++) {
$outPath += $splitPath[$i] + $Separator
}
$outPath += "$($TruncateChar)$($Separator)"
for ($i = ($splitPath.Count - $KeepAfter); $i -lt $splitPath.Count; $i++) {
if ($i -eq ($splitPath.Count - 1)) {
$outPath += $splitPath[$i]
}
else {
$outPath += $splitPath[$i] + $Separator
}
}
}
else {
$outPath = $splitPath -join $Separator
if ($splitPath.Count -eq 1) {
$outPath += $Separator
}
}
Write-Output $outPath
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Set-PowerlinePrompt.ps1
|
Set-PowerlinePrompt.ps1
|
function Set-PowerlinePrompt {
$global:branchSymbol = [char]57504
$global:dividerSymbolFull = [char]57520
$global:arrowUpSymbol = [char]42779
$global:arrowDownSymbol = [char]42780
$global:isAdmin = Test-IsAdmin
if (Get-Module -Name 'psgit' -ListAvailable) {
$customPrompt = {
$currentLocation = $executionContext.SessionState.Path.CurrentLocation.ToString()
if (Test-MasterVolumeIsMuted) {
$volumeString = '(MUTE)'
}
else {
$volumeString = '(' + "$(Get-MasterVolume)".PadLeft(3, ' ') + '%)'
}
$host.UI.RawUI.WindowTitle = "$($volumeString) $($currentLocation)"
if ([bool]($gitStatus = Get-GitStatus -WarningAction SilentlyContinue)) {
$branch = $gitStatus.Branch
if ($isAdmin) {
Write-Host " $($branchSymbol) $($branch) " -NoNewline -BackgroundColor DarkRed
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkRed -BackgroundColor Gray
}
else {
Write-Host " $($branchSymbol) $($branch) " -NoNewline -BackgroundColor DarkGray
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkGray -BackgroundColor Gray
}
}
else {
if (Test-Path variable:/PSDebugContext) {
Write-Host ' DBG ' -NoNewline -BackgroundColor DarkGray -ForegroundColor DarkRed
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkGray -BackgroundColor Gray
}
elseif($isAdmin){
Write-Host " $($env:COMPUTERNAME) " -NoNewLine -BackgroundColor DarkRed
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkRed -BackgroundColor Gray
}
else{
Write-Host " $($env:COMPUTERNAME) " -NoNewLine -BackgroundColor DarkGray
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkGray -BackgroundColor Gray
}
}
Write-Host "$(Invoke-PathShortener -Path $currentLocation) " -NoNewLine -BackgroundColor Gray -ForegroundColor Black
if ([bool]$gitStatus) {
if ([bool]([array]$gitChange = Get-GitChange)) {
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor Gray -BackgroundColor DarkRed
if (($gitStatus.Ahead -gt 0) -or ($gitStatus.Behind -gt 0)) {
Write-Host "$($arrowUpSymbol)$($gitStatus.Ahead) $($arrowDownSymbol)$($gitStatus.Behind) " -BackgroundColor DarkRed -NoNewline
}
Write-Host "+$(($gitChange.Where({$_.Change -eq 'Added'})).Count) ~$(($gitChange.Where({$_.Change -eq 'Modified'})).Count) -$(($gitChange.Where({$_.Change -eq 'Removed'})).Count) " -NoNewline -BackgroundColor DarkRed
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkRed
}
elseif (($gitStatus.Ahead -gt 0) -or ($gitStatus.Behind -gt 0)) {
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor Gray -BackgroundColor DarkGreen
Write-Host "$($arrowUpSymbol)$($gitStatus.Ahead) $($arrowDownSymbol)$($gitStatus.Behind) " -BackgroundColor DarkGreen -NoNewline
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor DarkGreen
}
else {
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor Gray
}
}
else {
Write-Host $dividerSymbolFull -NoNewline -ForegroundColor Gray
}
return ' '
}
Set-Prompt -ScriptBlock $customPrompt
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/volumeControls.ps1
|
volumeControls.ps1
|
function Get-MasterVolume {
Write-Output ([Math]::Round([CoreAudio.API]::GetMasterVolume(),0))
}
function Set-MasterVolume {
param([int]$Volume)
if ($Volume) {
[CoreAudio.API]::SetMasterVolume($Volume)
}
}
function Test-MasterVolumeIsMuted {
[CoreAudio.API]::GetMasterVolumeMute()
}
function Invoke-MuteMasterVolume {
$res = [CoreAudio.API]::ToggleMasterVolumeMute()
if ($res) {
Write-Output 'Master Volume Muted'
}
else {
$vol = Get-MasterVolume
Write-Output "Master Volume: $($vol)%"
}
}
function Invoke-MasterVolumeControl {
if (-not $args) {
Get-MasterVolume
break
}
switch ($args) {
'm' {Invoke-MuteMasterVolume;break}
{$_ -in 1..100} {Set-MasterVolume $_;Write-Output $_;break}
DEFAULT {Get-MasterVolume}
}
}
New-Alias -Name 'vol' -Value 'Invoke-MasterVolumeControl' -Force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Invoke-Highlight.ps1
|
Invoke-Highlight.ps1
|
function Invoke-Highlight {
<#
.SYNOPSIS
Highlight patterns in string(s).
.DESCRIPTION
This function will let you define a regular expression pattern and
highlight matches in a string or string array.
.EXAMPLE
Get-Content .\file.txt | Invoke-Highlight error
Will output the contents of .\file.txt and highlight all occurences of 'error'
.NOTES
Author: Øyvind Kallstad
Date: 02.09.2016
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
[string[]]$InputObject,
# Specifies the text you want to highlight, as a regular expression.
[Parameter(Position = 0)]
[string] $Pattern,
# Makes matches case-sensitive. By default, matches are not case-sensitive.
[Parameter()]
[switch] $CaseSensitive
)
PROCESS {
foreach ($item in $InputObject) {
# Get matches
$match = $item | Select-String -Pattern $Pattern -AllMatches -CaseSensitive:$CaseSensitive
# Set initial index
$index = 0
# Loop through matches
foreach ($matchItem in ($match.Matches | Sort-Object -Property Index)) {
# Before match
$thisLength = $matchItem.Index - $index
Write-Host $item.SubString($index,$thisLength) -NoNewline
# Match
Write-Host $item.SubString($matchItem.Index,$matchItem.Length) -ForegroundColor Red -NoNewline
# Calculate new index
$index = $matchItem.Index + $matchItem.Length
}
# Write the rest of the line
$thisLength = $item.ToCharArray().Length - $index
Write-Host $item.SubString($index,$thisLength)
}
}
}
New-Alias -Name 'highlight' -Value 'Invoke-Highlight' -force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Invoke-Pause.ps1
|
Invoke-Pause.ps1
|
function Invoke-Pause {
<#
.SYNOPSIS
Will pause output of large objects.
.DESCRIPTION
This function will stop output of large objects at windows height,
and lets you continue by pressing any key.
.EXAMPLE
Get-Content -Path file.txt | Invoke-Pause
.EXAMPLE
Get-Command Get-* | Invoke-Pause
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$InputObject
)
BEGIN {
if ($host.Name -eq 'ConsoleHost') {
$windowHeight = [console]::WindowHeight
$usableHeight = $windowHeight - 2
$lines = 0
}
}
PROCESS {
foreach ($item in $InputObject) {
if ($host.Name -eq 'ConsoleHost') {
$lines++
Write-Output $item
if ($lines -eq $usableHeight) {
Write-Host ''
Write-Host 'Press any key to continue ...' -NoNewline
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ''
$lines = 0
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Invoke-Touch.ps1
|
Invoke-Touch.ps1
|
function Invoke-Touch {
<#
.SYNOPSIS
PowerShell inplementation of the Unix/Linux utility called touch.
.DESCRIPTION
Touch let's you update the access date and / or modification date of a file. If the file don't exist, an empty file will be created
unless you use the DoNotCreateNewFile parameter. This implementation have the original parameter names added as
aliases, so if you are familiar with the original touch utility it should be easy to use this one.
.EXAMPLE
Invoke-Touch newfile
Will create a new empty file called 'newfile' in the current folder.
.EXAMPLE
Invoke-Touch newfile3 -DateTime '10.10.2014'
Will create a new empty file called 'newfile3' with the provided date.
.EXAMPLE
Invoke-Touch newfile -r newfile3
Will update the timestamp of 'newfile' using 'newfile3' as a reference.
.LINK
https://gist.github.com/gravejester/f4934a5ce16c652d11d3
.NOTES
*** THIS FUNCTION IS USING 'Resolve-PathEx' AND WON'T WORK WITHOUT IT ***
Author: Øyvind Kallstad
Date: 13.11.2014
Version: 1.0
#>
[CmdletBinding(ConfirmImpact = 'Low',SupportsShouldProcess, DefaultParameterSetName = 'UserDateTime')]
param (
# Filename and/or path.
[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
[string[]] $Path,
# File to use as a timestamp reference.
[Parameter(ParameterSetName = 'ReferenceDateTime')]
[Alias('r')]
[string] $Reference,
# Timestamp offset in seconds.
[Parameter()]
[Alias('B','F')]
[int] $OffsetSeconds = 0,
# Used to override the timestamp. If omitted the current date and time will be used.
[Parameter(ParameterSetName = 'UserDateTime')]
[Alias('t','d')]
[string] $DateTime,
# Update Last Access Time.
[Parameter()]
[Alias('a')]
[switch] $AccessTime,
# Update Last Write Time.
[Parameter()]
[Alias('m','w')]
[switch] $WriteTime,
# Switch to override the basic functionality of creating a new file if it don't exist already.
[Parameter()]
[Alias('c')]
[switch] $DoNotCreateNewFile,
[Parameter()]
[switch] $PassThru
)
BEGIN {
try {
# use timestamp from a reference file
if (-not([string]::IsNullOrEmpty($Reference))) {
if (Test-Path $Reference) {
$referenceFile = Get-ChildItem -Path $Reference
$newLastAccessTime = ($referenceFile.LastAccessTime).AddSeconds($OffsetSeconds)
$newLastWriteTime = ($referenceFile.LastWriteTime).AddSeconds($OffsetSeconds)
Write-Verbose "Using timestamp from $Reference"
}
else {
Write-Warning "$Reference not found!"
}
}
# use timestamp from user input
elseif (-not([string]::IsNullOrEmpty($DateTime))) {
$userDateTime = [DateTime]::Parse($DateTime,[CultureInfo]::CurrentCulture,[System.Globalization.DateTimeStyles]::NoCurrentDateDefault)
Write-Verbose "Using timestamp from user input: $DateTime (Parsed: $($userDateTime))"
}
# use timestamp from current date/time
else {
$currentDateTime = (Get-Date).AddSeconds($OffsetSeconds)
$newLastAccessTime = $currentDateTime
$newLastWriteTime = $currentDateTime
Write-Verbose "Using timestamp from current date/time: $currentDateTime"
}
}
catch {
Write-Warning $_.Exception.Message
}
}
PROCESS {
foreach ($thisPath in $Path) {
try {
$thisPathResolved = Resolve-PathEx -Path $thisPath
foreach ($p in $thisPathResolved.Path) {
Write-Verbose "Resolved path: $p"
# if file is not found, and it's ok to create a new file, create it!
if (-not(Test-Path $p)) {
if ($DoNotCreateNewFile) {
Write-Verbose "$p not created"
return
}
else {
if ($PSCmdlet.ShouldProcess($p, 'Create File')) {
$null = New-Item -path $p -ItemType 'File' -ErrorAction 'Stop'
}
}
}
# get fileinfo object
$fileObject = Get-ChildItem $p -ErrorAction SilentlyContinue
if (-not([string]::IsNullOrEmpty($fileObject))) {
# handle date & time if datetime parameter is used
if (-not([string]::IsNullOrEmpty($DateTime))) {
# if parsed datetime object contains time
if ([bool]$userDateTime.TimeOfDay.Ticks) {
Write-Verbose 'Found time in datetime'
$userTime = $userDateTime.ToLongTimeString()
}
# else, get time from file
else {
Write-Verbose 'Did not find time in datetime - using time from file'
$userTime = $fileObject.LastAccessTime.ToLongTimeString()
}
# if parsed datetime object contains date
if ([bool]$userDateTime.Date.Ticks) {
Write-Verbose 'Found date in datetime'
$userDate = $userDateTime.ToShortDateString()
}
# else, get date from file
else {
Write-Verbose 'Did not find date in datetime - using date from file'
$userDate = $fileObject.LastAccessTime.ToShortDateString()
}
# parse the new datetime
$parsedNewDateTime = [datetime]::Parse("$userDate $userTime")
# add offset and save to the appropriate variables
$newLastAccessTime = $parsedNewDateTime.AddSeconds($OffsetSeconds)
$newLastWriteTime = $parsedNewDateTime.AddSeconds($OffsetSeconds)
}
}
if ($PSCmdlet.ShouldProcess($p, 'Update Timestamp')) {
# if neither -AccessTime nor -WriteTime is used, update both Last Access Time and Last Write Time
if ((-not($AccessTime)) -and (-not($WriteTime))) {
$fileObject.LastAccessTime = $newLastAccessTime
$fileObject.LastWriteTime = $newLastWriteTime
}
else {
if ($AccessTime) { $fileObject.LastAccessTime = $newLastAccessTime }
if ($WriteTime) { $fileObject.LastWriteTime = $newLastWriteTime }
}
}
}
if ($PassThru) {
Write-Output (Get-ChildItem $p)
}
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}
New-Alias -Name 'Touch' -Value 'Invoke-Touch' -Force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Set-Prompt.ps1
|
Set-Prompt.ps1
|
function Set-Prompt {
param ([ScriptBlock] $ScriptBlock)
$null = New-Item -Path function:prompt -Value $ScriptBlock -Force
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Show-Calendar.ps1
|
Show-Calendar.ps1
|
function Show-Calendar {
<#
.SYNOPSIS
Show calendar.
.DESCRIPTION
This function is a PowerShell version of the *NIX cal command and will show a
calendar of the chosen month(s). The current day will be marked with a '*'.
For best results, use together with the FormatPx module by Kirk Munro.
.EXAMPLE
Show-Calendar
Will show a calendar view of the current month.
.EXAMPLE
Show-Calendar -InvariantCulture
Will show a calendar view of the current month, using the Invariant Culture
.EXAMPLE
Show-Calendar -Culture 'de-DE'
Will show a calendar view of the current month, using the de-DE (German) culture.
.EXAMPLE
Show-Calendar 1 2015 -m 3
Will show a calendar view of the first three months in 2015.
.EXAMPLE
Show-Calendar 12 -MarkDay 25 -Abbreviated
Will show a calendar view of december and mark December 25, with abbreviated day names.
.EXAMPLE
Show-Calendar 1 2015 -m 12 -MarkDate (Get-Date -Year 2015 -Month 2 -Day 14)
Will show a calendar view of 2015 and mark 14th of February.
.LINK
https://github.com/KirkMunro/FormatPx
.NOTES
Author: Øyvind Kallstad
Date: 21.12.2014
Version: 1.1
22.12.2014
Added Alignment parameter
Made the entire function culture aware
Added support for abbreviated day names
#>
[CmdletBinding(DefaultParameterSetName = 'Culture')]
param (
# The starting month number. Default is current month.
[Parameter(Position = 0)]
[Alias('Month')]
[ValidateRange(1,12)]
[int] $StartMonth = [DateTime]::Now.Month,
# The starting year. Default is current year.
[Parameter(Position = 1)]
[Alias('Year')]
[ValidateRange(1,9999)]
[int32] $StartYear = [DateTime]::Now.Year,
# How many months to show. Default is 1.
[Parameter()]
[Alias('m')]
[ValidateRange(1,[int]::MaxValue)]
[int32] $Months = 1,
# Day to mark on the calendar.
[Parameter()]
[ValidateRange(1,31)]
[int32] $MarkDay,
# Date to mark on the calendar.
[Parameter()]
[datetime] $MarkDate,
# Set alignment of the dates in the output. Default value is 'Right'.
[Parameter()]
[ValidateSet('Left','Right')]
[string] $Alignment = 'Right',
# Use the Invariant Culture (English).
[Parameter(ParameterSetName = 'InvariantCulture')]
[switch] $InvariantCulture,
# Use this parameter to choose what culture to use. If this parameter is not used and
# the InvariantCulture parameter is false, the current culture will be used instead.
[Parameter(ParameterSetName = 'Culture')]
[string] $Culture,
# Use this parameter to use abbreviated day names. Default is to use the full name of days.
[Parameter()]
[switch] $AbbreviatedDayNames
)
function New-DayOfWeekString {
<#
.SYNPSIS
Output a culture aware string of a specified week day.
.NOTES
Author: Øyvind Kallstad
#>
[CmdletBinding()]
[OutputType([String])]
param (
# The day of week in Invariant Culture (English).
[Parameter(Position = 0, Mandatory)]
[System.DayOfWeek] $DayOfWeek,
[Parameter(Position = 1, ValueFromPipeline)]
[CultureInfo] $CultureInfo = [System.Globalization.CultureInfo]::CurrentCulture,
# Show the week day in an abbreviated form.
[Parameter()]
[switch] $Abbreviated
)
if ($Abbreviated) {
Write-Output ($cultureInfo.TextInfo.ToTitleCase($cultureInfo.DateTimeFormat.GetAbbreviatedDayName([System.DayOfWeek]::$DayOfWeek)))
}
else {
Write-Output ($cultureInfo.TextInfo.ToTitleCase($cultureInfo.DateTimeFormat.GetDayName([System.DayOfWeek]::$DayOfWeek)))
}
}
function New-Week {
<#
.SYNOPSIS
Returns an ordered dictionary representing a week.
.NOTES
Author: Øyvind Kallstad
#>
[CmdletBinding()]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
param (
[Parameter(Position = 0, ValueFromPipeline)]
[CultureInfo] $CultureInfo = [System.Globalization.CultureInfo]::CurrentCulture,
# Show the week day in an abbreviated form.
[Parameter()]
[switch] $Abbreviated
)
$propHash = @{
CultureInfo = $CultureInfo
}
if ($Abbreviated) {
$propHash.Abbreviated = $true
}
# define week day names
$monday = New-DayOfWeekString 'Monday' @propHash
$tuesday = New-DayOfWeekString 'Tuesday' @propHash
$wednesday = New-DayOfWeekString 'Wednesday' @propHash
$thursday = New-DayOfWeekString 'Thursday' @propHash
$friday = New-DayOfWeekString 'Friday' @propHash
$saturday = New-DayOfWeekString 'Saturday' @propHash
$sunday = New-DayOfWeekString 'Sunday' @propHash
$week = [Ordered] @{
$tuesday = $null
$wednesday = $null
$thursday = $null
$friday = $null
$saturday = $null
}
if (($CultureInfo.DateTimeFormat.FirstDayOfWeek) -eq 'Monday') {
$week.Insert(0, $monday, $null)
$week.Add($sunday, $null)
}
else {
$week.Insert(0, $sunday, $null)
$week.Insert(1, $monday, $null)
}
Write-Output $week
}
# get a CultureInfo object based on user input
# either with an Invariant Culture...
if ($InvariantCulture) {
$cultureInfo = [System.Globalization.CultureInfo]::InvariantCulture
}
# ... user defined culture...
elseif ($Culture) {
$cultureInfo = [System.Globalization.CultureInfo]::CreateSpecificCulture($Culture)
}
# ... or the current culture
else {
$cultureInfo = [System.Globalization.CultureInfo]::CurrentCulture
}
# supporting internationalization
# add additional languages as needed
switch ($cultureInfo.Name) {
'nb-NO' {$translate = @{Year = 'År'; Month = 'Måned'; Week = 'Uke'}} # Norwegian (Bokmål)
'da-DK' {$translate = @{Year = 'År'; Month = 'Måned'; Week = 'Uge'}} # Danish
'sv-SE' {$translate = @{Year = 'År'; Month = 'Månad'; Week = 'Vecka'}} # Swedish
'fi-FI' {$translate = @{Year = 'Vuosi'; Month = 'Kuukausi'; Week = 'Viikko'}} # Finnish
'de-DE' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German
'de-AT' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German (Austria)
'de-CH' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German (Switzerland)
'nl-NL' {$translate = @{Year = 'Jaar'; Month = 'Maand'; Week = 'Week'}} # Dutch
'fr-FR' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French
'fr-CH' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French (Switzerland)
'fr-LU' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French (Luxembourg)
'it-IT' {$translate = @{Year = 'Anno'; Month = 'Mese'; Week = 'Settimana'}} # Italian
'es-ES' {$translate = @{Year = 'Año'; Month = 'Mes'; Week = 'Semana'}} # Spanish
'ru-RU' {$translate = @{Year = 'Год'; Month = 'Месяц'; Week = 'Неделя'}} # Russian
'cs-CZ' {$translate = @{Year = 'Rok'; Month = 'Měsíc'; Week = 'Týden'}} # Czech
'ms-MY' {$translate = @{Year = 'Tahun'; Month = 'Bulan'; Week = 'Minggu'}} # Malay
'ja-JP' {$translate = @{Year = '年'; Month = '月'; Week = '1週間'}} # Japanese
'is-IS' {$translate = @{Year = 'Ári'; Month = 'Mánuði'; Week = 'Viku'}} # Icelandic
'pl-PL' {$translate = @{Year = 'Rok'; Month = 'Miesiąc'; Week = 'Tydzień'}} # Polish
'cy-GB' {$translate = @{Year = 'Blwyddyn'; Month = 'Mis'; Week = 'Wythnos'}} # Welsh (United Kingdom)
DEFAULT {$translate = @{Year = 'Year'; Month = 'Month'; Week = 'Week'}} # Invariant Culture (English)
}
$thisMonth = $StartMonth - 1
$thisYear = $StartYear
$output = @()
$weekProperties = @{}
if ($AbbreviatedDayNames) { $weekProperties.Abbreviated = $true }
# loop through the months
for ($i = 1; $i -le $Months; $i++) {
# increment month
$thisMonth++
# when month is greater than 12, a new year is triggered, so reset month to 1 and increment year
if ($thisMonth -gt 12) {
$thisMonth = 1
$thisYear++
}
# get the number of days in the month
$daysInMonth = $cultureInfo.Calendar.GetDaysInMonth($thisYear,$thisMonth)
# define new week
$thisWeek = $cultureInfo | New-Week @weekProperties
$thisWeek.Insert(0, $translate.Month, $null)
$thisWeek.Insert(1, $translate.Year, $null)
$thisWeek.Insert(2, $translate.Week, $null)
# loop through each day in the month
for ($y = 1; $y -lt ($daysInMonth + 1); $y++) {
# get a datetime object of the current date
$thisDate = New-Object -TypeName 'System.DateTime' -ArgumentList ($thisYear,$thisMonth,$y,$cultureInfo.Calendar)
# if current date is the first day of a week (but not if it's the very first day of the month at the same time)
if (($thisDate.DayOfWeek -eq ($cultureInfo.DateTimeFormat.FirstDayOfWeek)) -and ($y -gt 1)) {
# add the week object to the output array
$weekObject = New-Object -TypeName 'PSCustomObject' -Property $thisWeek
$output += $weekObject
# reset the week
$thisWeek = $cultureInfo | New-Week @weekProperties
$thisWeek.Insert(0, $translate.Month, $null)
$thisWeek.Insert(1, $translate.Year, $null)
$thisWeek.Insert(2, $translate.Week, $null)
}
# get string representation of the month and the current week number (if week number is 53, change to 1)
$monthString = $cultureInfo.TextInfo.ToTitleCase($thisDate.ToString('MMMM',$cultureInfo))
$thisWeekNumber = $cultureInfo.calendar.GetWeekOfYear($thisDate,$cultureInfo.DateTimeFormat.CalendarWeekRule,$cultureInfo.DateTimeFormat.FirstDayOfWeek)
if ($thisWeekNumber -eq 53) { $thisWeekNumber = 1 }
# overload the ToString method of the datetime object
$thisDate | Add-Member -MemberType ScriptMethod -Name 'ToString' -Value {
# mark today with '*'
if (($this.Date) -eq ([DateTime]::Now.Date)) {
if($Alignment -eq 'Left') {$this.Day.ToString() + '*'}
else {'*' + $this.Day.ToString()}
}
elseif ($MarkDay -eq $this.Day) {
if($Alignment -eq 'Left') {$this.Day.ToString() + '!'}
else {'!' + $this.Day.ToString()}
}
elseif ($MarkDate.Date -eq $this.Date) {
if($Alignment -eq 'Left') {$this.Day.ToString() + '!'}
else {'!' + $this.Day.ToString()}
}
else {
$this.Day.ToString()
}
} -Force
# update the week hashtable with the current day, week, month and year
$thisWeek[($cultureInfo | New-DayOfWeekString ($thisDate.DayOfWeek) -Abbreviated:$AbbreviatedDayNames)] = $thisDate
$thisWeek[$translate.Week] = $thisWeekNumber
$thisWeek[$translate.Month] = $monthString
$thisWeek[$translate.Year] = $thisYear
}
# add the final week to the output array
$weekObject = New-Object -TypeName 'PSCustomObject' -Property $thisWeek
$output += $weekObject
}
# translate day names
$monday = $cultureInfo | New-DayOfWeekString 'Monday' -Abbreviated:$AbbreviatedDayNames
$tuesday = $cultureInfo | New-DayOfWeekString 'Tuesday' -Abbreviated:$AbbreviatedDayNames
$wednesday = $cultureInfo | New-DayOfWeekString 'Wednesday' -Abbreviated:$AbbreviatedDayNames
$thursday = $cultureInfo | New-DayOfWeekString 'Thursday' -Abbreviated:$AbbreviatedDayNames
$friday = $cultureInfo | New-DayOfWeekString 'Friday' -Abbreviated:$AbbreviatedDayNames
$saturday = $cultureInfo | New-DayOfWeekString 'Saturday' -Abbreviated:$AbbreviatedDayNames
$sunday = $cultureInfo | New-DayOfWeekString 'Sunday' -Abbreviated:$AbbreviatedDayNames
# define a hashtable to hold format properties for the table output
if (($cultureInfo.DateTimeFormat.FirstDayOfWeek) -eq 'Monday') {
$formatProperties = @{
Property =
"$($translate.Week)",
@{Name = "$monday" ;Expression = {$_.$monday} ;Alignment = $Alignment},
@{Name = "$tuesday" ;Expression = {$_.$tuesday} ;Alignment = $Alignment},
@{Name = "$wednesday" ;Expression = {$_.$wednesday} ;Alignment = $Alignment},
@{Name = "$thursday" ;Expression = {$_.$thursday} ;Alignment = $Alignment},
@{Name = "$friday" ;Expression = {$_.$friday} ;Alignment = $Alignment},
@{Name = "$saturday" ;Expression = {$_.$saturday} ;Alignment = $Alignment},
@{Name = "$sunday" ;Expression = {$_.$sunday} ;Alignment = $Alignment}
}
}
else {
$formatProperties = @{
Property =
"$($translate.Week)",
@{Name = "$sunday" ;Expression = {$_.$sunday} ;Alignment = $Alignment},
@{Name = "$monday" ;Expression = {$_.$monday} ;Alignment = $Alignment},
@{Name = "$tuesday" ;Expression = {$_.$tuesday} ;Alignment = $Alignment},
@{Name = "$wednesday" ;Expression = {$_.$wednesday} ;Alignment = $Alignment},
@{Name = "$thursday" ;Expression = {$_.$thursday} ;Alignment = $Alignment},
@{Name = "$friday" ;Expression = {$_.$friday} ;Alignment = $Alignment},
@{Name = "$saturday" ;Expression = {$_.$saturday} ;Alignment = $Alignment}
}
}
# if FormatPx is loaded, use it to format the output
if (Get-Module -Name 'FormatPx') {
Write-Output ($output | Format-Table @formatProperties -AutoSize -GroupBy @{Name = "$($translate.Month)";Expression = {"$($_.($translate.Month)) $($_.($translate.Year))"}} -PersistWhenOutput)
}
# else use default PowerShell formatting
else {
Write-Output ($output | Format-Table @formatProperties -AutoSize -GroupBy @{Name = "$($translate.Month)";Expression = {"$($_.($translate.Month)) $($_.($translate.Year))"}})
}
}
New-Alias -Name 'cal' -Value 'Show-Calendar' -Force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Test-IsAdmin.ps1
|
Test-IsAdmin.ps1
|
function Test-IsAdmin {
$windowsIdentity=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($windowsIdentity)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
Write-Output ($windowsPrincipal.IsInRole($adm))
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Get-ArchiveContents.ps1
|
Get-ArchiveContents.ps1
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Get-ArchiveContents {
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)]
[string] $Path
)
$Path = Resolve-Path -Path $Path
$contents = [System.IO.Compression.ZipFile]::OpenRead($Path)
$contents.Entries | Select-Object FullName, LastWriteTime, CompressedLength,Length
$contents.Dispose()
}
New-Alias -Name 'peek' -Value 'Get-ArchiveContents' -Force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Invoke-ColorizedFileListing.ps1
|
Invoke-ColorizedFileListing.ps1
|
function Invoke-ColorizedFileListing {
<#
.SYNOPSIS
Provides colorized file listing.
.DESCRIPTION
This function is a replacement for Get-ChildItem when used to
list files and folders, and adds colorization of file types
as well as humanized dates and file sizes.
.EXAMPLE
Invoke-ColorizedFileListing
Will list the contents of the current folder.
.EXAMPLE
Invoke-ColorizedFileListing c:\ -Force
Will list all contents of c:\, including hidden files.
.EXAMPLE
Get-ChildItem c:\windows\*.log | Invoke-ColorizedFileListing
Will list all log files in the c:\windows directory.
.NOTES
Author: Øyvind Kallstad
Version: 1.0
Date: 31.08.2016
Dependencies: PowerShellHumanizer
#>
[CmdletBinding(DefaultParameterSetName = 'Path')]
param (
# Path. Will be forwarded to Get-ChildItem. Default value is '.'
[Parameter(ParameterSetName = 'Path', Position = 0)]
[ValidateNotNullOrEmpty()]
[string] $Path = '.',
# If Path is not used, you can pass in a FileSystemInfo object through the pipeline.
[Parameter(ParameterSetName = 'Object', ValueFromPipeline = $true)]
[System.IO.FileSystemInfo[]] $FileSystemInfo,
# Will also list hidden files. Will be forwarded to Get-ChildItem.
[Parameter(ParameterSetName = 'Path')]
[switch] $Force,
# Pause file listing if the results are longer than the window height.
[Parameter()]
[Alias('p')]
[switch] $Pause,
# Show file owner.
[Parameter()]
[Alias('owner')]
[switch] $ShowOwner,
[Parameter()]
[Alias('parent','directory','d')]
[switch] $ShowParentDirectory,
# Files that match this filter will be highlighted in red.
[Parameter()]
[Alias('m')]
[string] $Highlight = [string]::Empty,
# Show size on disk.
[Parameter()]
[Alias('s')]
[switch] $ShowSizeOnDisk
)
BEGIN {
# Colors
$directoryColor = 'Yellow'
$documentColor = 'Cyan'
$executableColor = 'Magenta'
$logColor = 'DarkCyan'
$hiddenColor = 'DarkGray'
$modeColor = 'Gray'
$compressedColor = 'Green'
$highlightColor = 'Red'
$defaultColor = 'White'
if (-not(Get-Module -Name 'PowerShellHumanizer' -ListAvailable -Verbose:$false)) {
Write-Warning 'This function depends on the module PowerShellHumanizer.'
Write-Warning 'Please run "Install-Module -Name PowerShellHumanizer -Scope CurrentUser" to install the missing module.'
break
}
else {
if (-not(Get-Module -Name 'PowerShellHumanizer')) {
try {
Write-Verbose 'Importing PowerShellHumanizer'
Import-Module -Name 'PowerShellHumanizer' -Force
}
catch {
Write-Warning $_.Exception.Message
break
}
}
}
# Since we need the window height for the pause function
# it will only work when in the console.
if (($host.Name -eq 'ConsoleHost') -and ($Pause)) {
$windowHeight = [console]::WindowHeight
$usableHeight = $windowHeight - 2
$lines = 0
}
}
PROCESS {
foreach ($FileSystemInfoItem in $FileSystemInfo) {
[array]$files += $FileSystemInfoItem
}
}
END {
if ($PSCmdlet.ParameterSetName -eq 'Path') {
[array]$files = Get-ChildItem -Path $Path -Force:$Force -ErrorAction SilentlyContinue
}
if ($ShowParentDirectory) {
Write-Host ''
Write-Host " Directory: $(($files.Where({-not $_.PSIsContainer})[0]).DirectoryName)"
Write-Host ''
}
else {
Write-Host ''
}
foreach ($file in $files) {
# Only supported for files and folders.
if (-not ($file.PSProvider.Name -eq 'FileSystem')) {
break
}
$fileOwner = [String]::Empty
$fileSizeValue = [string]::Empty
$fileSizeUnit = [string]::Empty
$fileSizeOnDiskValue = [string]::Empty
$fileSizeOnDiskUnit = [string]::Empty
# File
if (-not $file.PSIsContainer) {
$fileSize = [Humanizer.ByteSizeExtensions]::bytes($file.Length).ToString(0.00)
$fileSizeSplit = $fileSize.split(' ')
$fileSizeUnit = ($fileSizeSplit[-1][0]).ToString()
$fileSizeValue = $fileSizeSplit[0]
if (($ShowSizeOnDisk) -and (-not $file.PSIsContainer)) {
$fileSizeOnDisk = [Humanizer.ByteSizeExtensions]::bytes($file.SizeOnDisk).ToString(0.00)
$fileSizeOnDiskSplit = $fileSizeOnDisk.split(' ')
$fileSizeOnDiskUnit = ($fileSizeOnDiskSplit[-1][0]).ToString()
$fileSizeOnDiskValue = $fileSizeOnDiskSplit[0]
}
switch ($file.Extension) {
'.ps1' {$color = $executableColor}
'.exe' {$color = $executableColor}
'.cmd' {$color = $executableColor}
'.com' {$color = $executableColor}
'.bat' {$color = $executableColor}
'.vbs' {$color = $executableColor}
'.log' {$color = $logColor}
'.txt' {$color = $documentColor}
'.doc' {$color = $documentColor}
'.docx' {$color = $documentColor}
'.zip' {$color = $compressedColor}
'.7z' {$color = $compressedColor}
'.rar' {$color = $compressedColor}
'.tar' {$color = $compressedColor}
DEFAULT {$color = $defaultColor}
}
}
# Directory
else {
$color = $directoryColor
}
# If file is hidden, overwrite the color with the color for hidden files.
if ($file.Attributes.HasFlag([System.IO.FileAttributes]::Hidden)) {
$color = $hiddenColor
}
else {
try {
if ($ShowOwner) {
$fileOwner = ((Get-Acl -Path $file.FullName).Owner).Split('\')[-1]
}
}
catch {} # if this doesn't work, just silently ignore it.
}
$lastWriteTimeHumanized = $file.LastWriteTime.Humanize()
$lastWriteTimeHumanizedSplit = $lastWriteTimeHumanized.split(' ')
if ($lastWriteTimeHumanizedSplit.count -eq 3) {
$timeNumber = $lastWriteTimeHumanizedSplit[0]
$timeUnit = $lastWriteTimeHumanizedSplit[1]
if (($timeNumber -eq 'an') -or ($timeNumber -eq 'one') -or ($timeNumber -eq 'a')) {
$timeNumber = '1'
}
}
elseif ($lastWriteTimeHumanized -eq 'yesterday') {
$timeNumber = '1'
$timeUnit = 'day'
}
# Highligh
if ($Highlight) {
if ($file.Name -like $Highlight) {
$color = $highlightColor
}
}
# Write output
Write-Host "$($file.Mode)" -ForegroundColor $modeColor -NoNewline
if ($ShowOwner) {
Write-Host " $($fileOwner.PadRight(17,' ')) " -NoNewline
}
Write-Host " $($timeNumber.PadLeft(3, ' ')) $($timeUnit.PadRight(8, ' ')) $($fileSizeValue.PadLeft(5,' ')) $($fileSizeUnit.PadRight(3,' '))" -NoNewline -ForegroundColor $defaultColor
if ($ShowSizeOnDisk) {
Write-Host "$($fileSizeOnDiskValue.PadLeft(5, ' ')) $($fileSizeOnDiskUnit.PadRight(3,' '))" -NoNewline -ForegroundColor $modeColor
}
Write-Host "$($file.Name)" -ForegroundColor $color
if (($host.Name -eq 'ConsoleHost') -and ($Pause)) {
$lines++
if ($lines -eq $usableHeight) {
Write-Host ''
Write-Host 'Press any key to continue ...' -NoNewline
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ''
$lines = 0
}
}
}
Write-Host ''
}
}
New-Alias -Name 'c' -Value 'Invoke-ColorizedFileListing' -Force
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Update-FileInfoType.ps1
|
Update-FileInfoType.ps1
|
function Update-FileInfoType {
<#
Update FileInfo type to include SizeOnDisk
Author: Øyvind Kallstad
#>
$typeData = Get-TypeData System.IO.FileInfo
$scriptBlock = {
$blockSize = $this.PSDrive.BlockSize
$size = $this.Length
[math]::Ceiling($size/$blockSize) * $blockSize
}
$scriptProperty = New-Object System.Management.Automation.Runspaces.ScriptPropertyData 'SizeOnDisk', $scriptBlock
if (-not($typeData.Members['SizeOnDisk'])) {
$typeData.Members.Add('SizeOnDisk', $scriptProperty)
}
Update-TypeData $typeData -Force
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Get-SpecialFolder.ps1
|
Get-SpecialFolder.ps1
|
function Get-SpecialFolder {
param ([System.Environment+SpecialFolder] $Name)
if (-not $Name) {
[Enum]::GetValues([System.Environment+SpecialFolder])
}
else {
Write-Output (,([PSCustomObject] @{
Name = $Name.ToString()
Path = [System.Environment]::GetFolderPath($Name)
}))
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Update-PSDriveInfoType.ps1
|
Update-PSDriveInfoType.ps1
|
function Update-PSDriveInfoType {
<#
Update PSDriveInfo type to include BlockSize
Author: Øyvind Kallstad
#>
$typeData = Get-TypeData System.Management.Automation.PSDriveInfo
$scriptBlock = {
if ($this.Provider.ImplementingType -eq [Microsoft.PowerShell.Commands.FileSystemProvider]) {
$driveRoot = ([System.IO.DirectoryInfo] $this.Root).Name.Replace('\','\\')
(Get-WmiObject -Query "SELECT BlockSize FROM Win32_Volume WHERE Name='$driveRoot'").BlockSize
}
}
$scriptProperty = New-Object System.Management.Automation.Runspaces.ScriptPropertyData 'BlockSize', $scriptBlock
if (-not($typeData.Members['BlockSize'])) {
$typeData.Members.Add('BlockSize', $scriptProperty)
}
Update-TypeData $typeData -Force
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Resolve-PathEx.ps1
|
Resolve-PathEx.ps1
|
function Resolve-PathEx {
<#
.SYNOPSIS
Resolve-Path extended to also work with files that don't exist.
.DESCRIPTION
You can use Resolve-PathEx when you want to handle both filenames and paths in a single parameter in your functions.
The function returns an object, and includes the resolved path as well as a boolean indicating whether the file
exists or not. Wildcards are supported for both path and filename.
.EXAMPLE
Resolve-Path *.ps1
Will resolve full path of all files in the current directory with the ps1 file extension.
.EXAMPLE
Resolve-PathEx c:\program*\windows*\w*.exe
Will resolve full path of all exe files beginning with w in any folders of the root of C: that starts with 'progra',
and all subfolders of these that start with 'windows'.
.EXAMPLE
Resolve-Path
Will resolve the current path.
.EXAMPLE
Resolve-Path nosuchfile.txt
Will resolve the full path of the file, even though it doesn't exist.
.LINK
https://gist.github.com/gravejester/a5c8407fcf5fb16a356a
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2014
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
[string[]] $Path = '.\'
)
PROCESS{
foreach ($thisPath in $Path) {
try {
# first try to resolve using the whole path
[array]$resolvedPath += (Resolve-Path -Path $thisPath -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path)
# if that didn't work, split to get the path only
if ([string]::IsNullOrEmpty($resolvedPath)) {
$pathOnly = Split-Path $thisPath
# if no path returned, add current directory as path
if ([string]::IsNullOrEmpty($pathOnly)) {
$pathOnly = '.\'
}
# try to resolve again using only the path
$pathOnlyResolve = (Resolve-Path -Path $pathOnly -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path)
# if successfull
if (-not([string]::IsNullOrEmpty($pathOnlyResolve))) {
# add the path and the filename back together
foreach ($p in $pathOnlyResolve) {
$pathAndFile = Join-Path -Path $p -ChildPath (Split-Path -Path $thisPath -Leaf)
$exists = Test-Path $pathAndFile
Write-Output (,([PSCustomObject] [Ordered] @{
Path = $pathAndFile
Exists = $exists
}))
}
}
# if we still are unable to resolve, the path most likely don't exist
else {
Write-Warning "Unable to resolve $pathOnly"
}
}
else {
foreach ($item in $resolvedPath) {
$exists = Test-Path $item
Write-Output (,([PSCustomObject] [Ordered] @{
Path = $item
Exists = $exists
}))
}
}
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/Communary.ConsoleExtensions/1.0.69/Functions/Resize-Console.ps1
|
Resize-Console.ps1
|
function Resize-Console {
<#
.SYNOPSIS
Resize the PowerShell console programmatically.
.DESCRIPTION
This function lets you resize the PowerShell console window by setting
custom width and height properties, as well as maximize and restore the
console window.
.EXAMPLE
Resize-Console 200 50
.EXAMPLE
Resize-Console -Maximize
.EXAMPLE
Resize-Console -Restore
.EXAMPLE
if (Get-WindowState -eq 'Normal') {Resize-Console -Maximize}
.NOTES
Author: Øyvind Kallstad
Date: 11.10.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
#>
[CmdletBinding(DefaultParameterSetName = 'CustomSize')]
param (
# Set the window width.
[Parameter(ParameterSetName = 'CustomSize', Position = 0)]
[ValidateRange(1,[int]::MaxValue)]
[int] $Width = $host.UI.RawUI.WindowSize.Width,
# Set the window height.
[Parameter(ParameterSetName = 'CustomSize', Position = 1)]
[ValidateRange(1,[int]::MaxValue)]
[int] $Height = $host.UI.RawUI.WindowSize.Height,
# Maximize the window.
[Parameter(ParameterSetName = 'Maximize')]
[switch] $Maximize,
# Restore the window (if maximized).
[Parameter(ParameterSetName = 'Restore')]
[switch] $Restore
)
if(($PSCmdlet.ParameterSetName -eq 'Maximize') -or ($PSCmdlet.ParameterSetName -eq 'Restore')) {
# get main window handle of the current process
$MainWindowHandle = (Get-Process -id $pid).MainWindowHandle
if ($Maximize) {
[Win32Functions.Win32ShowWindowAsync]::ShowWindowAsync($MainWindowHandle, 3) | Out-Null
}
if ($Restore) {
[Win32Functions.Win32ShowWindowAsync]::ShowWindowAsync($MainWindowHandle, 9) | Out-Null
}
}
else {
if ($host.Name -eq 'ConsoleHost') {
# buffer size can't be smaller than window size
if ($Width -gt $host.UI.RawUI.BufferSize.Width) {
$host.UI.RawUI.BufferSize = New-Object -TypeName System.Management.Automation.Host.Size -ArgumentList ($Width, $host.UI.RawUI.BufferSize.Height)
}
# if width is too large, set to max allowed size
if ($Width -gt $host.UI.RawUI.MaxPhysicalWindowSize.Width) {
$Width = $host.UI.RawUI.MaxPhysicalWindowSize.Width
}
# if height is too large, set to max allowed size
if ($Height -gt $host.UI.RawUI.MaxPhysicalWindowSize.Height) {
$Height = $host.UI.RawUI.MaxPhysicalWindowSize.Height
}
# set window size
$host.UI.RawUI.WindowSize = New-Object -TypeName System.Management.Automation.Host.Size -ArgumentList ($Width, $Height)
}
else {
Write-Warning 'Setting the console window size is only supported when running in the console host.'
}
}
}
function Get-ConsoleSize {
Write-Output ($host.UI.RawUI.WindowSize)
}
function Get-WindowState {
if ([Win32Functions.Win32IsZoomed]::IsZoomed(((Get-Process -id $pid).MainWindowHandle))) {
Write-Output 'Maximized'
}
else {
Write-Output 'Normal'
}
}
|
PowerShellCorpus/PowerShellGallery/cSCCM/1.4/Examples/SCCMConfiguration.ps1
|
SCCMConfiguration.ps1
|
Configuration SCCMConfiguration
{
param
(
[Parameter(Mandatory=$true)][ValidateNotNullorEmpty()][PsCredential]$SCCMAdministratorCredential
)
Import-DSCResource -ModuleName cSCCM
Node $AllNodes.NodeName
{
cCMFolder Device_All
{
FolderName = "_All"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder User_All
{
FolderName = "_All"
FolderType = "User Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSystems
{
FolderName = "Systems"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSystemsType
{
FolderName = "Systems - Type"
FolderType = "Device Collection"
ParentFolder = "Systems"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSystemsLocation
{
FolderName = "Systems - Location"
FolderType = "Device Collection"
ParentFolder = "Systems"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSystemsDepartment
{
FolderName = "Systems - Department"
FolderType = "Device Collection"
ParentFolder = "Systems"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceEndpointProtection
{
FolderName = "Endpoint Protection"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSoftwareUpdates
{
FolderName = "Software Updates"
FolderType = "Device Collection"
SCCMAdministratorCredential = $SCCMAdministratorCredential
ParentFolder = "Root"
Ensure = "Present"
}
cCMFolder DeviceServerUpdates
{
FolderName = "Software Updates - Servers"
FolderType = "Device Collection"
ParentFolder = "Software Updates"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceWorkstationUpdates
{
FolderName = "Software Updates - Workstations"
FolderType = "Device Collection"
ParentFolder = "Software Updates"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceSCCMUpdates
{
FolderName = "Software Updates - SCCM"
FolderType = "Device Collection"
ParentFolder = "Software Updates"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceOSD
{
FolderName = "Operating System Deployment"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DevicePowerProfile
{
FolderName = "Power Profile"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DeviceApplications
{
FolderName = "Applications"
FolderType = "Device Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder UserApplications
{
FolderName = "Applications"
FolderType = "User Collection"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverPWindows8_x64
{
FolderName = "Windows_8_x64"
FolderType = "Driver Package"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverPWindows7_x64
{
FolderName = "Windows_7_x64"
FolderType = "Driver Package"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverMicrosoft
{
FolderName = "Microsoft"
FolderType = "Driver"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverHyperV
{
FolderName = "Hyper-V"
FolderType = "Driver"
ParentFolder = "Microsoft"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverWindows8_x64
{
FolderName = "Windows_8_x64"
FolderType = "Driver"
ParentFolder = "Hyper-V"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder DriverWindows7_x64
{
FolderName = "Windows_7_x64"
FolderType = "Driver"
ParentFolder = "Hyper-V"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder ImagesDeployment
{
FolderName = "Deployment Ready Images"
FolderType = "Image Package"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder ImagesReference
{
FolderName = "Reference Images"
FolderType = "Image Package"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder SeqBuild
{
FolderName = "Build Sequences"
FolderType = "Task Sequence"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder SeqDeploy
{
FolderName = "Deployment Sequences"
FolderType = "Task Sequence"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMFolder SeqGeneral
{
FolderName = "General Task Sequences"
FolderType = "Task Sequence"
ParentFolder = "Root"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllWorkstations
{
CollectionName = "All Workstations"
LimitingCollectionName = "All Systems"
ParentFolder = "Root"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllWorkstationsQuery
{
RuleName = 'Windows Workstations'
ParentCollection = 'All Workstations'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Workstation%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllServers
{
CollectionName = "All Servers"
LimitingCollectionName = "All Systems"
ParentFolder = "Root"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllServersQuery
{
RuleName = 'Windows Servers'
ParentCollection = 'All Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Server%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllWin7
{
CollectionName = "Systems - Type - Windows 7 Workstations"
LimitingCollectionName = "All Workstations"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllWin7Query
{
RuleName = 'Windows 7 Clients'
ParentCollection = 'Systems - Type - Windows 7 Workstations'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Workstation 6.1%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllWin8
{
CollectionName = "Systems - Type - Windows 8 Workstations"
LimitingCollectionName = "All Workstations"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllWin8Query
{
RuleName = 'Windows 8 Clients'
ParentCollection = 'Systems - Type - Windows 8 Workstations'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Workstation 6.2%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllWin81
{
CollectionName = "Systems - Type - Windows 8.1 Workstations"
LimitingCollectionName = "All Workstations"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllWin81Query
{
RuleName = 'Windows 8.1 Clients'
ParentCollection = 'Systems - Type - Windows 8.1 Workstations'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Workstation 6.3%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllWinXP
{
CollectionName = "Systems - Type - Windows XP Workstations"
LimitingCollectionName = "All Workstations"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllWinXPQuery
{
RuleName = 'Windows XP Clients'
ParentCollection = 'Systems - Type - Windows XP Workstations'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Workstation 5.1%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAllSCCM
{
CollectionName = "Systems - Type - ConfigManager Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAllSCCMQuery
{
RuleName = 'Query SCCM Roles'
ParentCollection = 'Systems - Type - ConfigManager Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.SystemRoles IS NOT NULL'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAll2008
{
CollectionName = "Systems - Type - Windows 2008 Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAll2008Query
{
RuleName = '2008 Name Query'
ParentCollection = 'Systems - Type - Windows 2008 Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Server 6.0%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAll2008R2
{
CollectionName = "Systems - Type - Windows 2008 R2 Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAll2008R2Query
{
RuleName = '2008 R2 Name Query'
ParentCollection = 'Systems - Type - Windows 2008 R2 Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Server 6.1%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAll2012
{
CollectionName = "Systems - Type - Windows 2012 Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAll2012Query
{
RuleName = '2012 Name Query'
ParentCollection = 'Systems - Type - Windows 2012 Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Server 6.2%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceAll2012R2
{
CollectionName = "Systems - Type - Windows 2012 R2 Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceAll2012R2Query
{
RuleName = '2012 R2 Name Query'
ParentCollection = 'Systems - Type - Windows 2012 R2 Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from SMS_R_System where SMS_R_System.OperatingSystemNameandVersion LIKE "%Server 6.3%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceDCs
{
CollectionName = "Systems - Type - Domain Controllers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceDCsQuery
{
RuleName = 'DC Role Query'
ParentCollection = 'Systems - Type - Domain Controllers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_COMPUTER_SYSTEM on SMS_G_System_COMPUTER_SYSTEM.ResourceId = SMS_R_System.ResourceId where SMS_G_System_COMPUTER_SYSTEM.Roles like "%Domain_Controller%"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceDNSServers
{
CollectionName = "Systems - Type - DNS Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceDNSQuery
{
RuleName = 'DNS Role Query'
ParentCollection = 'Systems - Type - DNS Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select * from SMS_R_System inner join SMS_G_System_SERVICE on SMS_G_System_SERVICE.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SERVICE.DisplayName = "DNS Server" and SMS_G_System_SERVICE.StartMode = "Auto"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection DeviceDHCPServers
{
CollectionName = "Systems - Type - DHCP Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule DeviceDHCPQuery
{
RuleName = 'DHCP Role Query'
ParentCollection = 'Systems - Type - DHCP Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select * from SMS_R_System inner join SMS_G_System_SERVICE on SMS_G_System_SERVICE.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SERVICE.DisplayName = "DHCP Server" and SMS_G_System_SERVICE.StartMode = "Auto"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection HyperVServers
{
CollectionName = "Systems - Type - Hyper-V Servers"
LimitingCollectionName = "All Servers"
ParentFolder = "Systems - Type"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Both"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule HyperVServersQuery
{
RuleName = 'Hyper-V Role Query'
ParentCollection = 'Systems - Type - Hyper-V Servers'
ParentCollectionType = 'Device'
QueryType = 'Query'
QueryExpression = 'select * from SMS_R_System inner join SMS_G_System_SERVICE on SMS_G_System_SERVICE.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SERVICE.DisplayName = "Hyper-V Virtual Machine Management" and SMS_G_System_SERVICE.StartMode = "Auto"'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointDeploymentWS
{
CollectionName = "Endpoint Deployment"
LimitingCollectionName = "All Desktop and Server Clients"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointDeploymentWSQueryinc1
{
RuleName = 'Systems - Type - Windows 7 Workstations'
ParentCollection = 'Endpoint Deployment'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointDeploymentWSQueryinc2
{
RuleName = 'Systems - Type - Windows 8 Workstations'
ParentCollection = 'Endpoint Deployment'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointDeploymentWSQueryinc3
{
RuleName = 'Systems - Type - Windows 8.1 Workstations'
ParentCollection = 'Endpoint Deployment'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointDeploymentWSQueryinc4
{
RuleName = 'Systems - Type - Windows XP Workstations'
ParentCollection = 'Endpoint Deployment'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyDesktop
{
CollectionName = "Endpoint Policy - Standard Desktop"
LimitingCollectionName = "All Workstations"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDesktopQueryinc1
{
RuleName = 'Systems - Type - Windows 7 Workstations'
ParentCollection = 'Endpoint Policy - Standard Desktop'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDesktopQueryinc2
{
RuleName = 'Systems - Type - Windows 8 Workstations'
ParentCollection = 'Endpoint Policy - Standard Desktop'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDesktopQueryinc3
{
RuleName = 'Systems - Type - Windows 8.1 Workstations'
ParentCollection = 'Endpoint Policy - Standard Desktop'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDesktopQueryinc4
{
RuleName = 'Systems - Type - Windows XP Workstations'
ParentCollection = 'Endpoint Policy - Standard Desktop'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyServer
{
CollectionName = "Endpoint Policy - Standard Server"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyServerQueryinc1
{
RuleName = 'Systems - Type - Windows 2008 Servers'
ParentCollection = 'Endpoint Policy - Standard Server'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyServerQueryinc2
{
RuleName = 'Systems - Type - Windows 2008 R2 Servers'
ParentCollection = 'Endpoint Policy - Standard Server'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyServerQueryinc3
{
RuleName = 'Systems - Type - Windows 2012 Servers'
ParentCollection = 'Endpoint Policy - Standard Server'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyServerQueryinc4
{
RuleName = 'Systems - Type - Windows 2012 R2 Servers'
ParentCollection = 'Endpoint Policy - Standard Server'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyCM
{
CollectionName = "Endpoint Policy - ConfigManager"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyCMQueryinc1
{
RuleName = 'Systems - Type - ConfigManager Servers'
ParentCollection = 'Endpoint Policy - ConfigManager'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyDC
{
CollectionName = "Endpoint Policy - Domain Controller"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDCQueryinc1
{
RuleName = 'Systems - Type - Domain Controllers'
ParentCollection = 'Endpoint Policy - Domain Controller'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyDHCP
{
CollectionName = "Endpoint Policy - DHCP"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDHCPQueryinc1
{
RuleName = 'Systems - Type - DHCP Servers'
ParentCollection = 'Endpoint Policy - DHCP'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyDNS
{
CollectionName = "Endpoint Policy - DNS"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyDNSQueryinc1
{
RuleName = 'Systems - Type - DNS Servers'
ParentCollection = 'Endpoint Policy - DNS'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection EndpointPolicyDHyperV
{
CollectionName = "Endpoint Policy - Hyper-V"
LimitingCollectionName = "All Servers"
ParentFolder = "Endpoint Protection"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollectionRule EndpointPolicyHyperVQueryinc1
{
RuleName = 'Systems - Type - Hyper-V Servers'
ParentCollection = 'Endpoint Policy - Hyper-V'
ParentCollectionType = 'Device'
QueryType = 'Include'
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRSVRAssign
{
CollectionName = "Software Updates - Servers - ADR Assignment"
LimitingCollectionName = "All Servers"
ParentFolder = "Software Updates - Servers"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRSVRWeek1
{
CollectionName = "Software Updates - Servers - Week 1"
LimitingCollectionName = "Software Updates - Servers - ADR Assignment"
ParentFolder = "Software Updates - Servers"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRSVRWeek2
{
CollectionName = "Software Updates - Servers - Week 2"
LimitingCollectionName = "Software Updates - Servers - ADR Assignment"
ParentFolder = "Software Updates - Servers"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRSVRWeek3
{
CollectionName = "Software Updates - Servers - Week 3"
LimitingCollectionName = "Software Updates - Servers - ADR Assignment"
ParentFolder = "Software Updates - Servers"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRWKSAssign
{
CollectionName = "Software Updates - Workstations - ADR Assignment"
LimitingCollectionName = "All Workstations"
ParentFolder = "Software Updates - Workstations"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRWKSWeek1
{
CollectionName = "Software Updates - Workstations - Week 1"
LimitingCollectionName = "Software Updates - Workstations - ADR Assignment"
ParentFolder = "Software Updates - Workstations"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRWKSWeek2
{
CollectionName = "Software Updates - Workstations - Week 2"
LimitingCollectionName = "Software Updates - Workstations - ADR Assignment"
ParentFolder = "Software Updates - Workstations"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection SUPADRWKSWeek3
{
CollectionName = "Software Updates - Workstations - Week 3"
LimitingCollectionName = "Software Updates - Workstations - ADR Assignment"
ParentFolder = "Software Updates - Workstations"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection OSDAppStage
{
CollectionName = "OSD - Application Staging"
LimitingCollectionName = "All Systems"
ParentFolder = "Operating System Deployment"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection OSDBuildCapture
{
CollectionName = "OSD - Build and Capture"
LimitingCollectionName = "All Systems"
ParentFolder = "Operating System Deployment"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection OSDDeployment
{
CollectionName = "OSD - Master Deployment"
LimitingCollectionName = "All Systems"
ParentFolder = "Operating System Deployment"
CollectionType = "Device"
RefreshDays = "7"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection PPBalanced
{
CollectionName = "Power Profile - Balanced"
LimitingCollectionName = "All Workstations"
ParentFolder = "Power Profile"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection PPHighPerf
{
CollectionName = "Power Profile - High Performance"
LimitingCollectionName = "All Workstations"
ParentFolder = "Power Profile"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection PPPwrSaver
{
CollectionName = "Power Profile - Power Saver"
LimitingCollectionName = "All Workstations"
ParentFolder = "Power Profile"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
cCMCollection PPVServer
{
CollectionName = "Power Profile - Custom"
LimitingCollectionName = "All Workstations"
ParentFolder = "Power Profile"
CollectionType = "Device"
RefreshDays = "1"
RefreshType = "Periodic"
SCCMAdministratorCredential = $SCCMAdministratorCredential
Ensure = "Present"
}
}
Node $AllNodes.Where{$_.DSLPath -ne $NULL}.NodeName
{
File DSLApplications
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Application_Management\Applications'
Ensure = 'Present'
}
File DSLAppPackages
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Application_Management\Packages\Windows_8_SxS'
Ensure = 'Present'
}
File DSLOSDBoot
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Boot\MDT_x64'
Ensure = 'Present'
}
File DSLOSDDriverPackages
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Drivers\Packages'
Ensure = 'Present'
}
File DSLOSDDriverSource
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Drivers\Source'
Ensure = 'Present'
}
File DSLOSDImagesCapture
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Images\Capture'
Ensure = 'Present'
}
File DSLOSDImagesDeployment
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Images\Deployment'
Ensure = 'Present'
}
File DSLOSDImagesReference
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Images\Reference'
Ensure = 'Present'
}
File DSLOSDMDT2013CS
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\MDT2013_CustomSettings'
Ensure = 'Present'
}
File DSLOSDMDT2013EF
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\MDT2013_ExtraFiles'
Ensure = 'Present'
}
File DSLOSDMDT2013PS
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\MDT2013_PreStart'
Ensure = 'Present'
}
File DSLOSDMDT2013TK
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\MDT2013_ToolKit'
Ensure = 'Present'
}
File DSLOSDMDT2013WP
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\MDT2013_Wallpaper'
Ensure = 'Present'
}
File DSLOSDUSMT8
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Operating_Systems\Tools\USMT-ADK8'
Ensure = 'Present'
}
File DSLSUPPackagesSCEP
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Software_Updates\Packages\Endpoint_Protection_Updates'
Ensure = 'Present'
}
File DSLSUPPackages2013
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Software_Updates\Packages\Updates_2013'
Ensure = 'Present'
}
File DSLSUPPackages2014
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Software_Updates\Packages\Updates_2014'
Ensure = 'Present'
}
File DSLSUPSource
{
Type = 'Directory'
DestinationPath = $Node.DSLPath + '\Software_Updates\Source'
Ensure = 'Present'
}
}
}
$Nodes = @{
AllNodes = @(
@{
PSDscAllowPlainTextPassword=$true
NodeName = "SCCM01"
DSLPath = 'P:\DSL'
}
);
}
#Build Configuration
$SCCMAdminCred = Get-Credential
SCCMConfiguration -ConfigurationData $Nodes -SCCMAdministratorCredential $SCCMAdminCred
#Apply Configuration
Start-DscConfiguration .\SCCMConfiguration -wait -verbose
|
PowerShellCorpus/PowerShellGallery/LogInsight/1.0/Examples/Query-Events-TimeInterval.ps1
|
Query-Events-TimeInterval.ps1
|
Import-Module -Name LogInsight
$sConnect = @{
Server = 'LogInsight.local.lab'
User = 'admin'
Password = 'VMware1!'
}
Connect-LogInsight @sConnect
$start = (Get-Date).AddHours(-1)
$intervalMinutes = 10
$constraint = (Get-LogInsightConstraint -Field 'timestamp' -Operator GE -Value $start),
(Get-LogInsightConstraint -Field 'timestamp' -Operator LT -Value $start.AddMinutes($intervalMinutes))
$result = Get-LogInsightEvent -Event -Constraint $constraint
$result.events
|
PowerShellCorpus/PowerShellGallery/LogInsight/1.0/Examples/Query-Events-Timestamp.ps1
|
Query-Events-Timestamp.ps1
|
Import-Module -Name LogInsight
$sConnect = @{
Server = 'LogInsight.local.lab'
User = 'admin'
Password = 'VMware1!'
}
Connect-LogInsight @sConnect
$constraint = Get-LogInsightConstraint -Field 'timestamp' -Operator GE -Value (Get-Date).AddHours(-1)
$result = Get-LogInsightEvent -Constraint $constraint -Event
$result.events
|
PowerShellCorpus/PowerShellGallery/LogInsight/1.0/Examples/Query-Events-Hostname.ps1
|
Query-Events-Hostname.ps1
|
Import-Module -Name LogInsight
$sConnect = @{
Server = 'LogInsight.local.lab'
User = 'admin'
Password = 'VMware1!'
}
Connect-LogInsight @sConnect
$constraint = Get-LogInsightConstraint -Field 'hostname' -Operator STARTS_WITH -Value 'esx1'
$result = Get-LogInsightEvent -Constraint $constraint -Limit 100 -Event
$result.events
|
PowerShellCorpus/PowerShellGallery/LogInsight/1.0/Examples/Query-Bins.ps1
|
Query-Bins.ps1
|
Import-Module -Name LogInsight
$sConnect = @{
Server = 'LogInsight.local.lab'
User = 'admin'
Password = 'VMware1!'
}
Connect-LogInsight @sConnect
$constraint = Get-LogInsightConstraint -Field 'hostname' -Operator STARTS_WITH -Value 'esx1'
$result = Get-LogInsightEvent -Constraint $constraint -Limit 100 -Aggregate -Function SAMPLE -BinWidth 60000
$result.bins
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Src/Build.ps1
|
Build.ps1
|
param ( [switch]$clean )
if ( $clean )
{
remove-item SMLets.Module.dll -ea silentlycontinue
remove-item SMLets.Module.dll-Help.xml -ea silentlycontinue
remove-item SMLets.Module.pdb -ea silentlycontinue
exit
}
# this function creates the Get-SMLetsVersion cmdlet file
function New-SMLetsVersionFile
{
$rs = "";
$rs += " -replace '_SMCOREVERSION_','" + $COREDLLVERSION.FileVersion + "'"
$foundMatches = $null
$pstring = " -replace '_PRIVATE_','true'"
$cstring = " -replace '_CHANGES_',''"
if ( get-command -ea silentlycontinue svn )
{
$changedFiles = (svn stat) -match "^[AM]"
if ( $changedFiles )
{
$pstring = " -replace '_PRIVATE_','true'"
$cstring = " -replace '_CHANGES_','" + ($changedFiles -join '","') + "'"
}
else
{
$pstring = " -replace '_PRIVATE_','false'"
}
$l1 = "Working Copy Root Path: (?<_WORKINGCOPYROOTPATH_>.*)"
$l2 = "URL: (?<_URL_>.*)"
$l3 = "Repository Root: (?<_REPOSITORYROOT_>.*)"
$l4 = "Repository UUID: (?<_REPOSITORYUUID_>.*)"
$l5 = "Revision: (?<_REVISION_>.*)"
$l6 = "Node Kind: (?<j1_>.*)"
$l7 = "Schedule: (?<j2_>.*)"
$l8 = "Last Changed Author: (?<_LASTCHANGEDAUTHOR_>.*)"
$l9 = "Last Changed Rev: (?<_LASTCHANGEDREV_>.*)"
$la = "Last Changed Date: (?<_LASTCHANGEDDATE_>.*)"
$pattern = "$l1 $l2 $l3 $l4 $l5 $l6 $l7 $l8 $l9 $la"
if ( ([string](svn info) -match $pattern))
{
$foundMatches = $matches
}
}
if ( $foundMatches -eq $null )
{
$foundMatches = @{
_WORKINGCOPYROOTPATH_ = "$PWD"
_URL_ = "https://smlets.svn.codeplex.com/svn/Main/Source/SMLets/SMLets"
_REPOSITORYROOT_ = "https://smlets.svn.codeplex.com/svn"
_REPOSITORYUUID_ = "e17a0e51-4ae3-4d35-97c3-1a29b211df97"
_REVISION_ = "unknown"
_LASTCHANGEDAUTHOR_ = $env:username
_LASTCHANGEDREV_ = "unknown"
_LASTCHANGEDDATE_ = get-date
}
}
$foundMatches['_TARGETPRODUCT_'] = (get-itemproperty 'hklm:/software/microsoft/system center/2010/Service Manager/Setup' product).product
foreach($k in $foundMatches.keys)
{
if ( $k -match "^_" )
{
$rs += " -replace '$k','" + $foundMatches.$k + "'"
}
}
$rs += " $pstring"
$rs += " $cstring"
$rs += " -replace '\\','/'"
$sv = '${' + "$pwd\SMLETSVERSION.cs}"
$executionContext.InvokeCommand.NewScriptBlock("$sv $rs").Invoke()
}
# Find the compiler - pick the latest
$INSTALLDIR = Ā(gp 'hklm:/software/microsoft/system center\2010\Service Manager\Setup').InstallDirectory
$COREDLL = "${INSTALLDIR}\SDK Binaries\Microsoft.EnterpriseManagement.Core.dll"
$COREDLLVERSION = [system.diagnostics.fileversioninfo]::GetVersionInfo($COREDLL)
$SMDLL = "${INSTALLDIR}\SDK Binaries\Microsoft.EnterpriseManagement.ServiceManager.dll"
$PKGDLL = "${INSTALLDIR}\SDK Binaries\Microsoft.EnterpriseManagement.Packaging.dll"
$SMADLL = ([appdomain]::CurrentDomain.getassemblies()|?{$_.location -match "System.Management.Automation.dll"}).location
foreach ( $version in "v3.5","v3.0","v2.0.50727" )
{
$fmwk64 = "${env:windir}\Microsoft.Net\Framework64\$version"
$fmwk32 = "${env:windir}\Microsoft.Net\Framework\$version"
if ( test-path $fmwk64 )
{
set-alias csc "$fmwk64\csc.exe"
break
}
elseif ( test-path $fmwk32 )
{
set-alias csc "$fmwk32\csc.exe"
break
}
}
$files = "Identifiers.cs", "Incident.cs", "Helper.cs", "Session.cs", "EntityTypes.cs", "DataWarehouse.cs", "EntityObjects.cs", "Subscription.cs", "Announcement.cs", "ManagementPack.cs", "Security.cs", "Templates.cs", "Presentation.cs", "Monitoring.cs", "Categories.cs", "Resources.cs", "Offering.cs"
$CurrentVersionFile = "SMLETSCURRENTVERSION.CS"
New-SMLetsVersionFile > $CurrentVersionFile
$files += $CurrentVersionFile
$output = "SMLets.Module.dll"
$reference = "/r:$SMADLL","/r:$COREDLL","/r:$PKGDLL","/r:$SMDLL"
$R2Version = new-object System.Version 7.5.0.0
if ( $COREDLLVERSION.ProductVersion -ge $R2Version )
{
$CFLAGS = "/d:_SERVICEMANAGER_R2_"
}
else
{
$CFLAGS = ""
}
csc /target:library /debug $CFLAGS /out:$output $files $reference
# we've named the Module assembly something different
# so we'll copy that help to the appropriate name for the Module assembly
$SNAPINHELP = "SMLets.dll-Help.xml"
$MODULEHELP = "SMLets.Module.dll-Help.xml"
Copy-Item $SNAPINHELP $MODULEHELP
# remove the SMLETSCURRENTVERSION file
if ( test-path $CurrentVersionFile ) { remove-item $CurrentVersionFile }
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/Test-SortParameter.ps1
|
Test-SortParameter.ps1
|
$PT = "System.WorkItem.Incident.View.ProjectionType"
$props = "CreatedDate","ID","DisplayName",{$_.object.get_id()}
set-alias gsop get-SCSMObjectProjection
set-alias os out-string
$count = 10
### PROJECTION
"PROJECTION"
$r = gsop $PT -max $count
if ( $r.Count -eq $count ) { "PASS - Count" } else { "FAIL - Count" }
$r = gsop $PT -sort tIMEaDDED -max $count
if ( $r[0].TimeAdded -le $r[-1].TimeAdded ) { "PASS + tIMEaDDED" } else { "FAIL + tIMEaDDED" }
$r = gsop $PT -sort -TimeAdded -max $count
if ( $r[0].TimeAdded -ge $r[-1].TimeAdded ) { "PASS - TimeAdded" } else { "FAIL - TimeAdded" }
$r = gsop $PT -sort DisplayName -max $count
if ( $r[0].DisplayName -le $r[-1].DisplayName ) { "PASS + DisplayName" } else { "FAIL + DisplayName" }
$r = gsop $PT -sort -DisplayName -max $count
if ( $r[0].DisplayName -ge $r[-1].DisplayName ) { "PASS - DisplayName" } else { "FAIL - DisplayName" }
$r = gsop $PT -sort Id -max $count -filter "Id -like '*IR??'"
if ( $r[0].Id -le $r[-1].Id ) { "PASS + Id" } else { "FAIL + Id" }
$r = gsop $PT -sort "-Id" -max $count -filter "Id -like '*IR??'"
if ( $r[0].Id -ge $r[-1].Id ) { "PASS - Id" } else { "FAIL - Id" }
$r = gsop $PT -sort Priority
if ( $r[0].Priority -le $r[-1].Priority ) { "PASS + Priority" } else { "FAIL + Priority" }
$r = gsop $PT -sort -Priority
if ( $r[0].Priority -ge $r[-1].Priority ) { "PASS - Priority" } else { "FAIL - Priority" }
$PT = get-scsmclass -name "System.WorkItem.Incident$"
$props = "CreatedDate","ID","DisplayName",{$_.object.get_id()}
set-alias gso get-SCSMObject
### INSTANCE
"INSTANCE"
$r = gso $PT -max $count
if ( $r.Count -eq $count ) { "PASS - Count" } else { "FAIL - Count" }
$r = gso $PT -sort tIMEaDDED -max $count
if ( $r[0].TimeAdded -le $r[-1].TimeAdded ) { "PASS + tIMEaDDED" } else { "FAIL + tIMEaDDED" }
$r = gso $PT -sort -TimeAdded -max $count
if ( $r[0].TimeAdded -ge $r[-1].TimeAdded ) { "PASS - TimeAdded" } else { "FAIL - TimeAdded" }
$r = gso $PT -sort DisplayName -max $count
if ( $r[0].DisplayName -le $r[-1].DisplayName ) { "PASS + DisplayName" } else { "FAIL + DisplayName" }
$r = gso $PT -sort -DisplayName -max $count
if ( $r[0].DisplayName -ge $r[-1].DisplayName ) { "PASS - DisplayName" } else { "FAIL - DisplayName" }
$r = gso $PT -sort Id -max $count -filter "Name -like '*IR??'"
if ( $r[0].Id -le $r[-1].Id ) { "PASS + Name" } else { "FAIL + Name" }
$r = gso $PT -sort "-Id" -max $count -filter "Name -like '*IR??'"
if ( $r[0].Id -ge $r[-1].Id ) { "PASS - Name" } else { "FAIL - Name" }
$r = gso $PT -sort Priority
if ( $r[0].Priority -le $r[-1].Priority ) { "PASS + Priority" } else { "FAIL + Priority" }
$r = gso $PT -sort -Priority
if ( $r[0].Priority -ge $r[-1].Priority ) { "PASS - Priority" } else { "FAIL - Priority" }
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test-newproblem.ps1
|
test-newproblem.ps1
|
param ( $count = 10 , [switch]$whatif, [switch]$Verbose, [switch]$debug)
BEGIN
{
function Get-Priority
{
param ( [string]$myurgency, [string]$myimpact )
$hunt = "${myurgency}${myimpact}"
$PriorityData = (get-scsmobject -class (get-scsmclass -name System.WorkItem.Incident.GeneralSetting)).PriorityMatrix
if ( $PriorityData )
{
$matrix = [xml]$PriorityData
}
$Impact = Get-SCSMEnumeration System.WorkItem.TroubleTicket.ImpactEnum.|sort-object Ordinal
$Urgency = Get-SCSMEnumeration System.WorkItem.TroubleTicket.UrgencyEnum.|sort-object Ordinal
$hash = @{}
$count=1
foreach($U in $Urgency)
{
foreach($I in $Impact)
{
$UN = $U.DisplayName; $IN = $I.DisplayName
$UID = $U.ID; $IID = $I.ID
$xpath = "Matrix/U[@Id='$UID']/I[@Id='$IID']/P"
if ( $ProrityData )
{
$value = $Matrix.SelectSingleNode($xpath)."#text"
}
else
{
$Value = $count++
}
$hash["${UN}${IN}"] = $value
}
}
$hash[$hunt]
}
function new-FileAttachmentStream
{
param ( $count = 3 )
$OPEN = ([io.filemode]::Open)
$RACC = ([io.fileaccess]::Read)
$RSHR = ([io.fileshare]::read)
for($i = 0; $i -lt $count; $i++)
{
$DOCUMENT = [io.path]::GetTempFileName()
get-loremipsum 60 > $DOCUMENT
new-object io.filestream $DOCUMENT,$OPEN,$RACC,$RSHR
}
}
function get-loremipsum
{
param ( [int]$count = 11 )
#$s = $Start.ToString().ToLower()
#$URL = Ā"http://www.lipsum.com/feed/xml?amount=${count}&what=words&start=${s}"
#[xml]$x = ((new-object net.webclient).downloadstring($URL))
#$x.feed.lipsum
$words = "consetetur","sadipscing","elitr","sed","diam","nonumy","eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam","erat","sed","diam","voluptua","at","vero","eos","et","accusam","et",
"justo","duo","dolores","et","ea","rebum","stet","clita","kasd","gubergren","no","sea","takimata","sanctus", "est","lorem","ipsum","dolor","sit","amet","lorem","ipsum","dolor","sit","amet","consetetur","sadipscing",
"elitr","sed","diam","nonumy","eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam", "erat","sed","diam","voluptua","at","vero","eos","et","accusam","et","justo","duo","dolores","et","ea",
"rebum","stet","clita","kasd","gubergren","no","sea","takimata","sanctus","est","lorem","ipsum","dolor", "sit","amet","lorem","ipsum","dolor","sit","amet","consetetur","sadipscing","elitr","sed","diam","nonumy",
"eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam","erat","sed","diam","voluptua", "at","vero","eos","et","accusam","et","justo","duo","dolores","et","ea","rebum","stet","clita","kasd",
"gubergren","no","sea","takimata","sanctus","est","lorem","ipsum","dolor","sit","amet","duis","autem","vel", "eum","iriure","dolor","in","hendrerit","in","vulputate","velit","esse","molestie","consequat","vel","illum",
"dolore","eu","feugiat","nulla","facilisis","at","vero","eros","et","accumsan","et","iusto","odio", "dignissim","qui","blandit","praesent","luptatum","zzril","delenit","augue","duis","dolore","te","feugait",
"nulla","facilisi","lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","sed","diam", "nonummy","nibh","euismod","tincidunt","ut","laoreet","dolore","magna","aliquam","erat","volutpat","ut",
"wisi","enim","ad","minim","veniam","quis","nostrud","exerci","tation","ullamcorper","suscipit","lobortis", "nisl","ut","aliquip","ex","ea","commodo","consequat","duis","autem","vel","eum","iriure","dolor","in",
"hendrerit","in","vulputate","velit","esse","molestie","consequat","vel","illum","dolore","eu","feugiat", "nulla","facilisis","at","vero","eros","et","accumsan","et"
$RANDOM = new RANDOM
[byte[]]$b = new byte[] $count
$RANDOM.NextBytes($b)
($words[$b] -join " ").Trim() + "."
}
function Get-RandomItemFromList
{
param ( [Parameter(Mandatory=$true,Position=0)]$list )
$list[$RANDOM.Next(0,$list.Count)]
}
function Get-RandomListFromList
{
param (
[Parameter(Mandatory=$true,Position=0)]$list,
[Parameter(Mandatory=$true,Position=1)][int]$count
)
$mylist = [Collections.ArrayList]$list
$RandomList = @()
for($i = 0; $i -lt $count -and $mylist.Count -gt 0; $i++)
{
$r = $RANDOM.Next(0,$mylist.Count)
$RandomList += $mylist[$r]
$mylist.RemoveAt($r)
}
$RandomList
}
$RANDOM = new-object System.Random
$PTYPE = "System.WorkItem.Problem.ProjectionType"
###
### SETUP
### Retrieve stuff from the CMDB which will be used later
###
Write-Progress -Activity "Setting Up Environment" -Status "Getting Users"
$Users = Get-scsmobject -class (get-scsmclass -name Microsoft.AD.User$) -MaxCount 60
if ( $Users.Count -lt 20 ) {
Write-Error "Not enough users, go make some more"
exit
}
Write-Progress -Activity "Setting Up Environment" -Status "Getting Config Items"
$CIList = get-scsmobject -class (get-scsmclass -name System.ConfigItem$) -MaxCount 60
if ( $CIList.Count -lt 20 ) {
Write-Error "Not enough CIs, go make some more"
exit
}
Write-Progress -Activity "Setting Up Environment" -Status "Getting Enumerations"
# ENUMERATIONS
# the "." at the end of the enumeration is required to be sure we get the list
$StatusList = Get-SCSMEnumeration ProblemStatusEnum.
$SourceList = get-scsmenumeration ProblemSourceEnum.
$ResolutionList = Get-SCSMEnumeration ProblemResolutionEnum.
$ClassificationList = Get-SCSMEnumeration ProblemClassificationEnum.
$ImpactList = Get-SCSMEnumeration System.WorkItem.TroubleTicket.ImpactEnum.
$UrgencyList = Get-SCSMEnumeration System.WorkItem.TroubleTicket.UrgencyEnum.
Write-Progress -Activity "Setting Up Environment" -Status "Starting Problem Creation"
}
END
{
1..$count|%{
$i = $_
Write-Progress -Activity "Creating Problem" -Status $i -perc ([int]($i/$count * 100))
# This is the date
$CreatedDate = [datetime]::Now.AddDays(-$RANDOM.Next(30,90))
$ACIs = Get-RandomListFromList $CIList 5 # $CIList[$rlist]
$RCIs = Get-RandomListFromList $CIList 4 # $CIList[$rlist]
$Impact = Get-RandomItemFromList $ImpactList
$Urgency = Get-RandomItemFromList $UrgencyList
$Priority = Get-Priority $Urgency.DisplayName $Impact.DisplayName
$Status = Get-RandomItemFromList $StatusList
# DEBUG::: $Status = $StatusList | ?{$_.Name -match "Resolv"}
$Source = Get-RandomItemFromList $SourceList
$Classification = Get-RandomItemFromList $ClassificationList
$Resolution = Get-RandomItemFromList $ResolutionList
if ( $Urgency -match "high" ) { $TargetResolutionTime = $CreatedDate.AddHours(4) }
elseif ( $Urgency -match "medium" ) { $TargetResolutionTime = $CreatedDate.AddHours(24) }
elseif ( $Urgency -match "high" ) { $TargetResolutionTime = $CreatedDate.AddHours(72) }
else { $TargetResolutionTime = $CreatedDate.AddHours(48) }
$AffectedUser = Get-RandomItemFromList $users
$AssignedUser = Get-RandomItemFromList $users
$CreatedByUser = Get-RandomItemFromList $users
$ResolvedBy = Get-RandomItemFromList $users
$ClosedBy = Get-RandomItemFromList $users
# by default this creates 5
# $global:FASTREAMS = new-FileAttachmentStream
# CREATE THE SEED HASH TABLE
$ProblemSeed = @{
Id = "CustomProblem{0}"
Urgency = $Urgency
Impact = $Impact
Status = $Status
Source = $Source
Classification = $Classification
Resolution = $Resolution
Priority = $Priority
# ClosedDate
# ResolvedDate
Title = get-loremipsum 6
Description = get-loremipsum 22
CreatedDate = $CreatedDate
KnownError = [bool]($random.Next(0,2))
RequiresMajorProblemReview = [bool]($random.Next(0,2))
}
# FINISH THE SEED HASH TABLE
# set up for closed and resolved status
if ( $status -match "Closed" -or $status -match "Resolved" )
{
$ProblemSeed['ResolutionDescription'] = get-lorem 22
$ProblemSeed['ResolutionCategory'] = Get-RandomItemFromList $ResolutionList
$ResolveDiff = ($TargetResolutionTime - $CreatedDate).TotalHours
$TimeVariance = $RANDOM.Next(-$ResolveDiff,$ResolveDiff)
$ResolvedDate = $TargetResolutionTime.AddHours($TimeVariance)
$ProblemSeed['ResolvedDate'] = $ResolvedDate
if ( $status -match "Closed" )
{
$ProblemSeed['ClosedDate'] = $ResolvedDate.AddHours($RANDOM.Next(0,2)*24)
}
}
$p = @{
__CLASS = "System.WorkItem.Problem"
__OBJECT = $ProblemSeed
# Now for the Aliases
AssignedTo = $AssignedUser
CreatedBy = $CreatedByUser
AffectedConfigItems = $ACIs
}
if ( $status -match "Resolved" ) { $p['ResolvedBy'] = $ResolvedBy }
if ( $status -match "Closed" ) { $p['ResolvedBy'] = $ResolvedBy; $p['ClosedBy'] = $ClosedBy }
$p } | new-SCSMOBjectProjection -Type $PType -bulk -verbose:$verbose -whatif:$whatif -debug:$debug
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test004.ps1
|
test004.ps1
|
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$STARTTIME = [datetime]::Now
$TESTFAILED = $FALSE
}
END
{
try
{
[array]$r = get-scsmtask
if ( $null -ne $r[0] )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}a" )
}
else
{
$TESTFAILED = $TRUE
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}a" )
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}a" )
$TESTFAILED = $TRUE
}
try
{
[array]$r = get-scsmtaskresult
if ( $null -ne $r[0] )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}b" )
}
else
{
$TESTFAILED = $TRUE
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}b" )
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}b" )
$TESTFAILED = $TRUE
}
if ( $TESTFAILED )
{
return 1
}
else
{
return 0
}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test-newprojectionobject.ps1
|
test-newprojectionobject.ps1
|
param ( $count = 10 , [switch]$whatif, [switch]$Verbose)
BEGIN
{
function new-FileAttachmentStream
{
param ( $count = 3 )
$OPEN = ([io.filemode]::Open)
$RACC = ([io.fileaccess]::Read)
$RSHR = ([io.fileshare]::read)
for($i = 0; $i -lt $count; $i++)
{
$DOCUMENT = [io.path]::GetTempFileName()
get-loremipsum 60 > $DOCUMENT
new-object io.filestream $DOCUMENT,$OPEN,$RACC,$RSHR
}
}
function get-loremipsum
{
param ( [int]$count = 11 )
#$s = $Start.ToString().ToLower()
#$URL = Ā"http://www.lipsum.com/feed/xml?amount=${count}&what=words&start=${s}"
#[xml]$x = ((new-object net.webclient).downloadstring($URL))
#$x.feed.lipsum
$words = "consetetur","sadipscing","elitr","sed","diam","nonumy","eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam","erat","sed","diam","voluptua","at","vero","eos","et","accusam","et",
"justo","duo","dolores","et","ea","rebum","stet","clita","kasd","gubergren","no","sea","takimata","sanctus", "est","lorem","ipsum","dolor","sit","amet","lorem","ipsum","dolor","sit","amet","consetetur","sadipscing",
"elitr","sed","diam","nonumy","eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam", "erat","sed","diam","voluptua","at","vero","eos","et","accusam","et","justo","duo","dolores","et","ea",
"rebum","stet","clita","kasd","gubergren","no","sea","takimata","sanctus","est","lorem","ipsum","dolor", "sit","amet","lorem","ipsum","dolor","sit","amet","consetetur","sadipscing","elitr","sed","diam","nonumy",
"eirmod","tempor","invidunt","ut","labore","et","dolore","magna","aliquyam","erat","sed","diam","voluptua", "at","vero","eos","et","accusam","et","justo","duo","dolores","et","ea","rebum","stet","clita","kasd",
"gubergren","no","sea","takimata","sanctus","est","lorem","ipsum","dolor","sit","amet","duis","autem","vel", "eum","iriure","dolor","in","hendrerit","in","vulputate","velit","esse","molestie","consequat","vel","illum",
"dolore","eu","feugiat","nulla","facilisis","at","vero","eros","et","accumsan","et","iusto","odio", "dignissim","qui","blandit","praesent","luptatum","zzril","delenit","augue","duis","dolore","te","feugait",
"nulla","facilisi","lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","sed","diam", "nonummy","nibh","euismod","tincidunt","ut","laoreet","dolore","magna","aliquam","erat","volutpat","ut",
"wisi","enim","ad","minim","veniam","quis","nostrud","exerci","tation","ullamcorper","suscipit","lobortis", "nisl","ut","aliquip","ex","ea","commodo","consequat","duis","autem","vel","eum","iriure","dolor","in",
"hendrerit","in","vulputate","velit","esse","molestie","consequat","vel","illum","dolore","eu","feugiat", "nulla","facilisis","at","vero","eros","et","accumsan","et"
$RANDOM = new RANDOM
[byte[]]$b = new byte[] $count
$RANDOM.NextBytes($b)
($words[$b] -join " ").Trim() + "."
}
function Get-RandomItemFromList
{
param ( [Parameter(Mandatory=$true,Position=0)]$list )
$list[$RANDOM.Next(0,$list.Count)]
}
function Get-RandomListFromList
{
param (
[Parameter(Mandatory=$true,Position=0)]$list,
[Parameter(Mandatory=$true,Position=1)][int]$count
)
$mylist = [Collections.ArrayList]$list
$RandomList = @()
for($i = 0; $i -lt $count -and $mylist.Count -gt 0; $i++)
{
$r = $RANDOM.Next(0,$mylist.Count)
$RandomList += $mylist[$r]
$mylist.RemoveAt($r)
}
$RandomList
}
$RANDOM = new-object System.Random
$PTYPE = "System.WorkItem.Incident.ProjectionType"
###
### SETUP
### Retrieve stuff from the CMDB which will be used later
###
Write-Progress -Activity "Setting Up Environment" -Status "Getting Users"
$Users = Get-scsmobject -class (get-scsmclass -name Microsoft.AD.User$) -MaxCount 60
if ( $Users.Count -lt 20 ) {
Write-Error "Not enough users, go make some more"
exit
}
Write-Progress -Activity "Setting Up Environment" -Status "Getting Config Items"
$CIList = get-scsmobject -class (get-scsmclass -name System.ConfigItem$) -MaxCount 60
if ( $CIList.Count -lt 20 ) {
Write-Error "Not enough CIs, go make some more"
exit
}
Write-Progress -Activity "Setting Up Environment" -Status "Getting Knowledge Articles"
$KAList = get-scsmobject -class (get-scsmclass -name System.Knowledge.Article) -MaxCount 60
if ( $KAList.Count -lt 20 ) {
Write-Error "Not enough CIs, go make some more"
exit
}
Write-Progress -Activity "Setting Up Environment" -Status "Getting Enumerations"
# ENUMERATIONS
# the "." at the end of the enumeration is required to be sure we get the list
$TierQueueList = Get-SCSMEnumeration IncidentTierQueuesEnum.
$StatusList = Get-SCSMEnumeration IncidentStatusEnum.
$SourceList = get-scsmenumeration IncidentSourceEnum.
$ResolutionList = Get-SCSMEnumeration IncidentResolutionCategoryEnum.
$ClassificationList = Get-SCSMEnumeration IncidentClassificationEnum.
# RELATIONSHIPS
$billableTimeUser = Get-SCSMRelationshipClass System.WorkItem.BillableTimeHasWorkingUser
$billableTimeWork = Get-SCSMRelationshipClass System.WorkItemHasBillableTime
# CLASSES
$billableTimeClass = get-scsmclass system.workitem.billabletime
Write-Progress -Activity "Setting Up Environment" -Status "Starting Incident Creation"
}
END
{
1..$count|%{
$i = $_
Write-Progress -Activity "Creating Incident" -Status $i -perc ([int]($i/$count * 100))
# This is the date
$CreatedDate = [datetime]::Now.AddDays(-$RANDOM.Next(30,90))
$ACIs = Get-RandomListFromList $CIList 5 # $CIList[$rlist]
$RCIs = Get-RandomListFromList $CIList 4 # $CIList[$rlist]
$RCIs = Get-RandomListFromList $KAList 4 # $CIList[$rlist]
$PriorityHash = @{ Low = 1; Medium = 2; High = 3 }
$ImpactList = "Low","Medium","High"
$Impact = Get-RandomItemFromList $ImpactList
# bloody random numbers - sleep for a bit here
start-sleep -m 5
$Urgency = Get-RandomItemFromList $ImpactList
$PriorityValue = $PriorityHash[$Urgency] * $PriorityHash[$Impact]
$Priority = $PriorityValue
$TierQueue = Get-RandomItemFromList $TierQueueList
$Status = Get-RandomItemFromList $StatusList
# DEBUG::: $Status = $StatusList | ?{$_.Name -match "Resolv"}
$Source = Get-RandomItemFromList $SourceList
$Classification = Get-RandomItemFromList $ClassificationList
$Escalated = $false
if ( $Resolution.Name -eq "IncidentResolutionCategoryEnum.FixedByHigherTierSupport") { $Escalated = $true }
if ( $Urgency -match "high" ) { $TargetResolutionTime = $CreatedDate.AddHours(4) }
elseif ( $Urgency -match "medium" ) { $TargetResolutionTime = $CreatedDate.AddHours(24) }
elseif ( $Urgency -match "high" ) { $TargetResolutionTime = $CreatedDate.AddHours(72) }
else { $TargetResolutionTime = $CreatedDate.AddHours(48) }
$PrimaryOwner = Get-RandomItemFromList $users # [$RANDOM.Next(0,$users.Count)]
$AffectedUser = Get-RandomItemFromList $users # [$RANDOM.Next(0,$users.Count)]
$AssignedUser = Get-RandomItemFromList $users # [$RANDOM.Next(0,$users.Count)]
$CreatedByUser = Get-RandomItemFromList $users # [$RANDOM.Next(0,$users.Count)]
# by default this creates 5
# $global:FASTREAMS = new-FileAttachmentStream
# CREATE THE SEED HASH TABLE
$IncidentSeed = @{
Status = $Status
Source = $Source
Impact = $Impact
Urgency = $Urgency
TierQueue = $TierQueue
CreatedDate = $CreatedDate
Classification = $Classification
Title = get-loremipsum 6
Description = get-loremipsum 22
Priority = $Priority
Escalated = $Escalated
TargetResolutionTime = $TargetResolutionTime
Id = "CustomIR{0}"
}
# FINISH THE SEED HASH TABLE
# set up for closed and resolved status
if ( $status -match "Closed" -or $status -match "Resolved" )
{
$IncidentSeed['ResolutionDescription'] = get-lorem 22
$IncidentSeed['ResolutionCategory'] = Get-RandomItemFromList $ResolutionList
$ResolveDiff = ($TargetResolutionTime - $CreatedDate).TotalHours
$TimeVariance = $RANDOM.Next(-$ResolveDiff,$ResolveDiff)
$ResolvedDate = $TargetResolutionTime.AddHours($TimeVariance)
$IncidentSeed['ResolvedDate'] = $ResolvedDate
if ( $status -match "Closed" )
{
$IncidentSeed['ClosedDate'] = $ResolvedDate.AddHours($RANDOM.Next(0,2)*24)
}
}
# NOW CREATE THE REST OF THE INCIDENT
# User Comments
$UserComments = @{
__CLASS = "System.WorkItem.TroubleTicket.UserCommentLog"
__OBJECT = @{
Id = [string][guid]::NewGuid()
Comment = get-loremipsum 20
EnteredDate = $CreatedDate.AddHours($RANDOM.Next(0,5))
EnteredBy = $CreatedByUser.DisplayName
}
}
# Create 3 analyst comments
$AnalystComments = 1..3 | %{
@{
__CLASS = "System.WorkItem.TroubleTicket.AnalystCommentLog"
__OBJECT = @{
Id = [string][guid]::NewGuid().ToString();
Comment = get-loremipsum 20
EnteredDate = $CreatedDate.AddHours($RANDOM.Next(2,6));
EnteredBy = $AssignedUser.DisplayName
}
}
}
$KnowledgeArticles = @{
__CLASS = "System.Knowledge.Article"
__OBJECT = @{
Status = "Published"
ArticleId = "CustomKA{0}"
Title = get-loremipsum 6
Abstract = get-loremipsum 4
CreatedBy = "Joe User"
CreatedDate = $CreatedDate
}
},$KAs
#### File Attachments must have a new instance for each attachement
#### even if it's the same file
# NO FILE ATTACHMENTS FOR NOW
# $FileAttachments = $FASTREAMS | %{
# $stream = $_
# @{
# __CLASS = "System.FileAttachment"
# ### New-FileAttachmentInstance needs clean up which is done in the finally
# ### block. It creates a script scope array of file streams
# ### which must be cleaned up
# __OBJECT = @{
# Description = Get-Loremipsum 12
# AddedDate = [datetime]::Now.AddDays(-180)
# Extension = ".tmp"
# Id = [guid]::NewGuid().ToString()
# Content = $stream
# Size = $stream.Length
# }
# }
# }
$p = @{
__CLASS = "System.WorkItem.Incident"
__OBJECT = $IncidentSeed
# Now for the Aliases
PrimaryOwner = $PrimaryOwner
AffectedUser = $AffectedUser
AssignedUser = $AssignedUser
CreatedByUser = $CreatedByUser
UserComments = $UserComments
AnalystComments = $AnalystComments
AffectedConfigItems = $ACIs
RelatedConfigItems = $RCIs
RelatedKnowledgeArticles = $KnowledgeArticles
# FileAttachments
}
$p } | new-SCSMOBjectProjection -Type $PType -bulk -verbose:$verbose -whatif:$whatif
# Create the Billable time - this doesn't use a projection, so create the relationships
# directly
# New-SCSMObjectProjection must use -passthru and then this is done in a foreach loop
#| %{
# $workitem = $_.object
# 1..3 | %{
# $id = [guid]::NewGuid().ToString()
# $bti = new-scsmobject -NoCommit $BillableTimeClass -PropertyHashtable @{
# DisplayName = $id
# Id = $id
# TimeInMinutes = $RANDOM.Next(30,55);
# LastUpdated = [datetime]::Now
# }
# @{
# Relationship = $billableTimeUser
# Source = $workitem
# Target = $bti
# }
# @{
# Relationship = $billableTimeWork
# Source = $bti
# Target = $AssignedUser
# }
# start-sleep -mil 10
# }
#} | new-scsmRelationshipObject
#$wi = $pp.object
#for($itr = 0; $itr -lt 3; $itr++)
#{
# $id = [guid]::newGuid().ToString()
# # this requires an uncommited instance
# # when the relationship is commited, so will the instance
# $bti = new-scsmobject -NoCommit $BillableTimeClass -PropertyHashtable @{
# DisplayName = $id
# Id = $id
# TimeInMinutes = $RANDOM.Next(30,55);
# LastUpdated = [datetime]::Now
# }
# New-SCSMRelationshipObject -Relationship $billableTimeUser -Source $wi -Target $bti
# New-SCSMRelationshipObject -Relationship $billableTimeWork -Source $bti -Target $AssignedUser
# this sleep is to be sure that the time spent changes
#}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test009.ps1
|
test009.ps1
|
# Test the filter parameter to get-scsmobject. It should handle
# property -eq
# property -gt
# property -lt
# property -ne
# property -like
# property -isnull
# property -isnotnull
# the same for GenericProperty
# property1 -eq value -and property2 -eq value2
# property1 -gt value -and property2 -gt value2
# property1 -lt value -and property2 -lt value2
# property1 -ne value -and property2 -ne value2
# property1 -like value -and property2 -like value2
# property1 -isnull -and property2 -isnull
# property1 -isnotnull -and property2 -isnotnull
# property1 -eq value -or property2 -eq value2
# property1 -gt value -or property2 -gt value2
# property1 -lt value -or property2 -lt value2
# property1 -ne value -or property2 -ne value2
# property1 -like value -or property2 -like value2
# property1 -isnull -or property2 -isnull
# property1 -isnotnull -or property2 -isnotnull
#
# we'll build the test to handle just a few of these
#
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$classname = "System.GlobalSetting.ProblemSettings"
$instance = get-scsmobject -class (Get-SCSMClass -name $classname) -max 1
$propertyNames = $instance|gm -MemberType noteproperty | %{$_.name}
$STARTTIME = [datetime]::Now
}
END
{
try
{
$pName = "MaxAttachments"
$v = $instance.$pName
$o = get-scsmobject -class (Get-SCSMClass -Name $classname) -filter "$pName = '$v'"
if ( $o.$pname -eq $v )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}a" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}a" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}a" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName = "MaxAttachments"
$v = $instance.$pName
$o = get-scsmobject -class (Get-SCSMClass -name $classname) -filter "$pName -eq '$v'"
if ( $o.$pname -eq $v )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}b" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}b" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}b" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName = "MaxAttachments"
$v = $instance.$pName
$nv = $v - 1
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName -gt '$nv'"
if ( $o.$pname -gt $nv )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}c" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}c" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}c" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName = "MaxAttachments"
$v = $instance.$pName
$nv = $v + 1
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName -lt '$nv'"
if ( $o.$pname -lt $nv )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}d" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}d" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}d" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName1 = "MaxAttachments"
$pName2 = "MaxAttachmentSize"
$v1 = $instance.$pName1
$v2 = $instance.$pName2
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName1 = '$v1' -and $pName2 = '$v2'"
if ( $o.$pname1 -eq $v1 -and $o.$pname2 -eq $v2)
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}e" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}e" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}e" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName1 = "MaxAttachments"
$pName2 = "MaxAttachmentSize"
$v1 = $instance.$pName1
$v2 = $instance.$pName2
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName1 = '$v1' -or $pName2 = '$v2'"
if ( $o.$pname1 -eq $v1 -and $o.$pname2 -eq $v2)
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}f" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}f" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}f" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName = "MaxAttachments"
$v = $instance.$pName
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName -isnotnull"
if ( $o.$pname )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}g" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}g" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}g" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$pName = "priorityminvalue"
$o = get-scsmobject -Class (Get-SCSMClass -Name $classname) -filter "$pName -isnull"
if ( ! $o.$pname )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}h" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}h" )
$o | out-string -str | %{ out-testlog (" DETAIL: " + $_ ) }
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}h" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test011.ps1
|
test011.ps1
|
BEGIN
{
# get the Out-TestLog function
. ./Common
# import common functions (get-lorem)
. ../DataGen/Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$name = "System.WorkItem.Incident"
$STARTTIME = [datetime]::Now
$CClass = get-scsmclass -name "microsoft.windows.computer$"
$includeList = @(get-scsmobject -class $CClass -MaxCount 3)
$excludeList = @(get-scsmobject -class (get-scsmclass -name system.printer) -max 2)
$GroupName = (Get-Lorem 3) -replace " "
$TESTFAILED = $FALSE
$SLEEPSECONDS = 60
$MSG = "Sleeping for $SLEEPSECONDS seconds for group calc execution"
if ( ! $includeList -or ! $excludeList )
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}001")
Out-TestLog (" DETAILS: IncludeList Count = " + $includeList.Count + " ExcludeList Count = " + $excludeList.Count)
1
exit
}
}
END
{
### TEST 011a
try
{
# Test with include and exclude where include and exclude are
# different classes but all objects within include and exclude
# are the same class
# This doesn't actually import the management pack, so no reason to remove it
# so only check the group configuration
$GroupArgs = @{
Include = $includeList
ManagementPackName = "TESTMP1"
Name = $GroupName
Description = "A description for you!"
Exclude = $excludeList
PassThru = $true
}
$MP = new-scgroup @GroupArgs
$INCLUDEXPATH = "ManagementPack/Monitoring/Discoveries/Discovery/DataSource/MembershipRules/MembershipRule/IncludeList/MonitoringObjectId"
$EXCLUDEXPATH = "ManagementPack/Monitoring/Discoveries/Discovery/DataSource/MembershipRules/MembershipRule/ExcludeList/MonitoringObjectId"
$groupIncludeMembers = ([xml]$MP.getxml()).SelectNodes($INCLUDEXPATH)|%{$_."#text"}|sort
$groupExcludeMembers = ([xml]$MP.getxml()).SelectNodes($EXCLUDEXPATH)|%{$_."#text"}|sort
# $groupIncludeMembers = $g.IncludeList |%{$_.id}|sort
# $groupExcludeMembers = $g.ExcludeList |%{$_.id}|sort
$includeListGuids = $includeList|%{$_.id}|sort
$excludeListGuids = $excludeList|%{$_.id}|sort
if ( (compare-object $groupIncludeMembers $includeListGuids) -or (Compare-Object $groupExcludeMembers $excludeListGuids))
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011a")
}
else
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}011a")
}
}
catch
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011a")
$error | %{ Out-TestLog (" DETAIL: " + $_) }
}
# no MP imported - test complete
### TEST 011b
try
{
## The simplest group test
$MANAGEMENTPACKNAME = "TESTMP2"
$error.clear()
# clear the include and exclude lists
# we'll pass the include list in the pipeline
$GroupArgs.Remove("Include")
$GroupArgs.Remove("Exclude")
$GroupArgs.ManagementPackName = $MANAGEMENTPACKNAME
$GroupArgs.Import = $true
$MP = $includeList | new-scgroup @GroupArgs
for($i = 0; $i -le $SLEEPSECONDS; $i+=5)
{
Write-Progress -Activity $msg -Status $i -perc ( 100 * ($i/$SLEEPSECONDS))
start-sleep 5
}
$Group = Get-SCGroup -DisplayName $GroupName
$includeListGuids = $includeList | %{ $_.id } | sort
$groupIncludeMembers = $Group.Members | %{ $_.id } | sort
if ( Compare-Object $includeListGuids $groupIncludeMembers )
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011b")
}
else
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}011b")
}
}
catch
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011b" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
}
finally
{
Get-SCManagementPack -Name $MANAGEMENTPACKNAME | Remove-SCManagementPack
}
#
# Test 3 include are multiple classes
try
{
$MANAGEMENTPACKNAME = "TESTMP3"
$GroupArgs.Include = @( $includelist; $excludeList )
$GroupArgs.Import = $true
$GroupArgs.ManagementPackName = $MANAGEMENTPACKNAME
$MP = new-scgroup @GroupArgs
for($i = 0; $i -lt $SLEEPSECONDS; $i+=5)
{
Write-Progress -Activity $msg -Status $i -perc ( 100 * ($i/$SLEEPSECONDS))
start-sleep 5
}
start-sleep $SLEEPSECONDS
$Group = Get-SCGroup -DisplayName $GroupName
$ListGuids = @( $includeList; $excludeList) | %{ $_.id } | sort
$groupIncludeMembers = $Group.Members | %{ $_.id } | sort
if ( (compare-object $groupIncludeMembers $ListGuids))
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011c")
$groupIncludeMembers | %{ Out-TestLog (" Details: includemember - $_" ) }
$ListGuids | %{ Out-TestLog (" Details: ListGuid - $_" ) }
}
else
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}011c")
}
}
catch
{
$TESTFAILED = $true
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}011c")
$error | %{ Out-TestLog (" DETAIL: " + $_) }
}
finally
{
# ok - this MP was imported, so remove it
Get-SCManagementPack -Name $MANAGEMENTPACKNAME | Remove-SCManagementPack
}
if ( $TESTFAILED ) { return 1 } else { return 0 }
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/Invoke-Test.ps1
|
Invoke-Test.ps1
|
#requires -version 2.0
[CmdletBinding(SupportsShouldProcess=$true)]
param (
[string[]]$tests
)
BEGIN
{
# dot source the common stuff
. ./common.ps1
$ShowResults = $false
# these can be functions, or scripts
if ( $tests )
{
[string[]]$testprograms = $tests
}
else
{
[string[]]$testprograms = get-childitem test[0-9][0-9][0-9].ps1 -name
}
$TestResults = @()
if ( test-path $LOGFILE ) { remove-item $LOGFILE }
foreach ( $program in $testprograms )
{
if ( $PSCmdlet.ShouldProcess($program))
{
$ShowResults = $true
if ( & ./$program ) { $result = "FAIL" } else { $result = "PASS" }
$testresults += new-object psobject -prop @{
Name = $program
Result = $result
}
}
}
}
END
{
if ( $ShowResults )
{
$TestResults
}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/get-IncidentPriority.ps1
|
get-IncidentPriority.ps1
|
$PriorityData = (get-scsmobject System.WorkItem.Incident.GeneralSetting).PriorityMatrix
if ( $PriorityData )
{
$matrix = [xml]$PriorityData
}
$Impact = Get-SCSMEnumeration System.WorkItem.TroubleTicket.ImpactEnum. | sort Ordinal
$Urgency = Get-SCSMEnumeration System.WorkItem.TroubleTicket.UrgencyEnum. | sort Ordinal
$count=1
foreach($U in $Urgency)
{
$UOrdinal = $U.Ordinal
foreach($I in $Impact)
{
$IOrdinal = $I.Ordinal
$UN = $U.DisplayName; $IN = $I.DisplayName
$UID = $U.ID; $IID = $I.ID
$xpath = "Matrix/U[@Id='$UID']/I[@Id='$IID']/P"
if ( $ProrityData )
{
$value = $Matrix.SelectSingleNode($xpath)."#text"
}
else
{
$Value = $count++
}
new-object psobject |
add-member -pass NoteProperty UrgencyImpact "${UN}${IN}" |
add-member -pass NoteProperty Value $value |
add-member -pass NoteProperty Ordinal ($UOrdinal * $IOrdinal)
}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test010.ps1
|
test010.ps1
|
BEGIN
{
# set-psdebug -trace 2
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$name = "System.WorkItem.Incident"
$STARTTIME = [datetime]::Now
$IncidentTitle = "Test010 - $STARTTIME"
$Urgency = "Medium"
$Impact = "High"
$Status = "Active"
$Classification = "Software"
$Source = "System"
$CreatedAfter = $STARTTIME.AddHours(-1)
$CreatedBefore = $STARTTIME.AddHours(1)
$TESTFAILED = $false
}
END
{
try
{
# SETUP
$error.clear()
$incidentClass = get-scsmclass ^System.WorkItem.Incident$
$seed = new-scsmobject -pass $incidentClass @{
Id = "IR{0}";
Title = $IncidentTitle;
Urgency = $Urgency
Impact = $Impact
Status = $Status
Classification = $Classification
Source = $Source
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
# no reason to continue if this fails
return 1
}
finally
{
set-psdebug -trace 0
}
# TEST a - by ID
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -id $Id )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010a" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010a" )
out-testlog (" DETAIL: No Incident found (ID) - $ID" )
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010a" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST b - by Title
try
{
$error.clear()
$Title = $seed.Title
if ( get-scsmincident -title $Title )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010b" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010b" )
out-testlog (" DETAIL: No Incident found (Title) - $Title" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010b" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST c - by Id and Urgency
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -Urgency $Urgency )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010c" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010c" )
out-testlog (" DETAIL: No Incident found (Urgency) - $Urgency" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010c" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST d - by Id and Status
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -Status $Status )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010d" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010d" )
out-testlog (" DETAIL: No Incident found (Status) - $Status" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010d" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
# TEST e - by Id and Impact
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -Impact $Impact )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010e" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010e" )
out-testlog (" DETAIL: No Incident found (Impact) - $Impact" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010e" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST f - by Id and Classification
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -Classification $Classification )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010f" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010f" )
out-testlog (" DETAIL: No Incident found (Classification) - $Classification" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010f" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST g - by Id and Source
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -Source $Source )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010g" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010g" )
out-testlog (" DETAIL: No Incident found (Source) - $Source" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010g" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST h - by Id and CreatedAfter
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -CreatedAfter $CreatedAfter )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010h" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010h" )
out-testlog (" DETAIL: No Incident found (CreatedAfter) - $CreatedAfter" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010h" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
# TEST i - by Id and CreatedBefore
try
{
$error.clear()
$ID = $seed.ID
if ( get-scsmincident -ID $ID -CreatedBefore $CreatedBefore )
{
Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}010i" )
}
else
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010i" )
out-testlog (" DETAIL: No Incident found (CreatedBefore) - $CreatedBefore" )
$TESTFAILED = $true
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}010i" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
$TESTFAILED = $true
}
finally
{
set-psdebug -trace 0
}
if ( $TESTFAILED )
{
return 1
}
else
{
return 0
}
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/Test-soro.ps1
|
Test-soro.ps1
|
. ..\DataGen\Common.ps1
if ( ! (get-scsmmanagementpack -name SOTESTMP ))
{
New-SCSMManagementPack -name SOTESTMP
}
$mp = Get-SCSMManagementPack SOTESTMP
$user = get-scsmuser | select -first 1
$now = get-date
$title = get-lorem 6
$soArgs = @{
Title = $title
CostInformation = "Cost Information $now"
CostInformationLink = "http://www.microsoft.com"
BriefDescription = "Brief Description $now"
Overview = "Overview $now"
ManagementPack = $mp
DisplayName = $title
Notes = "Notes $now"
SLAInformation = "SLAInfo $now"
SLAInformationLink = "http://www.bing.com/"
comment = "COMMENT: $title"
owner = $user
PublishedBy = $user
PublishDate = $now
Category = "General"
Status = "Published"
}
New-SCSMServiceOffering @soArgs
$mySO = Get-SCSMServiceOffering -DisplayName $title
#### Now create a Request Offering
$enum = get-scsmenumeration ServiceRequestAreaEnum$
$qu = @()
$qu += @{ Prompt = "one"; TargetPath = "Title"; Type = "string"}
$qu += @{ Prompt = "two"; TargetPath = "Notes"; Type = "string"}
$qu += @{ Prompt = "thr"; TargetPath = "UserInput"; Type = "InlineList"; ListElements = "one","two","three" }
$qu += @{ Prompt = "fou"; TargetPath = "RequiredBy"; Type = "DateTime"}
$qu += @{ Prompt = "fiv"; TargetPath = "Area"; Type = "List" ; EnumerationList = $enum }
$qu += @{ Prompt = "six"; TargetPath = "ActualWork"; Type = "double" }
$qu += @{ Prompt = "sev"; TargetPath = "IsDowntime"; Type = "boolean" }
$qlist = @()
foreach ( $q in $qu )
{
$qlist += new-scsmrequestofferingquestion @q
}
$user = get-scsmuser |select -first 1
$mp = get-scsmmanagementpack SOTESTMP
$rotitle = get-lorem 4
$roargs = @{
BriefDescription = get-lorem 6
Comment = get-lorem 6
DisplayName = $roTitle
EstimatedTimeToCompletion = 5
ManagementPack = $mp
Notes = get-lorem 12
Overview = get-lorem 12
Owner = $user
PublishDate = get-date
PublishedBy = $user
Questions = $qlist
Status = "System.Offering.StatusEnum.Published"
Title = $rotitle
}
new-scsmrequestoffering @roArgs
$myRo = get-scsmclass requestoffering | get-scsmobject -filter "DisplayName -eq '$roTitle'"
add-SCSMRequestOffering $myRo $mySO.__base
"SO: $title"
"RO: $rotitle"
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test008.ps1
|
test008.ps1
|
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$MPNAME = "EnumTestMP"
$MPFILENAME = "${MPNAME}.xml"
$TESTNAME = $MyInvocation.MyCommand
$name = "System.WorkItem.Incident"
$STARTTIME = [datetime]::Now
# CREATE THE MP HERE
function New-EnumMP
{
@"
<?xml version="1.0" encoding="utf-8"?><ManagementPack ContentReadable="true" SchemaVersion="{0}" OriginalSchemaVersion="1.1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<Manifest>
<Identity>
<ID>${MPNAME}</ID>
<Version>1.0.0.0</Version>
</Identity>
<Name>Enumeration Test MP</Name>
<References>
"@ -f $SCHEMAVERSION
$MPList = "Microsoft.SystemCenter.InstanceGroup.Library",
"System.WorkItem.Library",
"Microsoft.SystemCenter.Library",
"Microsoft.Windows.Library",
"System.Library",
"System.WorkItem.Activity.Library",
"System.Notifications.Library"
foreach ( $mp in $MPList )
{
$mpi = get-scsmmanagementpack "^${mp}$"
" <Reference Alias=""{0}"">" -f $mp.Replace(".","_")
" <ID>$mp</ID>"
" <Version>{0}</Version>" -f $mpi.Version
" <PublicKeyToken>{0}</PublicKeyToken>" -f $mpi.KeyToken
" </Reference>"
}
@"
</References>
</Manifest>
<TypeDefinitions>
<EntityTypes>
<EnumerationTypes>
<EnumerationValue ID="System.WorkItem.TroubleTicket.UrgencyEnum.MediumHigh" Accessibility="Public" Parent="System_WorkItem_Library!System.WorkItem.TroubleTicket.UrgencyEnum" Ordinal="8" />
</EnumerationTypes>
</EntityTypes>
</TypeDefinitions>
</ManagementPack>
"@
}
}
END
{
$SYSMP = get-scsmmanagementPack System.Library
$SCHEMAVERSION = "{0}.{1}" -f $SYSMP.SchemaVersion.Major,$SYSMP.SchemaVersion.Minor
new-EnumMP |set-content -encoding ascii ${MPFILENAME}
try
{
# set-psdebug -trace 2
$error.clear()
import-scsmmanagementpack ${MPFILENAME}
$incidentClass = get-scsmclass ^System.WorkItem.Incident$
$r = new-scsmobject -pass $incidentClass @{ Id = "IR{0}"; Title = "foobar"; Urgency = "MediumHigh"; Impact = "High"}
$id = $r.id
$mpToRemove = get-scsmmanagementpack ${MPNAME}
$mpToRemove | remove-scsmmanagementpack
remove-item ${MPFILENAME}
start-sleep 5
$incident = get-scsmincident -id $id
$g = new-object guid $incident.Urgency
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
finally
{
set-psdebug -trace 0
}
Out-TestLog ("PASS: " + [datetime]::Now + ":$TESTNAME")
return 0
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test006.ps1
|
test006.ps1
|
# this test ensures that the cmdlets that should be here are here
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$name = "Microsoft.windows.computer"
$STARTTIME = [datetime]::Now
}
END
{
try
{
$o = get-scsmclass $name$|get-scsmobject -ea stop -max 1
if ( $null -ne $o ) { Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}a" ) }
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}a" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
try
{
$o = get-scsmtypeprojection $name|get-scsmobjectprojection -ea stop -max 1
if ( $null -ne $o ) { Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}b" ) }
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}b" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
return 0
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test007.ps1
|
test007.ps1
|
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$name = "Microsoft.windows.computer"
$STARTTIME = [datetime]::Now
}
END
{
try
{
$o = get-scsmannouncement
if ( $null -ne $o ) { Out-TestLog ("PASS: " + [datetime]::Now + ":${TESTNAME}" ) }
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":${TESTNAME}" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
return 1
}
return 0
}
|
PowerShellCorpus/PowerShellGallery/SMLets/0.5.0.1/Test/test005.ps1
|
test005.ps1
|
# this test ensures that the cmdlets that should be here are here
BEGIN
{
# the definition of Out-TestLog
. ./Common.ps1
$TESTNAME = $MyInvocation.MyCommand
$DOCUMENT = "${TESTDIR}\Document.RTF"
$class = Get-SCSMClass -Name "System.Knowledge.Article"
# get rid of the article we're creating
get-scsmobject -class $class -filter "DisplayName = 'TestArticle1'"|
remove-scsmobject -force
$STARTTIME = [datetime]::Now
}
END
{
try
{
$OPEN = ([io.filemode]::Open)
$RACC = ([io.fileaccess]::Read)
$RSHR = ([io.fileshare]::read)
$str = new-object io.filestream ${DOCUMENT},$OPEN,$RACC,$RSHR
new-scsmobject -class $class -PropertyHashtable @{
ArticleID = "TestArticle1"
Title = "test art1"
Status = "Draft"
EndUserContent = $str
}
}
catch
{
Out-TestLog ("FAIL: " + [datetime]::Now + ":$TESTNAME" )
$error | %{ Out-TestLog (" DETAIL: " + $_ ) }
}
finally
{
$str.close()
$str.dispose()
}
if (get-scsmobject -class $class -filter "DisplayName = 'TestArticle1'")
{
# cleanup
Out-TestLog ("PASS: " + [datetime]::Now + ":$TESTNAME")
get-scsmobject -class $class -filter "DisplayName = 'TestArticle1'"| remove-scsmobject -force
return 0
}
else
{
return 1
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.