full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Exchange AutoReply Admin_1.ps1
|
Exchange AutoReply Admin_1.ps1
|
<#
.NOTES
Name : Exchange Automatic Replies Administrator.ps1
Author : Bryan Jaudon <bryan.jaudon@gmail.com>
Version : 1.0
Date : 11/23/2012
.SYNOPSIS
Provides a graphical front-end to the Get-MailboxAutoReplyConfiguration and
Set-MailboxAutoReplyConfiguration Exchange cmdlets. Requires Exchange management
tools be installed on the same system as the script.
#>
#requires -version 2
$Script:ScriptTitle="Exchange Automatic Replies Administrator"
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()
#endregion
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 11/23/2012 2:32 PM
# Generated By: bjaudon
########################################################################
#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$labelConnectedFQDN = New-Object System.Windows.Forms.Label
$labelConnected = New-Object System.Windows.Forms.Label
$buttonOK = New-Object System.Windows.Forms.Button
$buttonCancel = New-Object System.Windows.Forms.Button
$labelAutoreply = New-Object System.Windows.Forms.Label
$tabControl1 = New-Object System.Windows.Forms.TabControl
$tabPage1 = New-Object System.Windows.Forms.TabPage
$textInside = New-Object System.Windows.Forms.TextBox
$tabPage2 = New-Object System.Windows.Forms.TabPage
$radioAll = New-Object System.Windows.Forms.RadioButton
$radioKnown = New-Object System.Windows.Forms.RadioButton
$checkReplyOutside = New-Object System.Windows.Forms.CheckBox
$textOutside = New-Object System.Windows.Forms.TextBox
$dateEndTime = New-Object System.Windows.Forms.DateTimePicker
$dateEndDate = New-Object System.Windows.Forms.DateTimePicker
$labelEndTime = New-Object System.Windows.Forms.Label
$dateStartTime = New-Object System.Windows.Forms.DateTimePicker
$dateStartDate = New-Object System.Windows.Forms.DateTimePicker
$labelStartTime = New-Object System.Windows.Forms.Label
$checkOnlySend = New-Object System.Windows.Forms.CheckBox
$radioSend = New-Object System.Windows.Forms.RadioButton
$radioDoNotSend = New-Object System.Windows.Forms.RadioButton
$comboIdentity = New-Object System.Windows.Forms.ComboBox
$labelIdentity = New-Object System.Windows.Forms.Label
$labelTitle = New-Object System.Windows.Forms.Label
$pbIcon = New-Object System.Windows.Forms.PictureBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$dateEndDate_ValueChanged=
{
$buttonOK.Enabled=$true
}
$dateStartTime_ValueChanged=
{
$buttonOK.Enabled=$true
}
$textOutside_TextChanged=
{
$buttonOK.Enabled=$true
}
$textInside_TextChanged=
{
$buttonOK.Enabled=$true
}
$dateStartDate_ValueChanged=
{
$buttonOK.Enabled=$true
}
$dateEndTime_ValueChanged=
{
$buttonOK.Enabled=$true
}
$handler_radioAll_Click=
{
$buttonOK.Enabled=$true
}
$handler_radioKnown_Click=
{
$buttonOK.Enabled=$true
}
$handler_checkReplyOutside_Click=
{
if ($checkReplyOutside.checked) {
$radioKnown.Enabled=$true
$radioAll.Enabled=$true
$textOutside.Enabled=$true
$tabPage2.Text = "Outside My Organization (On)"
}
else {
$radioKnown.Enabled=$false
$radioAll.Enabled=$false
$textOutside.Enabled=$false
$tabPage2.Text = "Outside My Organization (Off)"
}
$buttonOK.Enabled=$true
}
$buttonOK_OnClick=
{
$commandHashTable=@{ "Identity"=$comboIdentity.SelectedItem }
if ($radioDoNotSend.Checked) { $commandHashTable.Add("AutoReplyState","Disabled") }
else {
if ($checkOnlySend.Checked) {
$commandHashTable.Add("AutoReplyState","Scheduled")
$commandHashTable.Add("StartTime",$(Get-Date -Month $dateStartDate.value.Month -Day $dateStartDate.Value.Day -Year $dateStartDate.value.Year -Hour $dateStartTime.Value.Hour -Minute $dateStartTime.value.Minute -Second $dateStartTime.value.Second))
$commandHashTable.Add("EndTime",$(Get-Date -Month $dateEndDate.value.Month -Day $dateEndDate.Value.Day -Year $dateEndDate.value.Year -Hour $dateEndTime.Value.Hour -Minute $dateEndTime.value.Minute -Second $dateEndTime.value.Second))
if ($commandHashTable["EndTime"] -le $commandHashTable["StartTime"]) { ShowPrompt -Message "The end time cannot be less than or equal to start time." -icon Error -Buttons OK;return }
if ($commandHashTable["EndTime"] -le (Get-Date)) { ShowPrompt -Message "The end time that you entered occurs before the current time." -icon Error -Buttons OK;return }
}
else { $commandHashTable.Add("AutoReplyState","Enabled") }
$commandHashTable.Add("InternalMessage",$textInside.Text)
if ($checkReplyOutside.checked) {
$commandHashTable.Add("ExternalMessage",$textOutside.Text)
if ($radioAll.Checked) { $commandHashTable.Add("ExternalAudience","All") }
elseif ($radioKnown.Checked) { $commandHashTable.Add("ExternalAudience","Known") }
}
else { $commandHashTable.Add("ExternalAudience","None") }
}
try { $status=Get-MailboxAutoReplyConfiguration -Identity $comboIdentity.SelectedItem }
catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return }
$result=ShowPrompt -Message "You have chosen to change the Automatic Reply configuration for`n'$($comboIdentity.SelectedItem)' from the state of '$($status.AutoReplyState)' to the state of '$($commandhashtable["AutoReplyState"])'.`n`nDo you wish to commit this change?" -Buttons "YesNo" -icon Warning
if ($result -eq "Yes") {
try { Set-MailboxAutoReplyConfiguration @commandHashTable -ErrorAction STOP }
catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return }
try { $status=Get-MailboxAutoReplyConfiguration -Identity $comboIdentity.SelectedItem }
catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return }
if (($status.AutoReplyState -eq $commandHashTable["AutoReplyState"]) -and ($status.IsValid -eq $True)) {
ShowPrompt -Message "Automatic Reply configuration successful!" -Icon Information -Buttons OK;GetAutoReplyStatus -identity $comboIdentity.SelectedItem;$buttonOK.Enabled=$false;$form1.Refresh();return
}
else { ShowPrompt -Message "Automatic Reply configuration failed. `n`nCurrent Status is: $($status.AutoReplyState)" -Icon Error -Buttons OK;GetAutoReplyStatus -identity $comboIdentity.SelectedItem;$form1.Refresh();return }
}
else { ShowPrompt -Message "Automatic Reply configuration cancelled!" -Icon Error -Buttons OK;return }
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
$form1.Update()
try { $comboIdentity.items.AddRange($(Get-CASMailbox | sort -Property Identity | Select -ExpandProperty Identity)) }
catch { ShowPrompt -Message $_ -Buttons OK -Icon Error }
if ($comboIdentity.items.count -lt 1) { ShowPrompt -Message "There were no Mailboxes found in the Exchange Organization.`nExiting Application." -Buttons OK -Icon Error;$form1.Close() }
}
$comboIdentity_SelectionChangeCommitted=
{
GetAutoReplyStatus -identity $comboIdentity.SelectedItem
}
$handler_radioSend_Click=
{
$scheduledstate=$checkOnlySend.Checked
Status-EnabledAutoReply
$checkOnlySend.Checked=$scheduledstate
}
$handler_radioDoNotSend_Click=
{
$scheduledstate=$checkOnlySend.Checked
Status-DisabledAutoReply
$checkOnlySend.Checked=$scheduledstate
}
$handler_checkOnlySend_Click=
{
switch ($checkOnlySend.Checked) {
true { Status-ScheduledAutoReply }
false { Status-EnabledAutoReply }
}
}
#----------------------------------------------
#region ImageList for nodes
$imageList = new-Object System.Windows.Forms.ImageList
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 24
$System_Drawing_Size.Height = 24
$imageList.ImageSize = $System_Drawing_Size
$image1 = $Insideicon
$image2 = $Outsideicon
$imageList.Images.Add("Inside",$image1)
$imageList.Images.Add("Outside",$image2)
#endregion
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 557
$System_Drawing_Size.Width = 538
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.FormBorderStyle = 1
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
$form1.Name = "form1"
$form1.Text = "Exchange Automatic Replies Administrator"
$form1.Icon=$icon
$labelConnectedFQDN.AutoEllipsis = $True
$labelConnectedFQDN.DataBindings.DefaultDataSourceUpdateMode = 0
$labelConnectedFQDN.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,1)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 120
$System_Drawing_Point.Y = 522
$labelConnectedFQDN.Location = $System_Drawing_Point
$labelConnectedFQDN.Name = "labelConnectedFQDN"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 238
$labelConnectedFQDN.Size = $System_Drawing_Size
$labelConnectedFQDN.TabIndex = 18
$labelConnectedFQDN.Text = "$connectedFqdn"
$labelConnectedFQDN.TextAlign = 16
$form1.Controls.Add($labelConnectedFQDN)
$labelConnected.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 522
$labelConnected.Location = $System_Drawing_Point
$labelConnected.Name = "labelConnected"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 101
$labelConnected.Size = $System_Drawing_Size
$labelConnected.TabIndex = 17
$labelConnected.Text = "Connected Server:"
$labelConnected.TextAlign = 16
$form1.Controls.Add($labelConnected)
$buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonOK.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 371
$System_Drawing_Point.Y = 522
$buttonOK.Location = $System_Drawing_Point
$buttonOK.Name = "buttonOK"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$buttonOK.Size = $System_Drawing_Size
$buttonOK.TabIndex = 16
$buttonOK.Text = "OK"
$buttonOK.UseVisualStyleBackColor = $True
$buttonOK.add_Click($buttonOK_OnClick)
$form1.Controls.Add($buttonOK)
$buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonCancel.DialogResult = 2
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 452
$System_Drawing_Point.Y = 522
$buttonCancel.Location = $System_Drawing_Point
$buttonCancel.Name = "buttonCancel"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$buttonCancel.Size = $System_Drawing_Size
$buttonCancel.TabIndex = 15
$buttonCancel.Text = "Cancel"
$buttonCancel.UseVisualStyleBackColor = $True
$buttonCancel.add_Click($buttonCancel_OnClick)
$form1.Controls.Add($buttonCancel)
$labelAutoreply.DataBindings.DefaultDataSourceUpdateMode = 0
$labelAutoreply.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 234
$labelAutoreply.Location = $System_Drawing_Point
$labelAutoreply.Name = "labelAutoreply"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 514
$labelAutoreply.Size = $System_Drawing_Size
$labelAutoreply.TabIndex = 14
$labelAutoreply.Text = "Automatically reply once for each sender with the following messages:"
$labelAutoreply.TextAlign = 16
$form1.Controls.Add($labelAutoreply)
$tabControl1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 25
$System_Drawing_Size.Width = 119
$tabControl1.ItemSize = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 260
$tabControl1.Location = $System_Drawing_Point
$tabControl1.Name = "tabControl1"
$tabControl1.SelectedIndex = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 256
$System_Drawing_Size.Width = 514
$tabControl1.Size = $System_Drawing_Size
$tabControl1.TabIndex = 13
$tabControl1.ImageList=$imageList
$form1.Controls.Add($tabControl1)
$tabPage1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$tabPage1.Location = $System_Drawing_Point
$tabPage1.Name = "tabPage1"
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$tabPage1.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 230
$System_Drawing_Size.Width = 506
$tabPage1.Size = $System_Drawing_Size
$tabPage1.TabIndex = 0
$tabPage1.Text = "Inside My Organization"
$tabPage1.UseVisualStyleBackColor = $True
$tabPage1.ImageIndex=0
$tabControl1.Controls.Add($tabPage1)
$textInside.DataBindings.DefaultDataSourceUpdateMode = 0
$textInside.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 7
$textInside.Location = $System_Drawing_Point
$textInside.Multiline = $True
$textInside.Name = "textInside"
$textInside.ScrollBars = 3
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 210
$System_Drawing_Size.Width = 494
$textInside.Size = $System_Drawing_Size
$textInside.TabIndex = 0
$textInside.add_TextChanged($textInside_TextChanged)
$tabPage1.Controls.Add($textInside)
$tabPage2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$tabPage2.Location = $System_Drawing_Point
$tabPage2.Name = "tabPage2"
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$tabPage2.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 230
$System_Drawing_Size.Width = 506
$tabPage2.Size = $System_Drawing_Size
$tabPage2.TabIndex = 1
$tabPage2.Text = "Outside My Organization (Off)"
$tabPage2.UseVisualStyleBackColor = $True
$tabPage2.ImageIndex=1
$tabControl1.Controls.Add($tabPage2)
$radioAll.DataBindings.DefaultDataSourceUpdateMode = 0
$radioAll.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 141
$System_Drawing_Point.Y = 23
$radioAll.Location = $System_Drawing_Point
$radioAll.Name = "radioAll"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 190
$radioAll.Size = $System_Drawing_Size
$radioAll.TabIndex = 3
$radioAll.TabStop = $True
$radioAll.Text = "Anyone outside my organization"
$radioAll.UseVisualStyleBackColor = $True
$radioAll.Checked=$True
$radioAll.add_Click($handler_radioAll_Click)
$tabPage2.Controls.Add($radioAll)
$radioKnown.DataBindings.DefaultDataSourceUpdateMode = 0
$radioKnown.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 25
$System_Drawing_Point.Y = 23
$radioKnown.Location = $System_Drawing_Point
$radioKnown.Name = "radioKnown"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 110
$radioKnown.Size = $System_Drawing_Size
$radioKnown.TabIndex = 2
$radioKnown.TabStop = $True
$radioKnown.Text = "My Contacts only"
$radioKnown.UseVisualStyleBackColor = $True
$radioKnown.add_Click($handler_radioKnown_Click)
$tabPage2.Controls.Add($radioKnown)
$checkReplyOutside.DataBindings.DefaultDataSourceUpdateMode = 0
$checkReplyOutside.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 3
$checkReplyOutside.Location = $System_Drawing_Point
$checkReplyOutside.Name = "checkReplyOutside"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 253
$checkReplyOutside.Size = $System_Drawing_Size
$checkReplyOutside.TabIndex = 1
$checkReplyOutside.Text = "Auto-Reply to people outside my organization"
$checkReplyOutside.UseVisualStyleBackColor = $True
$checkReplyOutside.add_Click($handler_checkReplyOutside_Click)
$tabPage2.Controls.Add($checkReplyOutside)
$textOutside.DataBindings.DefaultDataSourceUpdateMode = 0
$textOutside.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 53
$textOutside.Location = $System_Drawing_Point
$textOutside.Multiline = $True
$textOutside.Name = "textOutside"
$textOutside.ScrollBars = 3
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 164
$System_Drawing_Size.Width = 494
$textOutside.Size = $System_Drawing_Size
$textOutside.TabIndex = 0
$textOutside.add_TextChanged($textOutside_TextChanged)
$tabPage2.Controls.Add($textOutside)
$dateEndTime.CustomFormat = "h:mm tt"
$dateEndTime.DataBindings.DefaultDataSourceUpdateMode = 0
$dateEndTime.Enabled = $False
$dateEndTime.Format = 8
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 282
$System_Drawing_Point.Y = 204
$dateEndTime.Location = $System_Drawing_Point
$dateEndTime.Name = "dateEndTime"
$dateEndTime.ShowUpDown = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 76
$dateEndTime.Size = $System_Drawing_Size
$dateEndTime.TabIndex = 12
$dateEndTime.add_ValueChanged($dateEndTime_ValueChanged)
$form1.Controls.Add($dateEndTime)
$dateEndDate.CustomFormat = "ddd MM/dd/yyyy"
$dateEndDate.DataBindings.DefaultDataSourceUpdateMode = 0
$dateEndDate.Enabled = $False
$dateEndDate.Format = 8
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 152
$System_Drawing_Point.Y = 204
$dateEndDate.Location = $System_Drawing_Point
$dateEndDate.Name = "dateEndDate"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 124
$dateEndDate.Size = $System_Drawing_Size
$dateEndDate.TabIndex = 11
$dateEndDate.add_ValueChanged($dateEndDate_ValueChanged)
$form1.Controls.Add($dateEndDate)
$labelEndTime.DataBindings.DefaultDataSourceUpdateMode = 0
$labelEndTime.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 82
$System_Drawing_Point.Y = 202
$labelEndTime.Location = $System_Drawing_Point
$labelEndTime.Name = "labelEndTime"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 64
$labelEndTime.Size = $System_Drawing_Size
$labelEndTime.TabIndex = 10
$labelEndTime.Text = "End time:"
$labelEndTime.TextAlign = 16
$form1.Controls.Add($labelEndTime)
$dateStartTime.CustomFormat = "h:mm tt"
$dateStartTime.DataBindings.DefaultDataSourceUpdateMode = 0
$dateStartTime.Enabled = $False
$dateStartTime.Format = 8
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 282
$System_Drawing_Point.Y = 178
$dateStartTime.Location = $System_Drawing_Point
$dateStartTime.Name = "dateStartTime"
$dateStartTime.ShowUpDown = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 77
$dateStartTime.Size = $System_Drawing_Size
$dateStartTime.TabIndex = 9
$dateStartTime.add_ValueChanged($dateStartTime_ValueChanged)
$form1.Controls.Add($dateStartTime)
$dateStartDate.CustomFormat = "ddd MM/dd/yyyy"
$dateStartDate.DataBindings.DefaultDataSourceUpdateMode = 0
$dateStartDate.Enabled = $False
$dateStartDate.Format = 8
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 152
$System_Drawing_Point.Y = 178
$dateStartDate.Location = $System_Drawing_Point
$dateStartDate.Name = "dateStartDate"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 124
$dateStartDate.Size = $System_Drawing_Size
$dateStartDate.TabIndex = 8
$dateStartDate.add_ValueChanged($dateStartDate_ValueChanged)
$form1.Controls.Add($dateStartDate)
$labelStartTime.DataBindings.DefaultDataSourceUpdateMode = 0
$labelStartTime.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 82
$System_Drawing_Point.Y = 175
$labelStartTime.Location = $System_Drawing_Point
$labelStartTime.Name = "labelStartTime"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 64
$labelStartTime.Size = $System_Drawing_Size
$labelStartTime.TabIndex = 7
$labelStartTime.Text = "Start time:"
$labelStartTime.TextAlign = 16
$form1.Controls.Add($labelStartTime)
$checkOnlySend.DataBindings.DefaultDataSourceUpdateMode = 0
$checkOnlySend.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 52
$System_Drawing_Point.Y = 148
$checkOnlySend.Location = $System_Drawing_Point
$checkOnlySend.Name = "checkOnlySend"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 190
$checkOnlySend.Size = $System_Drawing_Size
$checkOnlySend.TabIndex = 6
$checkOnlySend.Text = "Only send during this time range:"
$checkOnlySend.UseVisualStyleBackColor = $True
$checkOnlySend.add_Click($handler_checkOnlySend_Click)
$form1.Controls.Add($checkOnlySend)
$radioSend.DataBindings.DefaultDataSourceUpdateMode = 0
$radioSend.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 125
$radioSend.Location = $System_Drawing_Point
$radioSend.Name = "radioSend"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 182
$radioSend.Size = $System_Drawing_Size
$radioSend.TabIndex = 5
$radioSend.Text = "Send automatic replies"
$radioSend.UseVisualStyleBackColor = $True
$radioSend.add_Click($handler_radioSend_Click)
$form1.Controls.Add($radioSend)
$radioDoNotSend.Checked = $True
$radioDoNotSend.DataBindings.DefaultDataSourceUpdateMode = 0
$radioDoNotSend.Enabled = $False
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 104
$radioDoNotSend.Location = $System_Drawing_Point
$radioDoNotSend.Name = "radioDoNotSend"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 182
$radioDoNotSend.Size = $System_Drawing_Size
$radioDoNotSend.TabIndex = 4
$radioDoNotSend.TabStop = $True
$radioDoNotSend.Text = "Do not send automatic replies"
$radioDoNotSend.UseVisualStyleBackColor = $True
$radioDoNotSend.add_Click($handler_radioDoNotSend_Click)
$form1.Controls.Add($radioDoNotSend)
$comboIdentity.DataBindings.DefaultDataSourceUpdateMode = 0
$comboIdentity.DropDownStyle = 2
$comboIdentity.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 69
$System_Drawing_Point.Y = 67
$comboIdentity.Location = $System_Drawing_Point
$comboIdentity.Name = "comboIdentity"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 458
$comboIdentity.Size = $System_Drawing_Size
$comboIdentity.TabIndex = 3
$comboIdentity.add_SelectionChangeCommitted($comboIdentity_SelectionChangeCommitted)
$form1.Controls.Add($comboIdentity)
$labelIdentity.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 66
$labelIdentity.Location = $System_Drawing_Point
$labelIdentity.Name = "labelIdentity"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 50
$labelIdentity.Size = $System_Drawing_Size
$labelIdentity.TabIndex = 2
$labelIdentity.Text = "Identity:"
$labelIdentity.TextAlign = 16
$form1.Controls.Add($labelIdentity)
$labelTitle.DataBindings.DefaultDataSourceUpdateMode = 0
$labelTitle.Font = New-Object System.Drawing.Font("Trebuchet MS",9.75,1,3,1)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 52
$System_Drawing_Point.Y = 13
$labelTitle.Location = $System_Drawing_Point
$labelTitle.Name = "labelTitle"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 31
$System_Drawing_Size.Width = 469
$labelTitle.Size = $System_Drawing_Size
$labelTitle.TabIndex = 1
$labelTitle.Text = "Exchange Automatic Replies Administrator"
$labelTitle.TextAlign = 16
$form1.Controls.Add($labelTitle)
$pbIcon.BackgroundImageLayout = 3
$pbIcon.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 13
$pbIcon.Location = $System_Drawing_Point
$pbIcon.Name = "pbIcon"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 32
$System_Drawing_Size.Width = 32
$pbIcon.Size = $System_Drawing_Size
$pbIcon.TabIndex = 0
$pbIcon.TabStop = $False
$pbIcon.Image=$logobmp
$form1.Controls.Add($pbIcon)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
function GetAutoReplyStatus ($identity) {
try {
$status=Get-MailboxAutoReplyConfiguration $identity
switch ($status.autoreplystate) {
enabled { Status-EnabledAutoReply }
disabled { Status-DisabledAutoReply }
scheduled { Status-ScheduledAutoReply }
}
$dateStartDate.Value=$status.StartTime
$dateStartTime.Value=$status.StartTime
$dateEndDate.Value=$status.EndTime
$dateEndTime.Value=$status.EndTime
$textInside.Text=$status.InternalMessage
$textOutside.Text=$status.ExternalMessage
switch ($status.ExternalAudience) {
All {
$checkReplyOutside.Checked = $true
$radioAll.Checked = $true
$tabPage2.Text = "Outside My Organization (On)"
}
None {
$checkReplyOutside.Checked = $false
$radioAll.Checked = $true
$radioAll.enabled=$false
$radioKnown.enabled=$false
$textOutside.Enabled=$false
$tabPage2.Text = "Outside My Organization (Off)"
}
Known {
$checkReplyOutside.Checked = $true
$radioKnown.Checked = $true
$tabPage2.Text = "Outside My Organization (On)"
}
}
$buttonOK.Enabled=$true
$form1.Update()
}
catch { ShowPrompt -Message $_ -Buttons OK -Icon Error;return }
}
function Status-DisabledAutoReply {
$radioDoNotSend.enabled=$true
$radioDoNotSend.checked = $true
$radioSend.enabled=$true
$radioSend.Checked=$false
$checkOnlySend.checked=$false
$checkOnlySend.enabled=$false
$labelStartTime.enabled=$false
$labelEndTime.enabled=$false
$dateStartDate.enabled=$false
$dateStartTime.enabled=$false
$dateEndDate.enabled=$false
$dateEndTime.enabled=$false
$labelAutoReply.enabled=$false
$textInside.enabled=$false
$textOutside.enabled=$false
$checkReplyOutside.enabled=$false
$radioKnown.enabled=$false
$radioAll.enabled=$false
$buttonOK.Enabled=$true
$form1.Update()
}
function Status-EnabledAutoReply {
$radioDoNotSend.enabled=$true
$radioDoNotSend.checked = $false
$radioSend.enabled=$true
$radioSend.Checked=$true
$checkOnlySend.checked=$false
$checkOnlySend.enabled=$true
$labelStartTime.enabled=$false
$labelEndTime.enabled=$false
$dateStartDate.enabled=$false
$dateStartTime.enabled=$false
$dateEndDate.enabled=$false
$dateEndTime.enabled=$false
$labelAutoReply.enabled=$true
$textInside.enabled=$true
$textOutside.enabled=$true
$checkReplyOutside.enabled=$true
$radioKnown.enabled=$true
$radioAll.enabled=$true
$buttonOK.Enabled=$true
$form1.Update()
}
function Status-ScheduledAutoReply {
$radioDoNotSend.enabled=$true
$radioDoNotSend.checked = $false
$radioSend.enabled=$true
$radioSend.Checked=$true
$checkOnlySend.checked=$true
$checkOnlySend.enabled=$true
$labelStartTime.enabled=$true
$labelEndTime.enabled=$true
$dateStartDate.enabled=$true
$dateStartTime.enabled=$true
$dateEndDate.enabled=$true
$dateEndTime.enabled=$true
$labelAutoReply.enabled=$true
$textInside.enabled=$true
$textOutside.enabled=$true
$checkReplyOutside.enabled=$true
$radioKnown.enabled=$true
$radioAll.enabled=$true
$buttonOK.Enabled=$true
$form1.Update()
}
Function ShowPrompt {
param ($Message,$Title=$Script:ScriptTitle,$Buttons,$Icon,$DefaultButton="button1")
return [System.Windows.Forms.MessageBox]::Show($Message,$Title,$Buttons,$Icon,$DefaultButton)
}
Function Hide-PowerShell {
$null = $showWindowAsync::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0)
}
$script:showWindowAsync = Add-Type -MemberDefinition @"
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@ -name Win32ShowWindowAsync -namespace Win32Functions -PassThru
if ($host.name -ne "Windows PowerShell ISE Host") { Hide-PowerShell } #Only hide console if not run from ISE.
[string]$logob64=@"
iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI
WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AsVFgcLeQdwxQAAAB1pVFh0Q29tbWVudAAAAAAAQ3Jl
YXRlZCB3aXRoIEdJTVBkLmUHAAABsklEQVRYw+2XS0sCURiG31M2OqZol8EobNEiKGjhONEvCNq2
62K1iv5Bi4KsQfoH0Toic9GinS1dBBGl7cKuUF5IJHIodTSH0yKUBMVFHRXy25zNMO/De16+7ztE
0zQ0strQ4NLV+iB1sUV/K2Idd5OmdaAF0AJoAbQAmr8VF4sfnILeNoFc4hzZ55P6O8D1OsrOugPk
EmdlZ92vQI0FoMYC/zCElWb5X+wINQFu4wrd9IaQyRUAAF0mPeQ5EXbBRJg7EI6mqOy7Kon3mA2Q
50UMdPPIPvkpU4Bq4v3WDnzceVFQHthloJL49qIEoVMj6Zs9WkjH2YUwHE3RzcMQ1Pz3mi5YDPC4
JNisPAEA0+gyYbG86gDgOvJGZd9VSRwAkoqKlZ1TAKj54+P1SfKrPrDrD5eJ130ark6PwWLkGteI
7IKJyPMi3TgIQcnkAQA2Kw+PSwoKFoPEEoD8fBs+vrxTtzeI9+xnKYjbC+PBHj4vpe+PqJaOsH0Z
DfWZiXtWhFGvKwVxbf/C+ZrlLs0jS4QTnGwdqNaGi06wuI6K03C430I2ZhwwcO1lTiQV9fKvAb4A
EHe5VK0uOSAAAAAASUVORK5CYII=
"@
$logostream=[System.IO.MemoryStream][System.Convert]::FromBase64String($logob64)
$logobmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($logostream)
$iconhandle=$logobmp.GetHicon()
$icon=[System.Drawing.Icon]::FromHandle($iconhandle)
[string]$Insideb64=@"
iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI
WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AsXFRw6KaDNtwAAAB1pVFh0Q29tbWVudAAAAAAAQ3Jl
YXRlZCB3aXRoIEdJTVBkLmUHAAAEnElEQVRIx5WVTWyUVRSGn/v9TKedb9optR0V0mIrFAIoqKUx
NDGoCYSwcisGE4kLF8YdOzfqUk2Ixg3RpDEkaqILEyVqJKjxh5rW/oCVAi1lBjo/TOl8M/PN93eP
Cwi60Lac5F3c5Jz73vec9+QqEWE9EccxtVqNIAiI4xjP8+jt7cU0zVXrrPVe3mw2mZiYoFQqied5
zM3Ncfz4ceU4zqq1aj0KLly4wNTUlNRqNcrlMtVqFRFh3759HD58WK2boFqtUqlUmJ2dlUKhgOu6
XLlyhcHBQQzDwHVdHMehv7+fwcFBzpw5QxAEHDlyRCWTybVbtLCwwMTEhARBQKFQoFwuk8/nGRgY
oKuri/379+M4abTWaB2TTqc5f/48Wuv1zWBsbEyCIGB+fh7Xdenv7+fQoUNMT0/jeR62baN1fBux
JpPpZK0W3yVwXZfZ2VmGhoY4cOAAbW1txLFGdIzv+0xOThJFEUoptNY0m03m56/gOA5KqbUJisUi
juMwMjKCYRhoHSOi0VrT3t6OiNx5uUmsNYVCgXqtzs4dO7FMa22CTCZDd3c3vu/T0tJCHOs7vdbk
cjm01kxPz6DjmFq9zrVr13DSDolkAtQ6XKS1ZnR0VCzLYvv2bcSxJggCrl5dZO7qHOneDKZWbH1w
KyNP7mOhkuPnq1Pcihc5OPCM2r3psdUVGIaBiDA+Pg7A8vIyruvSaDSwMzZRZ8il5UVe3PsC6TaH
pfkG0tjD0I4NnDjzjnx45OP/1GH8+1AJNpPKjOAH0NHRw9Gjxzh4+Hl+HO/l9Eed2EYHv1ye5Jvp
Kb48a1OsNNEitGXTnPjs/f+0k4qimIYf8v6nY7KyfB8RKao3Znjt2C5SKYf3Rs+RLyuwLPp7IdHZ
Sq7Ywd7dXdwoFXhooITvR5heguEte5VpGLQkDEyleKDLxmr4IRcXy9wsCspOIVqw2zfx3fcXiUjy
59wKvVt66cu2kExajF8Xhh/tJGEatBppxs7Z3FwOUYbN2fG8pJI2G+9P4SQMXjq4QVk3Cit8MPqD
ZHuG8OPbKhMtDj9NLlBcytG9+QH67k/itFl8/cctRob7uJyv07exnZ6sQ082hYhCAUqBUoqmL+SX
QkQEC9PCSG+gEYJhgGihGcbQ2o1pVdmzvYvFksdcIeSp4c1cX/LRAhcvVf/Xmv0b0+RLdWItGE4y
wRMPdas4DBEtBFGEH4Q0Qw+tltmYbeX32QqPP7KJxZyPVxP8+uoo3orx/QgEjJ4NbTx3YCtLN6e4
ls9xq9bAbXi49Tq1aoWZiyVGdnXxyRe/89d8CWUYayKMhIYXIMg/ixaEEef+WOD7ny5JsVCnsuJh
ErLl4SxDu/vUtoEeXj85I+Wok0xHJw2vSrNRI2lBFEMcCVoEUQYPZlPklqp8/uawUuv9Mm9vuzDy
8reyeWCQulflt1+nMEwDyzSxEyamYWBaJq0tNgnb5vS7Tw3cEwHA2fEbvHFyUpKZLGF1iVNvPa24
46A7q4VSPKtQ37U7FojIPUFrTRDGvH1qRg69+pWslW9wj6GUwrYMXnluUK0r/15bdHceIqxUAzo7
WlbN+xtBXrZJwlIuCAAAAABJRU5ErkJggg==
"@
$Insidestream=[System.IO.MemoryStream][System.Convert]::FromBase64String($Insideb64)
$Insidebmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($Insidestream)
$Insideiconhandle=$Insidebmp.GetHicon()
$Insideicon=[System.Drawing.Icon]::FromHandle($Insideiconhandle)
[string]$Outsideb64=@"
iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI
WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AsXFRol8vJnxAAAAB1pVFh0Q29tbWVudAAAAAAAQ3Jl
YXRlZCB3aXRoIEdJTVBkLmUHAAAFqklEQVRIx52VS2xcVxnHf+fcc+/MnRnPM37bSWxMXm7TUEhC
SkHqC5CKxBKQYIXEBokdQggWLFiwogsESCBKK0VQIYHaJiqIEvpK27hx68oRTWjqOIkdzySe6/G8
78x9fCzcJJWwqcQnfZvznXM+/f/f469qtRrbmYiglMJrb+A1GhjJIGIjIgAkHc3EUJaPM7NTQClF
JBFvXpnj9Py85IJZgmAQCUHFIbtHUnzv68eVpdWdpNv+s7Gx8V+H7aDFm8vneOHSKTGJHK1WkUSm
ReB/lsFsRO/WKE3PZTzX4sFDBXVoZoTiQPLjE3htj/fX3+dP7zwjdmEAowsEkRAFo1jRJGiNM7JA
gIu1/kXqlSJhxyNq3OTbX5pQh2cGSbsGpdRdij4K71LlIk+9flIm9iex7DS9WppGe5Ch7B4mSxZ+
d5R/rSl62mMyaQgyKZrKphem+OvckqRdR81OFbGsjyCoVqsA9CKfHzz/Q8mPweCEwo2HibslTDJm
LFXA0VBuhNS9B7GCCUTbVBshjU7MZj2g6a2Q11f57uOzanZm7E5d9O2Cnv3gDexciFsIAYVJ+JR2
NXGtkEvXYt69vIv1m59iKLOXiaEBShmbfMYmkzYkXYM7XkUOn+Hnp/4o9Wbz0dsItIgQxxF/effP
YiUiolARBBYSWOhY6NYzRL3DpMwxJvOHyKdS2LYi4Sgco7C14GgFcYDftFhqw2ql8g8RQUQwXtvj
rWtzdCQghUH3XCzHodFJsbpZImofYGbkEIVMhqSjMBoEwQ+2ZgWl0AaCm1PUlr4CdXju7LwcmJ5W
AOZmbYOT//ybxFmfq0sjVKN99HvjiB4hmx1jYnCUkASdIN6izoIwEgzw0CcdHC1sdIRfnH+e4XuX
yPsDeMu5O0XWUc+lV57F4LNxdYwPFg9R3biHRHKWpDNEGCta3YiWH9PsC40uNHxhJGcR9kNefNtj
siiEiQvkBjqo1C0su8sdiuI4ottvUHCEoDtDOzhASivCIKDXh24Pml2IROiHMQNJzb5dhqIT8bvT
q2g0/ciimLaJ+5pyq8awBHe6yMSxwm9rli9kyE69wZ78e9QqD9Pp7UY5faLmAEKOds9iMKu5bxia
tTqnXvKY3Z/j+mqTVa/Nt6Z/hB9HPD7UJ73XYTNIYdA/M1EE3bZhszLD7N4a6dK/iRNCWP8cqjSH
d+PTGPUAsZtk37ShVW9y8u8rPHxijJRtMTno8uJch4oXo5XBNkkK2SQLK13JJSxM2nW4Z/+Ien2+
K9fnSzTKSwwcvEhpuoxOdgjMdYJWmc/sfozR1C6efHmNh06Mc6PaJTmZZSDvciSfREShAKW25kop
xfJKgKpUKogovvHj0/LOFQPiM37wLSaOl7EzFvm0zVdHv0mzPM6pV/scvW8v67U+sQg77dCMa/jE
5AALFzc/nGQNX3t0WmlVR2lFgCLohHSaAWUvxPWneeLJZWamhrm24tNpxfhtobeDt5rCmhfh96Kt
BIjw+funvqODKpoaqcwGnU6fzq0+vTWfSrDIL39ygJfPXqBcbaK0/p+O0gSxptPtb1F0ex89+9Il
fv/sgtTsV3AnyyCCpQ3ZVIHZiQMcn3qA3/xBoZ0RhoaG6bQ36fV8XBuiEOJIiASSrs3YcIYrK7W7
iiYifOH+PWTTSfXTp18Rf1NhJUBsn436Gq/WK9gYHjlxjN8+c5lioUCr7XPxvStYRmMbg2U0xtLY
tuH6qkXCse8iAIhFiCLh3OJ5nnjqV1IOqlg5DdoFBNtyeOzII+QS0zx3RpPfNc7i4mV+/f296ti9
B1FKIRIjskU7gCqXy9t2glfzWLq6xJlz5+TGZhWLLRVx3STjI0NMDE7zwvkMry2sM//0l1UmuYPo
7yTYxXyR4pEiR48cVds+NIZSqSqvLax/uHd2EP21tTX+b1OGZickm9KIxNte+Q+Cp8N7LC5FgwAA
AABJRU5ErkJggg==
"@
$Outsidestream=[System.IO.MemoryStream][System.Convert]::FromBase64String($Outsideb64)
$Outsidebmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($Outsidestream)
$Outsideiconhandle=$Outsidebmp.GetHicon()
$Outsideicon=[System.Drawing.Icon]::FromHandle($Outsideiconhandle)
if (!(Test-Path $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1)) { ShowPrompt -Message "This application requires the Exchange Management Shell to be installed on this computer. Please install the Exchange Management Tools from the Microsoft Exchange Server installation media." -icon Error -buttons OK;break }
try {
.$env:ExchangeInstallPath\\bin\\RemoteExchange.ps1 | Out-Null
Connect-ExchangeServer -auto | Out-Null
}
catch { ShowPrompt -Message $_ -Buttons OK -Icon Error; break }
GenerateForm
Get-PSSession | Remove-PSSession -Confirm:$false
Exit-PSSession
|
PowerShellCorpus/PoshCode/Stop-ProcessRemote.ps1
|
Stop-ProcessRemote.ps1
|
Function Stop-ProcessRemote()
{
<#
.SYNOPSIS
Stops a process on a remote computer
.DESCRIPTION
Uses WMI to connect to a remote computer and terminate a process.
Assumes the user has administrative priviledges on the remote
computer.
.NOTES
Author : Brian Wahoff
Requires : Powershell V2
.PARAMETER ComputerName
The remote computer to which you want to connect
.PARAMETER Id
The PID of the process to stop (See Get-Process)
.PARAMETER ProcessName
The name of the process to stop. Will stop all processes with the same name
#>
param(
[Parameter(Position=0, Mandatory=$TRUE)]
[string]$ComputerName,
[Parameter(ParameterSetName="p1",Position=1,ValueFromPipeline=$TRUE)]
[int]$Id,
[Parameter(ParameterSetName="p2",Position=1, ValueFromPipeline=$TRUE)]
[string]$ProcessName)
if ($Id) {
$query = "select * from Win32_Process Where ProcessID = {0}" -f $Id
} else {
if ($ProcessName) {
$query = "select * from Win32_Process Where Name = '{0}'" -f $ProcessName
} else {
throw 'Either $Id or $ProcessName is required'
}
}
$process = Get-WMIObject -computer $ComputerName -query $query
if ($process) {
if ($process.count -gt 1) {
foreach ($p in $process) {
Stop-WMIProcess($p)
}
} else {
Stop-WMIProcess($process)
}
} else {
if ($ProcessName)
{
"Process '{0}' was not running on \\\\{1}" -f $ProcessName, $ComputerName
} else {
"Process '{0}' was not running on \\\\{1}" -f $Id, $ComputerName
}
}
}
Function Stop-WMIProcess($WmiProcess) {
<#
.SYNOPSIS
Stop a WmiProcess
.DESCRIPTION
Wrapper function around WmiProcess.Terminate. Displays message
based on all documented return values. Not intended to be called
directly.
.NOTES
Author : Brian Wahoff
Requires : Powershell V2
.PARAMETER WmiProcess
The WMI Process object to terminate
#>
$ret = $WmiProcess.Terminate()
switch ($ret.ReturnValue)
{
0 {
"Process {0}:{1} terminated" -f $WmiProcess.Name, $WmiProcess.ProcessID
}
2 {
"Access was denied terminating {0}" -f $WmiProcess.Name
}
3 {
"Insufficient Privilege terminating {0}" -f $WmiProcess.Name
}
8 {
"Unknown failure terminating {0}" -f $WmiProcess.Name
}
9
{
"Path Not Found"
}
21
{
"WMI Parameter Invalid"
}
}
}
|
PowerShellCorpus/PoshCode/Write-ScriptVariables.ps1
|
Write-ScriptVariables.ps1
|
function Write-ScriptVariables {
$globalVars = get-variable -scope Global | % { $_.Name }
Get-Variable -scope Script | Where-Object { $globalVars -notcontains $_.Name } | Where-Object { $_.Name -ne 'globalVars' } | Out-String
}
|
PowerShellCorpus/PoshCode/Log 4 SP easy restore .ps1
|
Log 4 SP easy restore .ps1
|
####### Log deletions in all sites in a web application ######
############# http://iLoveSharePoint.com ##################
############## by Christian Glessner ######################
################ begin config #################
# Url of the web application to audit. Don't forget to activate the delete audit log on sites you want to log.
$targetWebAppUrl = "http://localhost:100"
# Url of the web that contains the list to log (list must contains the following columns: "Title" (text), "Event Url" (Url), "Item Type" (text), "Event" (text), "Occurred" (DateTime), "User" (text)"
$logWebUrl = "http://localhost:100"
# Title of the log list
$logListTitle ="Audit"
################# end config ##################
$lastRunPropName = "_iLSP_lastAuditTimestamp"
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint')
$logSite = New-Object Microsoft.SharePoint.SPSite($logWebUrl)
$logWeb = $logSite.OpenWeb()
$logList = $logWeb.Lists[$logListTitle]
$targetWebApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($(New-Object Uri($targetWebAppUrl)))
if($targetWebApp.Properties.ContainsKey($lastRunPropName) -eq $false)
{
$targetWebApp.Properties[$lastRunPropName] = [DateTime]::MinValue
$targetWebApp.Update()
}
$lastRun = [DateTime]::Parse($targetWebApp.Properties[$lastRunPropName].ToString())
$newRun = [DateTime]::Now.ToUniversalTime()
foreach($site in $targetWebApp.Sites)
{
$query = New-Object Microsoft.SharePoint.SPAuditQuery($site)
$query.AddEventRestriction([Microsoft.SharePoint.SPAuditEventType]::Delete)
$query.SetRangeStart($lastRun)
$query.SetRangeEnd($newRun.AddDays(1))
$result = $site.Audit.GetEntries($query)
if($result.Count -gt 0)
{
foreach($entry in $result)
{
$eventUrl = $site.Url + "/" + $entry.DocLocation
$item = $logList.Items.Add()
$item[[Microsoft.SharePoint.SPBuiltInFieldId]::Title] = $entry.DocLocation
$item["Event Url"] = $eventUrl
$item["Item Type"] = $entry.ItemType
$item["Event"] = $entry.Event
$item["Occurred"] = $entry.Occurred.ToLocalTime()
$item["User"] = $logWeb.SiteUsers.GetByID($entry.UserId).LoginName
$item.Update()
}
}
$site.Dispose()
}
$targetWebApp.Properties[$lastRunPropName] = $newRun
$targetWebApp.Update()
$logWeb.Dispose()
$logSite.Dispose()
|
PowerShellCorpus/PoshCode/Get-NTFSPermissions.ps1
|
Get-NTFSPermissions.ps1
|
<#
.SYNOPSIS
Author:..Vidrine
Date:....2013.01.14
.DESCRIPTION
Thanks to http://jfrmilner.wordpress.com/
Specify target host and root directory. The script will then recursively check for all folders and report on their NTFS permissions.
Output is stored in a custom object, that is then exported to CSV.
Script can easily be scaled to include processing multiple hosts, processing hosts imported from source file, process files instead of just folders, etc...
#>
$targetServer = '\\\\svr-foo' #Enter hostname
$targetDirectory = 'fooDirectory' #Enter directory name
$target = Join-Path -ChildPath $targetDirectory -Path $targetServer
$arrResults = @() #Initialize array used to store custom object output
$exportPath = 'C:\\temp\\ntfsCheck.csv' #Enter name of the CSV output file
#Query target directory for all 'folders' (excludes files via Where statement)
Get-ChildItem -Recurse -Path $target | Where { $_.PSIsContainer } |
forEach {
$objPath = $_.FullName
$coLACL = Get-Acl -Path $objPath
forEach ( $objACL in $colACL ) {
forEach ( $accessRight in $objACL.Access ) {
$objResults = New-Object –TypeName PSObject
$objResults | Add-Member –MemberType NoteProperty –Name DirectoryPath –Value $objPath
$objResults | Add-Member –MemberType NoteProperty –Name Identity –Value $accessRight.IdentityReference
$objResults | Add-Member –MemberType NoteProperty –Name SystemRights –Value $accessRight.FileSystemRights
$objResults | Add-Member –MemberType NoteProperty –Name SystemRightsType –Value $accessRight.AccessControlType
$objResults | Add-Member -MemberType NoteProperty -Name IsInherited -Value $accessRight.IsInherited
$objResults | Add-Member -MemberType NoteProperty -Name InheritanceFlags -Value $accessRight.InheritanceFlags
$objResults | Add-Member –MemberType NoteProperty –Name RulesProtected –Value $objACL.AreAccessRulesProtected
$arrResults += $objResults
}
}
}
$arrResults | Export-CSV -NoTypeInformation -Path $exportPath
|
PowerShellCorpus/PoshCode/New-DynamicVariable.ps1
|
New-DynamicVariable.ps1
|
##############################################################################\n##\n## New-DynamicVariable\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nCreates a variable that supports scripted actions for its getter and setter\n\n.EXAMPLE\n\nPS >.\\New-DynamicVariable GLOBAL:WindowTitle `\n -Getter { $host.UI.RawUI.WindowTitle } `\n -Setter { $host.UI.RawUI.WindowTitle = $args[0] }\n\nPS >$windowTitle\nAdministrator: C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\nPS >$windowTitle = "Test"\nPS >$windowTitle\nTest\n\n#>\n\nparam(\n ## The name for the dynamic variable\n [Parameter(Mandatory = $true)]\n $Name,\n\n ## The scriptblock to invoke when getting the value of the variable\n [Parameter(Mandatory = $true)]\n [ScriptBlock] $Getter,\n\n ## The scriptblock to invoke when setting the value of the variable\n [ScriptBlock] $Setter\n)\n\nSet-StrictMode -Version Latest\n\nAdd-Type @"\nusing System;\nusing System.Collections.ObjectModel;\nusing System.Management.Automation;\n\nnamespace Lee.Holmes\n{\n public class DynamicVariable : PSVariable\n {\n public DynamicVariable(\n string name,\n ScriptBlock scriptGetter,\n ScriptBlock scriptSetter)\n : base(name, null, ScopedItemOptions.AllScope)\n {\n getter = scriptGetter;\n setter = scriptSetter;\n }\n private ScriptBlock getter;\n private ScriptBlock setter;\n\n public override object Value\n {\n get\n {\n if(getter != null)\n {\n Collection<PSObject> results = getter.Invoke();\n if(results.Count == 1)\n {\n return results[0];\n }\n else\n {\n PSObject[] returnResults =\n new PSObject[results.Count];\n results.CopyTo(returnResults, 0);\n return returnResults;\n }\n }\n else { return null; }\n }\n set\n {\n if(setter != null) { setter.Invoke(value); }\n }\n }\n }\n}\n"@\n\n## If we've already defined the variable, remove it.\nif(Test-Path variable:\\$name)\n{\n Remove-Item variable:\\$name -Force\n}\n\n## Set the new variable, along with its getter and setter.\n$executioncontext.SessionState.PSVariable.Set(\n (New-Object Lee.Holmes.DynamicVariable $name,$getter,$setter))
|
PowerShellCorpus/PoshCode/netcast show downloader_1.ps1
|
netcast show downloader_1.ps1
|
cd M:\\Files\\Netcasts\\ShowName # switch to the diretory to store your content
Import-Module BitsTransfer # enable BITS on host machine as a file transfer method
$start=47 # start epidode number
$end=170 # end epidode number
$url="http://download.domain.com/episodes/" # URL of the download up to the directory containing the content
$file_base="Podcast-" # this is the filename of the download without the show number
$file_ext=".ogg"
for($i=$start;$i -le $end;$i++) # start the loop, and run until end of range, incrementing by one
{
$b="{0:D3}" -f $i # cast loop counter to a string, stored as a formated number with leading zeros, example 002
$file="$file_base$b$file_ext" # Concatenatesthe file name with formated loop counter + file extension
Start-BitsTransfer -source $url$file; # download trigger,
}
|
PowerShellCorpus/PoshCode/Backup full.ps1
|
Backup full.ps1
|
# Ańadimos el modulo de exchange
If ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null)
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
}
$lista= ""
[int]$tam=30
$server = "MAILBOX"
$discos=get-wmiobject -class win32_volume -filter "DriveType=3" -computer $server
$databases = Get-MailboxDatabase -Server $server -Status
foreach ($database in $databases)
{
# Continuar solo si la bbdd no es de recovery
if (-not $database.Recovery)
{
# Continuar solo si la bbdd esta montada
if ($database.Mounted)
{
# Continuar solo si la bbdd no esta en modo backup
if (-not $database.BackupInProgress)
{
# A partir de aqui, sacamos los tamańos de la unidad de log
#Sacamos la unidades en la que se encuentra el log
$logpath = (get-storagegroup $database.storagegroup).logfolderpath
foreach ($disco in $discos)
{
#Verficamos que el server tenga la unidad log
if ($disco.driveletter -eq $logpath.drivename)
{
$tamlog= ($disco.freespace/1GB)
#Comparamos el tamańo
if ($tamlog -lt $tam)
{
if ($lista.Length -gt 0)
{
$lista += ","
}
$lista += "`"" + $($database.StorageGroupname) + "`""
$tamlog = $tam
}
}
}
}
}
}
}
# Ejecutar el full
$hoy = Get-Date
$fecha = $hoy.ToString("yyyyMMdd")
$log_full = "Full_" + $fecha + ".log"
cd "Ruta ejecutable del tdpexcc"
. ".\\tdpexcc.exe" "backup" $lista "full" >> $log_full
#Guardamos la lista de backups por dia
$fechac = Get-date
if ((Test-Path "F:\\Logs_BCKP\\full.txt") -ne $true)
{
New-Item -path "F:\\Logs_BCKP" -name "full.txt" -type File
}
Write "------------------------------------------" >> "F:\\Logs_BCKP\\full.txt"
Write $fechac >> "F:\\Logs_BCKP\\full.txt"
Write "FULL" $lista_full >> "F:\\Logs_BCKP\\full.txt"
Write "------------------------------------------" >> "F:\\Logs_BCKP\\full.txt"
# Limpiar logs, conservar 60 dias
foreach ($oldfile in (Get-ChildItem Full_*.log))
{
if ($oldfile.LastWriteTime -le $hoy.AddDays(-60))
{
Remove-Item $oldfile
}
}
|
PowerShellCorpus/PoshCode/79de7fa1-6c33-48aa-b0e4-a5f72def9bcc.ps1
|
79de7fa1-6c33-48aa-b0e4-a5f72def9bcc.ps1
|
################################################################
#
# PC Info v1.0 for SNOS(http://www.snos.ru/)
# (c)2009 by MakcoH(http://twitter.com/MakcoH)
# Script gathers information about remote PC using SCCM and WMI
#
################################################################
# Get the path to Program Files and IE to load SCCM report that shows
# PC name by User name
$pr = [system.environment]::GetFolderPath("ProgramFiles")
$ie = $pr + "\\Internet Explorer\\iexplore.exe"
$ie = '"' + $ie + '"' + " https://sccm/SMSReporting/Reports.asp?ReportId=423"
Invoke-Command -ScriptBlock {cmd /c $ie}
# File information saves on the Desktop
$pr = [system.environment]::GetFolderPath("Desktop")
$o = $pr + "\\info.txt"
# Get the PC Name and input it
$comp = read-host "Input PC Name for gathering information: "
# Let's ping it to know that it's alive :)
$tt = "ping $comp"
$ping = Invoke-Command -ScriptBlock {cmd /c $tt}
if($ping -match "Answer*"){ # Maybe string "Answer*" is incorrect. I use Russian version of Windows :)
# this line is for separating blocks of different pc information
$t = "-" * 25
# WMI Classes for getting right information
$cInfo = Get-WmiObject win32_ComputerSystem -computername $comp
$OSInfo = Get-WmiObject win32_OperatingSystem -computername $comp
$ServInfo = Get-WmiObject win32_Service -computername $comp
$DiskInfo = Get-WmiObject Win32_LogicalDisk -computername $comp
## -----------------------------------------------------------------------
$t | Out-File $o
out-file -InputObject "PC Information [ $(Get-Date) ]" -FilePath $o -Append
$t | Out-File $o -Append
out-file -InputObject "PC name: $($cInfo.Name)" -FilePath $o -Append
# out-file -InputObject "PC IP: $($ipInfo.IPAddress[0])" -FilePath $o -Append
# Gets information from command ping. Also may be incorrect because of localization
out-file -InputObject "PC IP: $($ping[7]) $($ping[9])" -FilePath $o -Append
$t | Out-File $o -Append
out-file -InputObject "Username: $($OSInfo.RegisteredUser)" -FilePath $o -Append
out-file -InputObject "Domain: $($cInfo.Domain)" -FilePath $o -Append
out-file -InputObject "PC model: $($cInfo.Manufacturer) $($cInfo.Model)" -FilePath $o -Append
out-file -InputObject "OS Version: $($OSInfo.caption) $($OSInfo.CSDVersion)" -FilePath $o -Append
$mem = $cInfo.TotalPhysicalMemory / (1024 *1024)
$t | Out-File $o -Append
out-file -InputObject "RAM: $mem Mb" -FilePath $o -Append
out-file -InputObject "" -FilePath $o -Append
out-file -InputObject "Logical disks: " -FilePath $o -Append
$DiskInfo | foreach { Out-File -InputObject "On $($_.DeviceID)($($_.FileSystem)) is free $($($_.FreeSpace)/(1024*1024)) Mb" -FilePath $o -Append}
$t | Out-File $o -Append
out-file -InputObject "Printers:" -FilePath $o -Append
Get-WmiObject Win32_Printer | foreach{
if($_.Default -eq $true){
$cap = $_.caption + "(default)"
if($_.network -eq $true){$cap = $cap + "(network)"}
Out-File -InputObject ($cap) -FilePath $o -Append
} else {
$cap = $_.caption
if($_.network -eq $true){$cap = $cap + "(network)"}
Out-File -InputObject $cap -FilePath $o -Append
}
}
$t | Out-File $o -Append
out-file -InputObject "Applications:" -FilePath $o -Append
out-file -InputObject "Internet Explorer Version: $((([wmiclass]"\\root\\default:stdRegProv").GetStringValue(2147483650,"SOFTWARE\\Microsoft\\Internet Explorer\\","Version")).sValue)" -FilePath $o -Append
# Get Antivirus Information
$AntiVirusExist = 0
$ServInfo | foreach {
if($_.Description -like "*Eset*"){
$AntiVirusExist = 1
$cap = "Service Nod32: $($_.Name)"
if($_.state -eq "Running"){ $cap = $cap + "(running)"}
out-file -InputObject $cap -FilePath $o -Append
}
if($_.Description -like "*Avast*"){
$AntiVirusExist = 1
$cap = "Service Avast: $($_.Name)"
if($_.state -eq "Running"){ $cap = $cap + "(running)"}
out-file -InputObject $cap -FilePath $o -Append
}
if($_.Description -like "*Forefront*"){
$AntiVirusExist = 1
$cap = "Service Forefront: $($_.Name)"
if($_.state -eq "Running"){ $cap = $cap + "(running)"}
out-file -InputObject $cap -FilePath $o -Append
}
}
if($AntiVirusExist -eq 0){
out-file -InputObject "Antivirus not detected. Check services:" -FilePath $o -Append
$t | Out-File $o -Append
$servinfo | ft name,startmode,state,status | Out-File $o -Append
$t | Out-File $o -Append
}
}
# if ping isn't successful then input all ping information to file
else
{
$ping | Out-File $o
}
# open this file with notepad
notepad $o
|
PowerShellCorpus/PoshCode/Shift Operators(Correct).ps1
|
Shift Operators(Correct).ps1
|
#requires -version 2.0
Add-Type @"
public class Shift {
public static int Right(int x, int count) { return x >> count; }
public static uint Right(uint x, int count) { return x >> count; }
public static long Right(long x, int count) { return x >> count; }
public static ulong Right(ulong x, int count) { return x >> count; }
public static int Left(int x, int count) { return x << count; }
public static uint Left(uint x, int count) { return x << count; }
public static long Left(long x, int count) { return x << count; }
public static ulong Left(ulong x, int count) { return x << count; }
}
"@
#.Example
# Shift-Left 16 1 ## returns 32
#.Example
# 8,16 |Shift-Left ## returns 16,32
function Shift-Left {
PARAM( $x=1, $y )
BEGIN {
if($y) {
[Shift]::Left( $x, $y )
}
}
PROCESS {
if($_){
[Shift]::Left($_, $x)
}
}
}
#.Example
# Shift-Right 8 1 ## returns 4
#.Example
# 2,4,8 |Shift-Right 2 ## returns 0,1,2
function Shift-Right {
PARAM( $x=1, $y )
BEGIN {
if($y) {
[Shift]::Right( $x, $y )
}
}
PROCESS {
if($_){
[Shift]::Right($_, $x)
}
}
}
|
PowerShellCorpus/PoshCode/ConvertTo-MultiArray_2.ps1
|
ConvertTo-MultiArray_2.ps1
|
function ConvertTo-MultiArray {
<#
.Notes
NAME: ConvertTo-MultiArray
AUTHOR: Tome Tanasovski
Website: http://powertoe.wordpress.com
Twitter: http://twitter.com/toenuff
Version: 1.0
CREATED: 11/5/2010
LASTEDIT:
11/5/2010 1.0
Initial Release
11/5/2010 1.1
Removed array parameter and passes a reference to the multi-dimensional array as output to the cmdlet
11/5/2010 1.2
Modified all rows to ensure they are entered as string values including $null values as a blank ("") string.
.Synopsis
Converts a collection of PowerShell objects into a multi-dimensional array
.Description
Converts a collection of PowerShell objects into a multi-dimensional array. The first row of the array contains the property names. Each additional row contains the values for each object.
This cmdlet was created to act as an intermediary to importing PowerShell objects into a range of cells in Exchange. By using a multi-dimensional array you can greatly speed up the process of adding data to Excel through the Excel COM objects.
.Parameter InputObject
Specifies the objects to export into the multi dimensional array. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to ConvertTo-MultiArray.
.Inputs
System.Management.Automation.PSObject
You can pipe any .NET Framework object to ConvertTo-MultiArray
.Outputs
[ref]
The cmdlet will return a reference to the multi-dimensional array. To access the array itself you will need to use the Value property of the reference
.Example
$arrayref = get-process |Convertto-MultiArray
.Example
$dir = Get-ChildItem c:\\
$arrayref = Convertto-MultiArray -InputObject $dir
.Example
$range.value2 = (ConvertTo-MultiArray (get-process)).value
.LINK
http://powertoe.wordpress.com
#>
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[PSObject[]]$InputObject
)
BEGIN {
$objects = @()
[ref]$array = [ref]$null
}
Process {
$objects += $InputObject
}
END {
$properties = $objects[0].psobject.properties |%{$_.name}
$array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count
# i = row and j = column
$j = 0
$properties |%{
$array.Value[0,$j] = $_.tostring()
$j++
}
$i = 1
$objects |% {
$item = $_
$j = 0
$properties | % {
if ($item.($_) -eq $null) {
$array.value[$i,$j] = ""
}
else {
$array.value[$i,$j] = $item.($_).tostring()
}
$j++
}
$i++
}
$array
}
}
|
PowerShellCorpus/PoshCode/PowerShell Talk Chickens_1.ps1
|
PowerShell Talk Chickens_1.ps1
|
#The PowerShell Talk
#Virtualization Congress 2009
#
#The Chicken Counter Script
#Get our cretendials
#More on credential stores: http://professionalvmware.com/2009/04/09/posh-article-of-the-week-secure-credential-storage/
$credentials = Get-VICredentialStoreItem -File "c:\\scripts\\really_secure_file.xml"
#Setup Our Counters
$datacenters = @{
Name = "Datacenters"
Expression = { Get-Datacenter | Measure-Object}
}
$hosts = @{
Name = "Hosts"
Expression = { Get-VMHost | Measure-Object }
}
$vms = @{
Name = "VMs"
Expression = { Get-VM | Measure-Object }
}
$clusters = @{
Name = "Clusters"
Expression = { Get-Cluster | Measure-Object }
}
#Connect to each vCenter in the credentials file
ForEach ($creds in $credentials) {
#Connect, Count, Disconnect
connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password
$output = $datacenter | Select-Object $datacenters, $hosts, $vms, $clusters
disconnect-viserver -confirm:$false
#Add this to the mail
$Body += "`nvCenter: " + $creds.Host
$Body += "`nDatacenters: " + $output.Datacenterss.count
@@$Body += "`nDatacenters: " + $output.Datacenters.count
$Body += "`nHosts: " + $output.Hosts.Count
$Body += "`nVMs: " + $output.VM.Count
@@$Body += "`nVMs: " + $output.VMS.Count
$Body += "`nClusters: " + $output.Clusters.Count
#Totals
$totalHosts += $output.Hosts.count
$totalVM += $output.VM.count
@@$totalVM += $output.VMS.count
$totalDatacenters += $output.Datacenters.count
$totalClusters += $output.Clusters.count
}
#Setup & Send our Mail
$SmtpClient = new-object Net.Mail.SmtpClient("localhost")
$From = "The Farm Hand <chicken_counter@professionalvmware.com>" #Change these for your environment
$To = "Your Pointy Haired Boss <The_Boss@professionalvmware.com>" #Change these for your environment
$Title = "Direct from your local VC: Weekly Statistics"
$Body += "`n`nTotals:`n"
$Body += "`nDatacenters: " + $totalDatacenters
$Body += "`nHosts: " + $totalHosts
$Body += "`nVMs: " + $totalVM
$Body += "`nClusters: " + $totalClusters
$SmtpClient.Send($From, $To, $Title, $Body)
|
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_1.ps1
|
Send-HTMLFormattedEmail_1.ps1
|
#-------------------------------------------------
# Send-HTMLFormattedEmail
#-------------------------------------------------
# Usage: Used to send an HTML Formatted Email that is based on an XSLT template.
#-------------------------------------------------
function Send-HTMLFormattedEmail{
param ( [string] $To,
[string] $ToDisName,
[string] $BCC,
[string] $From,
[string] $FromDisName,
[string] $Subject,
[string] $Content,
[string] $Relay,
[string] $XSLPath)
try {
# Load XSL Argument List
$XSLArg = New-Object System.Xml.Xsl.XsltArgumentList
$XSLArg.Clear()
$XSLArg.AddParam("To", $Null, $ToDisName)
$XSLArg.AddParam("Content", $Null, $Content)
# Load Documents
$BaseXMLDoc = New-Object System.Xml.XmlDocument
$BaseXMLDoc.LoadXml("<root/>")
$XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform
$XSLTrans.Load($XSLPath)
#Perform XSL Transform
$FinalXMLDoc = New-Object System.Xml.XmlDocument
$MemStream = New-Object System.IO.MemoryStream
$XMLWriter = [System.Xml.XmlWriter]::Create($MemStream)
$XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter)
$XMLWriter.Flush()
$MemStream.Position = 0
# Load the results
$FinalXMLDoc.Load($MemStream)
$Body = $FinalXMLDoc.Get_OuterXML()
# Create from, To, BCC and the message strucures
$MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName
$MessTo = New-Object System.Net.Mail.Mailaddress $To
$MessBCC = New-Object System.Net.Mail.Mailaddress $BCC
$Message = New-Object System.Net.Mail.MailMessage $MessFrom, $MessTo
# Populate message
$Message.Subject = $Subject
$Message.Body = $Body
$Message.IsBodyHTML = $True
# Add BCC
$Message.BCC.Add($MessBCC)
# Create SMTP Client
$Client = New-Object System.Net.Mail.SmtpClient $Relay
# Send The Message
$Client.Send($Message)
}
catch {
return $Error[0]
}
}
### XSLT Template Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output media-type="xml" omit-xml-declaration="yes" />
<xsl:param name="To"/>
<xsl:param name="Content"/>
<xsl:template match="/">
<html>
<head>
<title>My First Formatted Email</title>
</head>
<body>
<div width="400px">
<p>Dear <xsl:value-of select="$To" />,</p>
<p></p>
<p><xsl:value-of select="$Content" /></p>
<p></p>
<p><strong>Please do not respond to this email!</strong><br />
An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p>
<p></p>
<Address>
Many thanks from your:<br />
Really Cool IT Team<br />
</Address>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
PowerShellCorpus/PoshCode/FTP module.ps1
|
FTP module.ps1
|
<#
.Synopsis
Utilities for communicating with FTP server.
#>
function Get-ScriptPath {
Split-Path $myInvocation.ScriptName
}
Import-Module (Join-Path (Get-ScriptPath) common.psm1) -Force
<#
.Synopsis
Lists contents of directory via FTP.
.Parameter oath
URL of directory to list.
.Parameter credentials
Log-in credentials.
#>
function Get-FtpList {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
<#
.Synopsis
Downloads file via FTP.
.Parameter path
URL of fiel to download.
.Parameter credentials
Log-in credentials.
#>
function Get-FtpFile {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::DownloadFile
if ($credentials) { $request.Credentials = $credentials }
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
<#
.Synopsis
Uploads binary file via FTP.
.Parameter path
URL of file to upload.
.Parameter credentials
Log-in credentials.
#>
function Set-FtpFile {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $true)]
[string] $fileName,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::UploadFile
$request.UseBinary = $true
if ($credentials) { $request.Credentials = $credentials }
Set-Request $request $fileName
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
<#
.Synopsis
Uploads text file via FTP.
.Parameter path
URL of file to upload.
.Parameter credentials
Log-in credentials.
#>
function Set-FtpTextFile {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[String[]] $content,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
begin {
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::UploadFile
$request.UseBinary = $false
if ($credentials) { $request.Credentials = $credentials }
$writer = New-Object IO.StreamWriter $request.GetRequestStream()
} process {
$writer.WriteLine($_)
} end {
$writer.Dispose()
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
}
<#
.Synopsis
Creates new directory via FTP.
.Parameter path
URL of directory to create.
.Parameter credentials
Log-in credentials.
#>
function New-FtpDir {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::MakeDirectory
if ($credentials) { $request.Credentials = $credentials }
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
<#
.Synopsis
Removes directory via FTP.
.Parameter path
URL of directory to remove.
.Parameter credentials
Log-in credentials.
#>
function Remove-FtpDir {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $path,
[Parameter(Mandatory = $false)]
[Net.ICredentials] $credentials
)
$request = [Net.WebRequest]::Create($path)
$request.Method = [Net.WebRequestMethods+Ftp]::RemoveDirectory
if ($credentials) { $request.Credentials = $credentials }
try {
$response = $request.GetResponse()
return Get-Reponse($response);
} catch [Net.WebException] {
throw
}
}
function Set-Request([Net.WebRequest] $request, $contentFileName) {
try {
$readStream = [IO.File]::OpenRead( (Convert-Path $contentFileName) )
$writeStream = $request.GetRequestStream();
$buffer = New-Object byte[] 32KB
$offset = 0
$total = $readStream.Length
$progress = 0
do {
$offset = $readStream.Read($buffer, 0, $buffer.Length)
$progress += $offset
$writeStream.Write($buffer, 0, $offset);
Write-Progress "Uploading $contentFileName" "Uploading" `
-Percent ([int]($progress / $total * 100))
} while ($offset -gt 0)
} finally {
$readStream.Close()
$writeStream.Close()
}
}
function Get-Reponse([Net.WebResponse] $response) {
use ($reader = New-Object IO.StreamReader $response.GetResponseStream()) {
while (($line = $reader.ReadLine()) -ne $null) {
Write-Output $line
}
}
}
|
PowerShellCorpus/PoshCode/Create SP2010 Farm V_5.ps1
|
Create SP2010 Farm V_5.ps1
|
############################################################################
## Create-SPFarm
## V 0.3
## Jos.Verlinde
############################################################################
Param ( [String] $Farm = "SP2010",
[String] $SQLServer = $env:COMPUTERNAME,
[String] $Passphrase = "pass@word1",
[int] $CAPort = 26101 ,
[switch] $Force = $false )
# Disable the Loopback Check on stand alone demo servers.
# This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1
New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword
#region Process Input Parameters
$SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force
$Passphrase = $null
## get Farm Account
$cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" )
#Endregion
# Create a new farm
New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm
# Create Central Admin
New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM"
#Install Help Files
Install-SPApplicationContent
#Secure resources
Initialize-SPResourceSecurity
#Install (all) features
If ( $Force ) {
$Features = Install-SPFeature –AllExistingFeatures -force
} else {
$Features = Install-SPFeature –AllExistingFeatures
}
## Report features installed
$Features
# Provision all Services works only on stand alone servers (ie one-click-install )
# Install-SPService -Provision
## Todo : Check for Errors in the evenlog
##
## Start Central Admin
Start-Process "http://$($env:COMPUTERNAME):$CAPort"
## Run Farm configuration Wizard
Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome"
##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
|
PowerShellCorpus/PoshCode/Resize Console Window.ps1
|
Resize Console Window.ps1
|
##
## Author : Roman Kuzmin
## Synopsis : Resize console window/buffer using arrow keys
##
function Size($w, $h)
{
New-Object System.Management.Automation.Host.Size($w, $h)
}
function resize()
{
Write-Host '[Arrows] resize [Esc] exit ...'
$ErrorActionPreference = 'SilentlyContinue'
for($ui = $Host.UI.RawUI;;) {
$b = $ui.BufferSize
$w = $ui.WindowSize
switch($ui.ReadKey(6).VirtualKeyCode) {
37 {
$w = Size ($w.width - 1) $w.height
$ui.WindowSize = $w
$ui.BufferSize = Size $w.width $b.height
break
}
39 {
$w = Size ($w.width + 1) $w.height
$ui.BufferSize = Size $w.width $b.height
$ui.WindowSize = $w
break
}
38 {
$ui.WindowSize = Size $w.width ($w.height - 1)
break
}
40 {
$w = Size $w.width ($w.height + 1)
if ($w.height -gt $b.height) {
$ui.BufferSize = Size $b.width $w.height
}
$ui.WindowSize = $w
break
}
27 {
return
}
}
}
}
|
PowerShellCorpus/PoshCode/Find Local Group Members_4.ps1
|
Find Local Group Members_4.ps1
|
# Author: Hal Rottenberg
# Purpose: Find matching members in a local group
# Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx
# Change these two to suit your needs
$ChildGroups = "Domain Admins", "Group Two"
$LocalGroup = "Administrators"
$MemberNames = @()
# uncomment this line to grab list of computers from a file
# $Servers = Get-Content serverlist.txt
$Servers = $env:computername # for testing on local computer
foreach ( $Server in $Servers ) {
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
$Members = @($Group.psbase.Invoke("Members"))
$Members | ForEach-Object {
$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$ChildGroups | ForEach-Object {
$output = "" | Select-Object Server, Group, InLocalAdmin
$output.Server = $Server
$output.Group = $_
$output.InLocalAdmin = $MemberNames -contains $_
Write-Output $output
}
}
|
PowerShellCorpus/PoshCode/New-Event_1.ps1
|
New-Event_1.ps1
|
function New-Event {
<#
.Synopsis
Generates a new event from a plain English string
.Description
Takes a plain English date-time string like "Scrum every day at 9am" or "Lunch every other Tuesday at noon" and turns it into an event object (see notes).
.Example
New-Event Lunch every other Friday at 11:45
.Example
New-Event Lunch at noon on Christmas
.Notes
v 1.2 Supports resolving common calendar holidays
But NaturalInputs' API still can't do relative dates, so:
You can now schedule "Lunch at noon on Easter" but not "Lunch at noon the Sunday before Memorial Day" or "Dinner at 6 PM the day after Christmas"
#>
param(
[Parameter(ValueFromRemainingArguments=$true, ValueFromPipeline=$true, Position=0)]
[string]$query
,
[DateTime]$currentTime = $([DateTime]::Now)
,
[ValidateSet("Canada", "GreatBritain", "IrelandNorthern", "IrelandRepublicOf", "Scotland", "UnitedStates")]
[String]$Country = "UnitedStates"
)
begin {
$wc = New-Object System.Net.WebClient
$time = $currentTime.ToString("yyyyMMddThhmmss")
if(!$global:Holidays) {
$service = New-WebServiceProxy http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx
$global:Holidays = $service.GetHolidaysForYear( $Country, $currentTime.Year )
$global:Holidays += $service.GetHolidaysForYear( $Country, $currentTime.Year + 1 )
}
$HolidayKeys = @{}
foreach($holiday in $global:Holidays) {
$key = $holiday.Descriptor -replace " Day" -replace "'s" -replace " Birthday"
$key = $key.Trim()
$HolidayKeys[$key] += @($holiday)
}
}
process {
foreach($key in $HolidayKeys.Keys) {
$keyPattern = [System.Text.RegularExpressions.Regex]::Escape($key)
if($query -match $keyPattern ) {
Write-Verbose $keyPattern
if($query -match "next\\s+$keyPattern") {
$currentTime = $currentTime.AddYears(1)
}
if($query -match "$keyPattern.*observed") {
$holiday = $HolidayKeys[$key] | Where-Object { $_.DateType -match "observed" -and ($_.Date.Year -eq $currentTime.Year) } | Select -First 1
} else {
$holiday = $HolidayKeys[$key] | Where-Object { $_.DateType -match "actual" -and ($_.Date.Year -eq $currentTime.Year) } | Select -First 1
}
$query = $query -replace "(next\\s+)?$keyPattern(.*observed)?", $Holiday.Date.ToString("d",$Culture)
break
}
}
Write-Verbose "Query: $query"
$query = [System.Web.HttpUtility]::UrlEncode( $query )
[xml]$event = $wc.DownloadString( "http://naturalinputs.com/query?t=$time&q=$query" )
Write-Verbose "Response: $($event.OuterXml)"
foreach($r in $event.naturalinputsresponse) {
foreach($o in $r.occurrence) {
if($o.start_date) {
if($o.start_time) {
$startdate = Get-Date ([DateTime]::ParseExact( ("{0}T{1}" -f $o.start_date, $o.start_time), "yyyyMMddTHH:mm:ss", $null)) -DisplayHint "Date"
$starttime = Get-Date ([DateTime]::ParseExact( ("{0}T{1}" -f $o.start_date, $o.start_time), "yyyyMMddTHH:mm:ss", $null)) -DisplayHint "Time"
} else {
$startdate = Get-Date ([DateTime]::ParseExact( $o.start_date, "yyyyMMdd", $null)) -DisplayHint "Date"
$starttime = $null
}
} elseif ($o.start_time) {
$startdate = $null
$starttime = Get-Date $o.start_time -DisplayHint "Time"
}
if($o.end_date) {
if($o.end_time) {
$enddate = Get-Date ([DateTime]::ParseExact( ("{0}T{1}" -f $o.end_date, $o.end_time), "yyyyMMddTHH:mm:ss", $null)) -DisplayHint "Date"
$endtime = Get-Date ([DateTime]::ParseExact( ("{0}T{1}" -f $o.end_date, $o.end_time), "yyyyMMddTHH:mm:ss", $null)) -DisplayHint "Time"
} else {
$enddate = Get-Date ([DateTime]::ParseExact( $o.end_date, "yyyyMMdd", $null)) -DisplayHint "Date"
$endtime = $null
}
} elseif ($o.end_time) {
if($o.start_date) {
$enddate = $null
$endtime = Get-Date ([DateTime]::ParseExact( ("{0}T{1}" -f $o.start_date, $o.end_time), "yyyyMMddTHH:mm:ss", $null)) -DisplayHint "Time"
} else {
$enddate = $null
$endtime = Get-Date $o.end_time -DisplayHint "Time"
}
}
New-Object PSObject -Property @{
Name=$r.message
Type=$o.type
DayOfWeek=$o.day_of_week
WeekOfMonth=$o.week_of_month
DateOfMonth=$o.date_of_month
Interval=$o.interval
StartDate=$startdate
StartTime=$starttime
EndDate=$enddate
EndTime=$endtime
# Xml=$event
} | Add-Member ScriptProperty TimeUntil { $this.StartDate - (Get-Date) } -Passthru
}
}
}
}
|
PowerShellCorpus/PoshCode/QAD.psm1.ps1
|
QAD.psm1.ps1
|
#
# Module manifest for module 'QAD'
#
# Generated from: Quest.ActiveRoles.ADManagement
#
# Generated on: 1/28/2011
#
@{
# Script module or binary module file associated with this manifest
ModuleToProcess = 'Quest.ActiveRoles.ArsPowerShellSnapIn.dll'
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = '2b34f8ae-e6eb-4d14-9536-6e69cf4f31ed'
# Author of this module
Author = 'Quest.ActiveRoles.ADManagement'
# Company or vendor of this module
CompanyName = 'Quest Software, Inc.'
# Copyright statement for this module
Copyright = 'Quest Software, Inc.'
# Description of the functionality provided by this module
Description = 'This Windows PowerShell snap-in contains cmdlets to manage Active Directory and Quest ActiveRoles Server.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = ''
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = 'Quest.ActiveRoles.ArsPowerShellSnapIn.DirectoryAccess.dll',
'Microsoft.Practices.Unity.Interception.dll',
'Quest.ActiveRolesServer.Common.dll',
'Quest.ActiveRolesServer.Common.Services.dll',
'Microsoft.Practices.Unity.dll', 'NLog.dll',
'Quest.ActiveRoles.ArsPowerShellSnapIn.Utility.dll',
'Interop.ActiveDs.dll',
'Microsoft.Practices.Unity.StaticFactory.dll',
'Interop.ArsAdsi.dll'
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = 'Quest.ActiveRoles.ADManagement.Types.ps1xml'
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = 'Quest.ActiveRoles.ADManagement.Format.ps1xml'
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = @()
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess
PrivateData = ''
}
|
PowerShellCorpus/PoshCode/Reverse filename sequenc_3.ps1
|
Reverse filename sequenc_3.ps1
|
# Reverse filename sequence v 0.9
# Author: Sean Wendt
#
# This script will rename a sequenced set of files in a directory.
# For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg
# -- it will reverse the order, so the last file is now 01, the second to last 02, etc..
#
# Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars.
# -It's hardcoded to only support 5 digit numbers right now.
# -Similarly, it will only support a file sequence with up to 5 digits.
# This is the first script I've written, I know it's not great! ;)
# Help to make it better would be appreciated. Thanks.
#
$file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt"
$file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.."
$files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders
$idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg)
for ($ctr=$files.count; $ctr -gt 0 ; --$ctr)
{
if (($idx -ge 0) -and ($idx -le 9))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension)
}
elseif (($idx -ge 10) -and ($idx -le 99))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension)
}
elseif (($idx -ge 100) -and ($idx -le 999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension)
}
elseif (($idx -ge 1000) -and ($idx -le 9999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension)
}
elseif (($idx -ge 10000) -and ($idx -le 99999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension)
}
$idx #prints the index # it just completed
}
|
PowerShellCorpus/PoshCode/Logoff all users_1.ps1
|
Logoff all users_1.ps1
|
function RemoveSpace([string]$text) {
$private:array = $text.Split(" ", `
[StringSplitOptions]::RemoveEmptyEntries)
[string]::Join(" ", $array) }
$quser = quser
foreach ($sessionString in $quser) {
$sessionString = RemoveSpace($sessionString)
$session = $sessionString.split()
if ($session[0].Equals(">nistuke")) {
continue }
if ($session[0].Equals("USERNAME")) {
continue }
# Use [1] because if the user is disconnected there will be no session ID.
$result = logoff $session[1] }
|
PowerShellCorpus/PoshCode/Find FSMO Roles.ps1
|
Find FSMO Roles.ps1
|
$DCs = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).DomainControllers
$DCs | % { if ($_.Roles -ne '') {
"Server $_ has roles:"
""
foreach ($role in $_.roles) {
$role.tostring().padleft($role.tostring().length + 10)
}
""
}
}
|
PowerShellCorpus/PoshCode/Get-SNMPHost.ps1
|
Get-SNMPHost.ps1
|
Param($VC,$ESXCreds=(Get-Credential))
Write-Host "Connecting to VC to get ESX Hosts"
Connect-VIServer $VC | out-null
$ESXHosts = Get-VMHost
foreach($esxhost in $ESXHosts)
{
Write-Host " Connecting to $esxhost"
Connect-VIServer $esxhost.name -cred $ESXCreds | out-null
$SNMPHost = Get-VMHostSnmp
$SNMPHost | Add-Member -MemberType NoteProperty -Name ESXHost -Value $esxhost.name
$SNMPHost
}
|
PowerShellCorpus/PoshCode/User Logon details.ps1
|
User Logon details.ps1
|
########
#
#Used for enumerating local workstation for user details
#Author: Adam Liquorish
#Date: 12/10/11
########
########Define Parameters
param(
[Parameter(Mandatory=$true,
HelpMessage="Enter Path for output ie c:\\Temp\\output.html.")]
[ValidateNotNullOrEmpty()]
[string]$outputpath=$(Read-Host -prompt "Path for Output"),
[Parameter(Mandatory=$true,
HelpMessage="Enter ComputerName, enter 'localhost' for current workstation")]
[ValidateNotNullOrEmpty()]
[string]$computername=$(Read-Host -prompt "Computername")
)
########END DEFINE PARAMETERS
########Define Variables
if($computername -eq "localhost"){$computername="$env:computername"}
$i=$null
$results=$null
$useroutput=$null
########END DEFINE VARIABLES
########Define HTML Output
$a="<style>"
$a=$a +"TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a=$a +"TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: thistle}"
$a=$a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a=$a + "</style>"
########END DEFINE HTML OUTPUT
#GATHER USERS USING ADSI
$computer=[ADSI]"WinNT://$computerName,computer"
$users=$computer.psbase.Children|Where-object{$_.psbase.schemaclassname -eq 'user'}
#LIST USER PROPERTIES USING .NET
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$domain= "$env:computername"
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$principal=new-object System.DirectoryServices.AccountManagement.PrincipalContext $ctype,$domain
$useroutput=foreach($user in $users){
[System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principal,$user.name)}
#OUTPUT
$results=$useroutput|select-object name,AccountLockoutTime,Enabled,LastLogon,BadLogonCount,LastPasswordSet,LastBadPasswordAttempt,PasswordNotRequired,PasswordNeverExpires,UserCannotChangePassword,AllowReversiblePasswordEncryption
$results|sort-object Name|ConvertTo-Html -head $a -title "Local Users" -body "Local Users"|Set-Content $outputpath
|
PowerShellCorpus/PoshCode/egg_timer.ps1
|
egg_timer.ps1
|
function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form_main = New-Object System.Windows.Forms.Form
$reset_button = New-Object System.Windows.Forms.Button
$label1 = New-Object System.Windows.Forms.Label
$start_button = New-Object System.Windows.Forms.Button
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$timer1 = New-Object System.Windows.Forms.Timer
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$start_button_OnClick = {
$timer1.Enabled = $true
$timer1.Start()
$start_button.Text = 'Countdown Started.'
}
$reset_button_OnClick = {
$timer1.Enabled = $false
$progressBar1.Value = 0
$start_button.Text = 'Start'
$label1.Text = '3:00'
}
$timer1_OnTick = {
$progressBar1.PerformStep()
$time = 180 - $progressBar1.Value
[char[]]$mins = "{0}" -f ($time / 60)
$secs = "{0:00}" -f ($time % 60)
$label1.Text = "{0}:{1}" -f $mins[0], $secs
if ($progressBar1.Value -eq $progressBar1.Maximum) {
$timer1.Enabled = $false
$start_button.Text = 'FINISHED!'
}
}
$OnLoadForm_StateCorrection = {
#Correct the initial state of the form to prevent the .Net maximized form issue
$form_main.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 628
$System_Drawing_Size.Height = 295
$form_main.MaximumSize = $System_Drawing_Size
$form_main.Text = 'Super Duper Over-engineered Egg Timer'
$form_main.MaximizeBox = $False
$form_main.Name = 'form_main'
$form_main.ShowIcon = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 628
$System_Drawing_Size.Height = 295
$form_main.MinimumSize = $System_Drawing_Size
$form_main.StartPosition = 1
$form_main.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 612
$System_Drawing_Size.Height = 259
$form_main.ClientSize = $System_Drawing_Size
$reset_button.TabIndex = 4
$reset_button.Name = 'button2'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 209
$System_Drawing_Size.Height = 69
$reset_button.Size = $System_Drawing_Size
$reset_button.UseVisualStyleBackColor = $True
$reset_button.Text = 'Reset'
$reset_button.Font = New-Object System.Drawing.Font("Verdana",12,0,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 362
$System_Drawing_Point.Y = 13
$reset_button.Location = $System_Drawing_Point
$reset_button.DataBindings.DefaultDataSourceUpdateMode = 0
$reset_button.add_Click($reset_button_OnClick)
$form_main.Controls.Add($reset_button)
$label1.TabIndex = 3
$label1.TextAlign = 32
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 526
$System_Drawing_Size.Height = 54
$label1.Size = $System_Drawing_Size
$label1.Text = '3:00'
$label1.Font = New-Object System.Drawing.Font("Courier New",20.25,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 89
$label1.Location = $System_Drawing_Point
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$label1.Name = 'label1'
$form_main.Controls.Add($label1)
$start_button.TabIndex = 2
$start_button.Name = 'button1'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 310
$System_Drawing_Size.Height = 70
$start_button.Size = $System_Drawing_Size
$start_button.UseVisualStyleBackColor = $True
$start_button.Text = 'Start'
$start_button.Font = New-Object System.Drawing.Font("Verdana",12,0,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 12
$start_button.Location = $System_Drawing_Point
$start_button.DataBindings.DefaultDataSourceUpdateMode = 0
$start_button.add_Click($start_button_OnClick)
$form_main.Controls.Add($start_button)
$progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0
$progressBar1.Maximum = 180
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 526
$System_Drawing_Size.Height = 87
$progressBar1.Size = $System_Drawing_Size
$progressBar1.Step = 1
$progressBar1.TabIndex = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 146
$progressBar1.Location = $System_Drawing_Point
$progressBar1.Style = 1
$progressBar1.Name = 'progressBar1'
$form_main.Controls.Add($progressBar1)
$timer1.Interval = 1000
$timer1.add_tick($timer1_OnTick)
$InitialFormWindowState = $form_main.WindowState
$form_main.add_Load($OnLoadForm_StateCorrection)
$form_main.ShowDialog()| Out-Null
}
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Set-PsBreakPointLastErro.ps1
|
Set-PsBreakPointLastErro.ps1
|
Set-StrictMode -Version Latest\n\n$lastError = $error[0]\nSet-PsBreakpoint $lastError.InvocationInfo.ScriptName `\n $lastError.InvocationInfo.ScriptLineNumber
|
PowerShellCorpus/PoshCode/Get-Parameter_15.ps1
|
Get-Parameter_15.ps1
|
function Get-Parameter
{
[OutputType('System.String')]
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[String]$Command,
[Parameter(Position=1)]
[String[]]$Name=@('*'),
[Parameter()]
[ValidateSet('Name','Type','Pos','BV','BP','Aliases','Mandatory','Dynamic')]
[String]$SortBy='Name',
[Parameter()]
[switch]$Descending,
[Parameter()]
[ValidateSet('Cmdlet','Function','Alias','ExternalScript')]
[String]$CommandType,
[switch]$IncludeCommonParameters
)
Process
{
if($CommandType)
{
switch($CommandType)
{
"function"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
"filter"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
default
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue
}
}
}
else
{
$cmd = Get-Command -Name $Command -CommandType Cmdlet,Function,Alias,ExternalScript -ErrorAction SilentlyContinue
}
if(!$cmd)
{
Throw "'$Name' is not a Cmdlet,Function,Filter,Alias or ExternalScript"
}
if($cmd.length -gt 1)
{
$types = $cmd | Select-Object -ExpandProperty CommandType -Unique
Throw "'$Command' is ambiguous and matches one of $($types -join ","). Use -CommandType to get only a specified type of command."
}
if($cmd.CommandType -eq 'Alias')
{
Write-Verbose "'$Name' refers to an Alias, reolving command."
$cmd = Get-Command -Name $cmd.ResolvedCommandName
}
if($cmd.CommandType -eq 'cmdlet')
{
# object to get default parameter values
$dv = New-Object $cmd.ImplementingType
}
foreach($set in $cmd.ParameterSets)
{
if($IncludeCommonParameters)
{
$p = $set.Parameters | Select-Object *
}
else
{
# Get a list of common parameters
$cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name
$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object *
}
$params = $p | Foreach-Object {$_.Name}
for($i=0;$i -le $p.length;$i++)
{
$flag=$false
for($x=0;$x -le $params[$i].length -and !($flag);$x++)
{
$regex = "^" + $params[$i].substring(0,$x)
if(($params -match $regex).count -eq 1)
{
$flag=$true
$p[$i].Aliases += $regex.substring(1).ToLower()
}
}
}
$p | Where-Object {$_.Name -like $Name} | Foreach-Object {
$PropertyName = $_.Name
$psn = $_.Attributes | Where-Object {$_.ParameterSetName}
if($cmd.CommandType -eq 'cmdlet')
{
$DefaultValue = $dv.PSObject.Properties[$PropertyName].Value
}
else
{
$DefaultValue = $null
}
if($psn.ParameterSetName -notmatch '__AllParameterSets')
{
$PropertyName="*$PropertyName"
}
New-Object PSObject -Property @{
ParameterSet = $set.Name
Name = $PropertyName
BV = $_.ValueFromPipeline
BP = $_.ValueFromPipelineByPropertyName
Type = $_.ParameterType.Name
Aliases = $_.Aliases
Pos = if($_.Position -lt 0) {'Named'} else {$_.Position+1}
Mandatory = $_.IsMandatory
Dynamic = $_.IsDynamic
}
} | Sort-Object -Descending:$Descending {$_.$SortBy -replace '\\*'} | Format-Table Name,Type,Pos,BV,BP,Aliases,Mandatory,Dynamic -AutoSize -GroupBy ParameterSet | Out-String
}
}
}
Set-Alias -Name gprm -Value Get-Parameter
|
PowerShellCorpus/PoshCode/Find-MSDN.ps1
|
Find-MSDN.ps1
|
function New-UrlFile
{
param( $URL = "http://www.google.com")
$UrlFile = [system.io.Path]::ChangeExtension([system.io.Path]::GetTempFileName(),".url")
$UrlFileContents = `
"[InternetShortcut]",
"URL=$URL"
$UrlFileContents | Set-Content -Path $UrlFile
Get-Item $UrlFile
}
function Find-MSDN
{
param( $Class,
$DotNetVersion = "2.0",
$Section = ""
)
switch ($DotNetVersion) {
"1.1" { $VersionStem = "(VS.71)"; break}
"2.0" { $VersionStem = "(VS.80)"; break}
"3.0" { $VersionStem = "(VS.85)"; break}
"3.5" { $VersionStem = ""; break}
}
switch ($Section) {
"Members" { $SectionStem = "_members"; break}
"Methods" { $SectionStem = "_methods"; break}
"Properties" { $SectionStem = "_properties"; break}
}
$UrlFile = New-UrlFile "http://msdn2.microsoft.com/en-us/library/$Class$SectionStem$VersionStem.aspx"
Invoke-Item $UrlFile
Remove-Item $UrlFile
}
|
PowerShellCorpus/PoshCode/Search Files by Date.ps1
|
Search Files by Date.ps1
|
<#
Author: Matt Schmitt
Date: 11/30/12
Version: 1.0
From: USA
Email: ithink2020@gmail.com
Website: http://about.me/schmittmatt
Twitter: @MatthewASchmitt
Description
A script for finding files in a directory by Last Accessed Date.
#>
Write-Host "Enter Root Directory you would like to search"
Write-Host ""
Write-Host "Example: C:\\Users\\testuser"
Write-Host ""
$directory = Read-Host ">>"
cls
Write-Host "Enter "From" Date"
Write-Host ""
Write-Host "Example: 1/1/12"
Write-Host ""
$startDate = Read-Host '>>'
cls
Write-Host "Enter "To" Date"
Write-Host ""
Write-Host "Example: 11/30/12"
Write-Host ""
$endDate = Read-Host '>>'
cls
Write-Host "Enter where you would like the CSV file to be exported"
Write-Host ""
Write-Host "Example: C:\\Files.csv"
Write-Host ""
$outPutFile = Read-Host '>>'
cls
Write-Host ""
Write-Host ""
Write-Host "Searching for files in '$directory' from '$startDate' to '$endDate'..."
Get-ChildItem -path $directory -Recurse | where { $_.lastaccesstime -ge [datetime]$startDate -and $_.lastaccesstime -lt [datetime]$endDate} | select fullname | Export-CSV -Path $outPutFile
Write-Host ""
Write-Host "Results have been exported!"
Write-Host ""
Write-Host "Press any key to Exit."
#Code to wait for user to press a key.
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/PoshCode/Join-Collections 2.1.ps1
|
Join-Collections 2.1.ps1
|
#requires -version 2.1
####################################################################################################
## Version History:
##
## Version 2.1 Use a hashtable to improve join performance significantly
## Version 2.0 Added Join-Object and removed dependency on ConvertFrom-Hashtable
## Now works on DataTables!
## Version 1.1 Fixed column uniqueness bug http://poshcode.org/1460
## Version 1.0 First post http://poshcode.org/1459
#.Note
# This script includes a Join-Object function you could use outside
#.Synopsis
# Performs a inner join on two collections of objects based on a common key column.
#.Description
# Takes two sets of objects where there are multiple "rows" and where each set has a shared column where the values match, and generates new objects with all the values from each.
#.Parameter GroupOnColumn
# The name of the property to merge on. Items with the same value in this column will be combined.
#.Parameter FirstCollection
# The first set of data
#.Parameter FirstJoinColumn
# The name of the key id column in the first set
#.Parameter SecondCollection
# The second set of data
#.Parameter SecondJoinColumn
# The name of the matching key id column in the second set
# OPTIONAL. Defaults to the same as FirstJoinColum
#.Example
# Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value
#
# Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects.
#
#.Example
# $FirstCollection = @"
# FirstName, LastName, MailingAddress, EmployeeID
# John, Doe, 123 First Ave, J8329029
# Susan Q., Public, 3025 South Street, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# $SecondCollection = @"
# ID, Week, HrsWorked, PayRate, EmployeeID
# 12276, 12, 40, 55, J8329029
# 12277, 13, 40, 55, J8329029
# 12278, 14, 42, 55, J8329029
# 12279, 12, 35, 40, K4367143
# 12280, 13, 32, 40, K4367143
# 12281, 14, 48, 40, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# Join-Collections $FirstCollection EmployeeID $SecondCollection | ft -auto
#
#.Notes
# Author: Joel Bennett
# function Join-Collections {
PARAM(
$FirstCollection
, [string]$FirstJoinColumn
, $SecondCollection
, [string]$SecondJoinColumn=$FirstJoinColumn
)
PROCESS {
$ErrorActionPreference = "Inquire"
$JoinHashTable = @{}
$SecondCollection|%{$JoinHashTable."$SecondJoinColumn" = $_}
foreach($first in $FirstCollection) {
$JoinHashTable."$FirstJoinColumn" | Join-Object $first
}
}
BEGIN {
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true)]
$Second
)
BEGIN {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
Process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
}
#}
|
PowerShellCorpus/PoshCode/Email-ExpiringADAccounts_2.ps1
|
Email-ExpiringADAccounts_2.ps1
|
Function GetMsgBody {
Write-Output @"
<p>Dear $name,</p>
Your ABC network account is about to expire.<br/>
Please email helpdesk@abc.com or simply hit 'reply', and include the following details to have your account extended.<br/>
<br/>
Your name:<br/>
The department you currently volunteer in:<br/>
The staff supervisor's name you currently report to:<br/>
The current status of your involvement with ABC (Staff/Student/Volunteer):<br/>
<br/>
Kind Regards,<br/>
ABC IT Services
"@
}
Get-QADUser -AccountExpiresBefore "31/01/2012" -Enabled -SizeLimit 0 | ForEach-Object {
#Setup email variables
$smtpserver= "" # Enter your smtp server
$from= "" # Enter your from address
$subject= "" # Enter your email subject
$email= $_.mail
$name= $_.givenName
[string]$body= GetMsgBody
#Execute PowerShell's Send-MailMessage Function
Send-MailMessage -BodyAsHtml:$true -Body $body -To $email -From $from -SmtpServer $smtp -Subject $subject
}
|
PowerShellCorpus/PoshCode/ConvertTo-ASCII_2.ps1
|
ConvertTo-ASCII_2.ps1
|
#requires -version 2.0
#region Help
<#
.SYNOPSIS
Automation script for file character set format conversion to ASCII encoding.
.DESCRIPTION
Script for automating the conversion of files to ASCII format. Good for if you've used Out-File without specifying the
encoding. Which would make a Unicode formatted file by default. If you then used Add-Content to append data to that
file it would have garbage characters because even though it states it defaults to Unicode it will write ASCII/ANSI.
.INPUTS
Full Path to files to convert.
.OUTPUTS
Replacement files in ASCII format.
.NOTES
AUTHOR: Levon Becker
TITLE: ConvertTo-Ascii
VERSION: 1.001
DATE: 4/13/2011
ENV: Powershell v2
TOOLS: PowerGUI Script Editor, RegexBuddy
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt"
Will convert all of the files with a TXT file extension in the directory named Folder2.
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt"
Will convert a single file named filename.txt in the directory named Folder2
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt" -recursive $true
Will convert all of the files with a TXT file extension in the directory named Folder2 and any subdirectories.
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt" -recursive $true
Will convert a single file named filename.txt in the directory named Folder2 and any subdirectories.
.PARAMETER path
Full path to file/s to process. Standard wild cards are excepted. Be sure to put in quotation marks.
It should work without a trailing backslash or asterisk, but it's recommended to simply include.
See examples
.PARAMETER include
File name filtering option. Standard wild cards are excepted. Be sure to put in quotation marks.
.PARAMETER recursive
Specifies if the script should look in sub-folders off the path provided. Default is False (Do not do recursive).
Use -recursive $true to enable.
.LINK
#>
#endregion Help
#region Changelog
<#
04/12/2011: Created
04/13/2011: Added time-stamp capture and write in order to keep the replacement files with the same time information as the original.
Cleaned up comments and regions.
#>
#endregion Changelog
#region Sources
<#
http://rosettacode.org/wiki/File_modification_time#PowerShell
http://www.powergui.org
http://www.regexbuddy.com
#>
#endregion Sources
#region Parameters
[CmdletBinding()]
Param (
[parameter(Mandatory=$true)][string]$path,
[parameter(Mandatory=$true)][string]$include,
[parameter(Mandatory=$false)][string]$recursive = "$false"
)
#endregion Parameters
#region Variables
$scriptver = '1.001'
$originaltitle = $Host.UI.RawUI.WindowTitle
$title = "File Convert to ASCII Script v$scriptver by Levon Becker"
$count = $null
$file = $null
#endregion Variables
Clear
$Host.UI.RawUI.WindowTitle = $title
#region Check Parameters
If ((Test-Path -Path $path) -eq $false) {
Write-Host "ERROR: PATH NOT FOUND ($path)" -BackgroundColor Red -ForegroundColor White
Break
}
#endregion Check Parameters
#region Main Process
# Check that \\* is at the end of the path
$regex = '\\b\\\\\\*'
# If not then add \\* to the end of the path
If ($path -notmatch $regex) {
$path = $path + '\\*'
}
# Get list of filenames
If ($recursive -eq $true) {
$filelist = Get-ChildItem -path $path -Include $include -Recurse
}
Else {
$filelist = Get-ChildItem -path $path -Include $include
}
Foreach ($file in $filelist) {
$count++
# Get File Information
$fullname = ($file.FullName)
$creationtime = ($file.CreationTime)
$creationtimeutc = ($file.CreationTimeUtc)
$lastwritetime = ($file.LastWriteTime)
$lastwritetimeutc = ($file.LastWriteTimeUtc)
$lastaccesstime = ($file.LastAccessTime)
$lastaccesstimeutc = ($file.LastAccessTimeUtc)
# Get File Contents
$content = Get-Content $fullname
# Replace file with corrected character set
Out-File -FilePath $fullname -Encoding ASCII -Force -InputObject $content
# Set original time stamp information on new file
Set-ItemProperty -Path $fullname -Name CreationTime ($creationtime)
Set-ItemProperty -Path $fullname -Name CreationTimeUtc ($creationtimeutc)
Set-ItemProperty -Path $fullname -Name LastWriteTime ($lastwritetime)
Set-ItemProperty -Path $fullname -Name LastWriteTimeUtc ($lastwritetimeutc)
Set-ItemProperty -Path $fullname -Name LastAccessTime ($lastaccesstime)
Set-ItemProperty -Path $fullname -Name LastAccessTimeUtc ($lastaccesstimeutc)
Write-Host $file
}
#endregion Main Process
#region Conclusion Information
Write-Host '----------------------------------------------------------------------'
Write-Host ''
Write-Host "Total Converted: " -ForegroundColor Green -NoNewline
Write-Host $count
Write-Host ''
Write-Host '-------------' -ForegroundColor Green
Write-Host '| COMPLETED |' -ForegroundColor Green
Write-Host '-------------' -ForegroundColor Green
Write-Host ''
#endregion Conclusion Information
$Host.UI.RawUI.WindowTitle = $title + ' (COMPLETED)'
Sleep -Seconds 1
$Host.UI.RawUI.WindowTitle = $originaltitle
|
PowerShellCorpus/PoshCode/Test 2.ps1
|
Test 2.ps1
|
\nTesting from PowerShell 2
|
PowerShellCorpus/PoshCode/Get_Set Signature 2.0.ps1
|
Get_Set Signature 2.0.ps1
|
#Requires -version 2.0
## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping)
####################################################################################################
## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets
## These properly parse paths, so they don't kill your pipeline and script if you include a folder
##
## Usage:
## ls | Get-AuthenticodeSignature
## Get all the signatures
##
## ls | Select-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature
## Re-sign anything you signed before that has changed
##
## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature
## Re-sign scripts that are hash-correct but not signed by me or by someone trusted
##
####################################################################################################
## History:
## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support
## 1.7 - Modified the reading of certs to better support people who only have one :)
## 1.6 - Converted to work with CTP 3, and added function help comments
## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file
## Note: If you get this off PoshCode, you'll have to create it yourself, see below:
## 1.4 - Moved the default certificate setting into an external psd1 file.
## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-AuthenticodeSigned
## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned
## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files
## It's important to remember that the signatures are NOT checked by PowerShell yet...
## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed
## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly
## - commented out the default Certificate which won't work for "you"
## 1.0 - first working version, includes wrappers for Get and Set
##
####################################################################################################
## README! README! README! README! #################################################################
## README! README! README! README! #################################################################
##
## You should set the location to your default signing certificate. The permanent way to do that is
## to modify (or create) the .psd1 file to set the PrivateData member variable. Otherwise you'll be
## prompted to provide a cert path whenever you try to sign a script without passing a certificate.
##
## The PrivateData variable should point at your code-signing certificate either with a full path
## or with the THUMBPRINT of a certificate you have available in your Cert:\\CurrentUser\\My\\ provider
##
## EG:
## 4F8842037D878C1FCDC6FD1313B200449716C353
## OR:
## "Cert:\\CurrentUser\\My\\4F8842037D878C1FCDC6FD1313B200449716C353"
## OR a file name:
## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx"
##
## The simplest thing is to just update the PSD1
##
## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 `
## -Author "" -COmpany "" -Copy "" -Desc "" `
## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() `
## -PrivateData 4F8842037D878C1FCDC6FD1313B200449716C353
##
####################################################################################################
####################################################################################################
function Get-UserCertificate {
<#.SYNOPSIS
Gets the user's default signing certificate so we don't have to ask them over and over...
.DESCRIPTION
The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can be reused without re-querying for the location and/or password ...
.RETURNVALUE
An X509Certificate2 suitable for code-signing
#>
[CmdletBinding()]
Param()
Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)"
$UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData
$ExecutionContext.SessionState.Module.PrivateData = $UserCertificate.Thumbprint
return $UserCertificate
}
function Get-AuthenticodeCertificate {
[CmdletBinding()]
PARAM (
$Name = $ExecutionContext.SessionState.Module.PrivateData
)
BEGIN {
if(!$ExecutionContext.SessionState.Module.PrivateData -and $Name) {
$ExecutionContext.SessionState.Module.PrivateData = $Name
}
}
PROCESS {
trap {
Write-Host "The authenticode script module requires configuration to function fully!"
Write-Host
Write-Host "You must put the path to your default signing certificate in the module metadata"`
"file before you can use the module's Set-Authenticode cmdlet or to the 'mine'"`
"feature of the Select-AuthenticodeSigned or Test-AuthenticodeSignature. To set it up, you can do this:"
Write-Host
Write-Host "PrivateData = 'C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\PoshCerts\\Code-Signing.pfx'"
Write-Host
Write-Host "If you load your certificate into your 'CurrentUser\\My' store, or put the .pfx file"`
"into the folder with the Authenthenticode module script, you can just specify it's"`
"thumprint or filename, respectively. Otherwise, it should be a full path."
Write-Error $_
return
}
# Import-LocalizedData -bindingVariable CertificatePath -EA "STOP"
if(!$Name) {
$certs = ls Cert:\\CurrentUser\\My
if($certs.Count) {
Write-Host "You have $($certs.Count) certs in your local cert storage which you can specify by Thumbprint:" -fore cyan
$certs | Out-Host
}
$Name = $(Read-Host "Please specify a user certificate")
}
if($Name -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
Write-Debug "CertificatePath: $Name"
$ResolvedPath = $Null
$ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue"
if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) {
Write-Debug "Not a full path: $ResolvedPath"
$ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue"
}
if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) {
Write-Debug "Not a file Path: $ResolvedPath"
$ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $("$Name".ToUpper()) -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue"
Write-Debug "ResolvedPath: $ResolvedPath"
}
$Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue"
if($Certificate -is [System.IO.FileInfo]) {
$Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue"
}
Write-Verbose "Certificate: $($Certificate | Out-String)"
$Name = $Certificate
}
return $Name
}
}
####################################################################################################
function Test-AuthenticodeSignature {
<#.SYNOPSIS
Tests a script signature to see if it is valid, or at least unaltered.
.DESCRIPTION
The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it
is Valid, OR **unaltered** and signed by the user's certificate
.NOTES
Test-AuthenticodeSignature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate.
.EXAMPLE
ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_}
To get the signature reports for all the scripts that we consider safely signed.
.EXAMPLE
ls | ? { gas $_ | Test-AuthenticodeSignature }
List all the valid signed scripts (or scripts signed by our cert)
.INPUTTYPE
System.Management.Automation.Signature
.PARAMETER Signature
Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature.
.PARAMETER ForceValid
Switch parameter, forces the signature to be valid -- otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate).
Aliases Valid
.RETURNVALUE
Boolean value representing whether the script's signature is valid, or YOUR certificate
##################################################################################################
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
# The signature to test.
$Signature
,
[Alias("Valid")]
[Switch]$ForceValid
)
return ( $Signature.Status -eq "Valid" -or
( !$ForceValid -and
($Signature.Status -eq "UnknownError") -and
($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint)
) )
}
####################################################################################################
function Set-AuthenticodeSignature {
<#.SYNOPSIS
Adds an Authenticode signature to a Windows PowerShell script or other file.
.DESCRIPTION
The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP).
In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed.
.NOTES
After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script.
When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>".
.EXAMPLE
ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate
To sign all of the files with the specified certificate
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate.
.INPUTTYPE
String. You can pipe a file path to Set-AuthenticodeSignature.
.PARAMETER FilePath
Specifies the path to a file that is being signed.
Aliases Path, FullName
.PARAMETER Certificate
Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate.
To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails.
.PARAMETER Force
Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.
.Parameter HashAlgorithm
Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm.
Files that are signed with a different hashing algorithm might not be recognized on other systems.
.PARAMETER IncludeChain
Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default.
Valid values are:
-- Signer: Includes only the signer's certificate.
-- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority.
--All: Includes all the certificates in the certificate chain.
.PARAMETER TimestampServer
Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string.
Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll
The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing.
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)]
[Alias("FullName","Path")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string[]]
$FilePath
,
[Parameter(Position=2, Mandatory=$false)]
$Certificate = $(Get-UserCertificate)
,
[Switch]$Force
,
[ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")]
[String]$HashAlgorithm #="SHA1"
,
[ValidateSet("Signer","NotRoot","All")]
[String]$IncludeChain #="NotRoot"
,
[String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll"
)
BEGIN {
if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$Certificate = Get-AuthenticodeCertificate $Certificate
}
$PSBoundParameters["Certificate"] = $Certificate
}
PROCESS {
Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)"
$PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath)
if(Test-Path $FilePath -Type Leaf) {
Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters
} else {
Write-Warning "Cannot sign folders: '$FilePath'"
}
}
}
####################################################################################################
function Get-AuthenticodeSignature {
<#.SYNOPSIS
Gets information about the Authenticode signature in a file.
.DESCRIPTION
The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank.
.NOTES
For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing".
When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>".
.EXAMPLE
Get-AuthenticodeSignature script.ps1
To get the signature information about the script.ps1 script file.
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature
Get the signature information for all the script and data files
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid.
.INPUTTYPE
String. You can pipe the path to a file to Get-AuthenticodeSignature.
.PARAMETER FilePath
The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional.
Aliases Path, FullName
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName","Path")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
if(!(Test-Path -PathType Leaf $_)) {
throw "Specified Path is not a File: '$_'"
}
return $true
})]
[string[]]
$FilePath
)
PROCESS {
Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath
}
}
####################################################################################################
function Select-AuthenticodeSigned {
<#.SYNOPSIS
Select files based on the status of their Authenticode Signature.
.DESCRIPTION
The Select-AuthenticodeSigned function filters files on the pipeline based on the state of their authenticode signature.
.NOTES
For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing".
When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>".
.EXAMPLE
ls *.ps1,*.ps[dm]1 | Select-AuthenticodeSigned
To get the signature information about the script.ps1 script file.
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature
Get the signature information for all the script and data files
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid.
.INPUTTYPE
String. You can pipe the path to a file to Get-AuthenticodeSignature.
.PARAMETER FilePath
The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional.
Aliases Path, FullName
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string[]]
$FilePath
,
[Parameter()]
# Return only files that are signed with the users' certificate (as returned by Get-UserCertificate).
[switch]$MineOnly
,
[Parameter()]
# Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate).
[switch]$NotMineOnly
,
[Parameter()]
[Alias("HashMismatch")]
# Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match).
[switch]$BrokenOnly
,
[Parameter()]
# Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate).
#
# That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly)
[switch]$TrustedOnly
,
[Parameter()]
# Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate.
[switch]$ValidOnly
,
[Parameter()]
# Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate).
[switch]$InvalidOnly
,
[Parameter()]
# Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed.
[switch]$UnsignedOnly
)
PROCESS {
if(!(Test-Path -PathType Leaf $FilePath)) {
# if($ErrorAction -ne "SilentlyContinue") {
# Write-Error "Specified Path is not a File: '$FilePath'"
# }
} else {
foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) {
# Broken only returns ONLY things which are HashMismatch
if($BrokenOnly -and $sig.Status -ne "HashMismatch")
{
Write-Debug "$($sig.Status) - Not Broken: $FilePath"
return
}
# Trusted only returns ONLY things which are Valid
if($ValidOnly -and $sig.Status -ne "Valid")
{
Write-Debug "$($sig.Status) - Not Trusted: $FilePath"
return
}
# AllValid returns only things that are SIGNED and not HashMismatch
if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) )
{
Write-Debug "$($sig.Status) - Not Valid: $FilePath"
return
}
# NOTValid returns only things that are SIGNED and Valid
if($InvalidOnly -and ($sig.Status -eq "Valid"))
{
Write-Debug "$($sig.Status) - Valid: $FilePath"
return
}
# Unsigned returns only things that aren't signed
# NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files??
if($UnsignedOnly -and $sig.SignerCertificate )
{
Write-Debug "$($sig.Status) - Signed: $FilePath"
return
}
# Mine returns only things that were signed by MY CertificateThumbprint
if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint))))
{
Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)"
Write-Debug " $FilePath"
return
}
# NotMine returns only things that were signed by MY CertificateThumbprint
if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint))))
{
if($sig.SignerCertificate) {
Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)"
Write-Debug " $FilePath"
}
return
}
if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) )
{
Write-Debug "$($sig.Status) - Not Signed: $FilePath"
return
}
get-childItem $sig.Path
}}
}
}
Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Export-ModuleMember -Alias gas,sas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUGC9Hxzt7IltBOFHwDqZdsid6
# yBSggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD
# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk
# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo
# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg
# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG
# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3
# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv
# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj
# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG
# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA
# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF
# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q
# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h
# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B
# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5
# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1
# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4
# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV
# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki
# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp
# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR
# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB
# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0
# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW
# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC
# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD
# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0
# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2
# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU
# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC
# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE
# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ
# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq
# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD
# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud
# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC
# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg
# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g
# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG
# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0
# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB
# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j
# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A
# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb
# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27
# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n
# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j
# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D
# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT
# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj
# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ
# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBS8GjyBUI2Q
# ToTKzbh1b32xYCH55jANBgkqhkiG9w0BAQEFAASCAQCOkFKmiRUIVVrwHXJPrlhH
# 5mahN+xXjcPYH135ABo/+T2Nx42eA6Ekl3NRoyo/NJp9w0y5s5bQmLUhwp926ff2
# LofOumK0qzcL8/dZ/mct3xJqqpX9O+WWCwFxFz4nj+X8R8OaQfMNBPgDL37a4ZEK
# 7U52The31AgUCpQByUlJDE4/bf5egTbMXl7T+CvojAffxyjAljHAiYsT9b/GSFHz
# nq8iwCskpM9K7Oy3PVAv0ieNR7KodovxNZZm5wkD914OZyGbCjqb08hNvXiSJcEj
# O6a2gAYQHL+ic0XFTO7WKQv5TxF9bN0faSz2d1lysDbhfD3349oKaUJd1OjOHoeT
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Update phone # in AD.ps1
|
Update phone # in AD.ps1
|
#------------------------------------------------------------------------------
# Strips off the '1-' prefix from phone numbers stored in Active Directory.
# Requires 'ActiveRoles Management Shell for Active Directory' from Quest
# Software.
#------------------------------------------------------------------------------
$data = @()
$users = Get-QADUser -sizelimit 0 `
| Where-Object { $_.PhoneNumber -like "1-*" } `
| Where-Object { $_.PhoneNumber.Length -eq 14 } `
| Sort-Object -Property Name
foreach ( $user in $users )
{
if ( $user -eq $null )
{
continue
}
$newPhoneNumber = $user.PhoneNumber.ToString()
$newPhoneNumber = $newPhoneNumber.Substring(2,12)
$dataLine = New-Object psObject
$dataLine | Add-Member -MemberType NoteProperty -Name "User" -Value $user.Name
$dataLine | Add-Member -MemberType NoteProperty -Name "OldPhone" -Value $user.PhoneNumber
$dataLine | Add-Member -MemberType NoteProperty -Name "NewPhone" -Value $newPhoneNumber
$dataLine | Add-Member -MemberType NoteProperty -Name "DN" -Value $user.DN
$data += $dataLine
Set-QADUser -Identity $user.DN -PhoneNumber $newPhoneNumber
}
if ( $data.Count -gt 0 )
{
$data | Out-GridView
}
|
PowerShellCorpus/PoshCode/Export-PSCredential_3.ps1
|
Export-PSCredential_3.ps1
|
# Author: Hal Rottenberg <hal@halr9000.com>
# Url: http://halr9000.com/article/tag/lib-authentication.ps1
# Purpose: These functions allow one to easily save network credentials to disk in a relatively
# secure manner. The resulting on-disk credential file can only [1] be decrypted
# by the same user account which performed the encryption. For more details, see
# the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as
# MSDN pages about Windows Data Protection API.
# [1]: So far as I know today. Next week I'm sure a script kiddie will break it.
#
# Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>]
#
# If Credential is not specififed, user is prompted by Get-Credential cmdlet.
# If not specififed, Path is "./credentials.enc.xml".
# Output: FileInfo object referring to saved credentials
#
# Import-PSCredential [-Path <file to import>]
#
# If not specififed, Path is "./credentials.enc.xml".
# Output: PSCredential object
function Export-PSCredential {
param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" )
#
switch ( $Credential.GetType().Name ) {
PSCredential { continue }
String { $Credential = Get-Credential -credential $Credential }
default { Throw "You must specify a credential object to export to disk." }
}
# Create temporary object to be serialized to disk
$export = "" | Select-Object Username, EncryptedPassword
# Give object a type name which can be identified later
$export.PSObject.TypeNames.Insert(0,’ExportedPSCredential’)
$export.Username = $Credential.Username
# Encrypt SecureString password using Data Protection API
# Only the current user account can decrypt this cipher
$export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
# Export using the Export-Clixml cmdlet
$export | Export-Clixml $Path
Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine
# Return FileInfo object referring to saved credentials
Get-Item $Path
}
function Import-PSCredential {
param ( $Path = "credentials.enc.xml" )
# Import credential file
$import = Import-Clixml $Path
# Test for valid import
if ( $import.PSObject.TypeNames -notcontains 'Deserialized.ExportedPSCredential' ) {
Throw "Input is not a valid ExportedPSCredential object, exiting."
}
$Username = $import.Username
# Decrypt the password and store as a SecureString object for safekeeping
$SecurePass = $import.EncryptedPassword | ConvertTo-SecureString
# Build the new credential object
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass
Write-Output $Credential
}
|
PowerShellCorpus/PoshCode/AddTo-HostsFile_2.ps1
|
AddTo-HostsFile_2.ps1
|
function AddTo-HostsFile{
<#
.DESCRIPTION
This function checks to see if an entry exists in the hosts file.
If it does not, it attempts to add it and verifies the entry.
.EXAMPLE
Networkign.AddTo-Hosts -IPAddress 192.168.0.1 -HostName MyMachine
.EXTERNALHELP
None.
.FORWARDHELPTARGETNAME
None.
.INPUTS
System.String.
.LINK
None.
.NOTES
None.
.OUTPUTS
System.String.
.PARAMETER IPAddress
A string representing an IP address.
.PARAMETER HostName
A string representing a host name.
.SYNOPSIS
Add entries to the hosts file.
#>
param(
[parameter(Mandatory=$true,position=0)]
[string]
$IPAddress,
[parameter(Mandatory=$true,position=1)]
[string]
$HostName
)
$HostsLocation = "$env:windir\\System32\\drivers\\etc\\hosts";
$NewHostEntry = "`t$IPAddress`t$HostName";
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Time-Stamp): The hosts file already contains the entry: $NewHostEntry. File not updated.";
}
else
{
Write-Host "$(Time-Stamp): The hosts file does not contain the entry: $NewHostEntry. Attempting to update.";
Add-Content -Path $HostsLocation -Value $NewHostEntry;
}
# Validate entry
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Time-Stamp): New entry, $NewHostEntry, added to $HostsLocation.";
}
else
{
Write-Host "$(Time-Stamp): The new entry, $NewHostEntry, was not added to $HostsLocation.";
}
}
|
PowerShellCorpus/PoshCode/d2585c36-111c-47e6-87c4-568d89c06c20.ps1
|
d2585c36-111c-47e6-87c4-568d89c06c20.ps1
|
hi
i want a script in powershell that talks to the sharepoint and takes two arguments one is Ip address or server name other is config.xml file.
It checks if server exists and if yes it asks for user name and password and display error to the user accordingly . also it checks for duplicate entries in config.xml file.
any suggesions will be highly appreciated.
|
PowerShellCorpus/PoshCode/Write-DataTable.ps1
|
Write-DataTable.ps1
|
#######################
<#
.SYNOPSIS
Writes data only to SQL Server tables.
.DESCRIPTION
Writes data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.
.INPUTS
None
You cannot pipe objects to Write-DataTable
.OUTPUTS
None
Produces no output
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"
Write-DataTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -Data $dt
This example loads a variable dt of type DataTable from query and write the datatable to another database
.NOTES
Write-DataTable uses the SqlBulkCopy class see links for additional information on this class.
Version History
v1.0 - Chad Miller - Initial release
.LINK
http://msdn.microsoft.com/en-us/library/30c3y597%28v=VS.90%29.aspx
#>
function Write-DataTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [string]$TableName,
[Parameter(Position=3, Mandatory=$true)] $Data,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000,
[Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0,
[Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15
)
$conn=new-object System.Data.SqlClient.SQLConnection
if ($Username)
{ $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
else
{ $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout }
$conn.ConnectionString=$ConnectionString
try
{
$conn.Open()
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = $tableName
$bulkCopy.BatchSize = $BatchSize
$bulkCopy.BulkCopyTimeout = $QueryTimeOut
$bulkCopy.WriteToServer($Data)
$conn.Close()
}
catch
{
$ex = $_.Exception
Write-Error "Write-DataTable $($connectionName):$ex.Message"
continue
}
} #Write-DataTable
|
PowerShellCorpus/PoshCode/b4865a35-f8b9-4235-90a9-91f1b81e8dc1.ps1
|
b4865a35-f8b9-4235-90a9-91f1b81e8dc1.ps1
|
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null
@@#NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired
@@# to something that more suits your reality.
$crawlFreshnessDayThreshhold = 2
$crawlDurationHourThreshhold = 4
$successRatioThreshhold = 0.9
function Calculate-CrawlDuration(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource)
{
if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) {
return "Green - no current crawl"
}
$timespan = [datetime]::Now - $contentSource.CrawlStarted
$timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days" +
"($($timespan.TotalHours.ToString('0.0')) hours)"
if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) {
return "Green - $timespanFormatted"
} elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) {
return "Yellow - $timespanFormatted"
} else {
return "Red - $timespanFormatted"
}
}
function Calculate-CrawlFreshness(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource)
{
$timespan = [datetime]::Now - $contentSource.CrawlCompleted
$timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago"
if ($timespan.Days -le 0) {
return "Green - $timespanFormatted"
} elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) {
return "Yellow - $timespanFormatted"
} else {
return "Red - $timespanFormatted"
}
}
function Calculate-IndexHealth(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource,
$successCount, $warningCount, $errorCount)
{
$formatted = "($($successCount)/$($warningCount)/$($errorCount))"
if ($errorCount -eq 1) {
return "Red - exactly 1 error, usually indicates permissions/config error - $formatted"
}
$successRatio = ([double]$successCount)/([double]($warningCount + $errorCount))
$successRatioMidpointToPerfection = (1.0 - ((1.0 - $successRatioThreshhold)/2.0))
if ($successRatio -ge $successRatioMidpointToPerfection) {
return "Green - $formatted"
} elseif ($successRatio -ge $successRatioThreshhold) {
return "Yellow - $formatted"
} else {
return "Red - $formatted"
}
}
function Get-CrawlHealth
{
$serverContext = [Microsoft.Office.Server.ServerContext]::Default
$searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext)
$content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext
$history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext
$contentSources = $content.ContentSources | foreach { $_ }
$contentSources | foreach {
#unroll DataTable object into more useful DataRow object
$crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ }
add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value (
Calculate-CrawlDuration $_)
add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value (
Calculate-CrawlFreshness $_)
add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value (
Calculate-IndexHealth -contentSource $_ -successCount $crawlHistory.SuccessCount -warningCount (
$crawlHistory.WarningCount) -errorCount $crawlHistory.ErrorCount)
}
$contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth | fl
}
@@#USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials
@@# (specifically, with access to the SSP - usually the SharePoint farm account)
@@# -Tweak the threshholds (they may be too ambitious for your environment)
@@# -Paste this text into an open PowerShell window and type (without the # mark)
# Get-CrawlHealth
|
PowerShellCorpus/PoshCode/ESX host NTP Settings_1.ps1
|
ESX host NTP Settings_1.ps1
|
<#======================================================================================
File Name : ESX-NTP.ps1
Original Author : Kenneth C. Mazie
:
Description : This is a VMware PowerCLI script for synchronizing NTP settings across
: all ESX hosts in a Virtual Center instance. It grabs all ESX hosts and
: cycles through them setting the same NTP settings on each. It then
: starts the service and sets it to start automatically.
:
: The individual commands were found on a blog post from Anders Mikkelson.
: I simply combined them into a functioning script so credit goes to him.
: See http://www.amikkelsen.com/?p=458 for the original posting.
:
: Tested on ESXi 5.1 and 5.0
:
: Be sure to edit all sections to suit your needs before executing.
:
: As written the script will prompt for a Virtual Center instance to process
: and a user/password to connect as. It also prompts for the ESX host user ID.
: Hard code these if the prompts become annoying.
:
Notes : Requires VMware PowerShell PowerCLI extentions.
:
Warnings :
:
:
Last Update by : Kenneth C. Mazie (kcmjr AT kcmjr.com to report issues)
Version History : v1.0 - 03-13-12 - Original
Change History : v1.1 - 03-13-12 - Corrected 2 typos
:
=======================================================================================#>
clear-host
$out = Get-PSSnapin | Where-Object {$_.Name -like "vmware.vimautomation.core"};if ($out -eq $null) {Add-PSSnapin vmware.vimautomation.core}
$vSphere = read-host "Process Which vSphere Instance?"
$vUser = read-host "vSphere User ID?"
$vPass = ""
$eUser = read-host "ESX User ID?"
$ePass = "password"
$NTPServers = ("time.nist.gov","time-nw.nist.gov","us.pool.ntp.org") #--[ Change these to whatever NTP servers you use ]--
if ($vSphere -eq $null){break}
Disconnect-VIServer -confirm:$false
Connect-VIServer -Server $vSphere -User $vUser #-Password $vPass
$ESXhosts = get-vmhost
foreach ($ESX in $ESXHosts)
{
Write-Host "Target = $ESX"
Connect-VIServer -Server $ESX -User $eUser #-Password $ePass
$NTPList = Get-VMHostNtpServer -VMHost $ESX
Remove-VMHostNtpServer -VMHost $ESX -NtpServer $NTPList -Confirm:$false
Add-VMHostNtpServer -VMHost $ESX -NtpServer $NTPServers -Confirm:$false
Set-VMHostService -HostService (Get-VMHostservice -VMHost (Get-VMHost $ESXhost) | Where-Object {$_.key -eq "ntpd"}) -Policy "Automatic"
Get-VmhostFirewallException -VMHost $ESX -Name "NTP Client" | Set-VMHostFirewallException -enabled:$true
$ntpd = Get-VMHostService -VMHost $ESX | where {$_.Key -eq 'ntpd'}
Restart-VMHostService $ntpd -Confirm:$false
Disconnect-viserver -server $ESX -confirm:$false
}
Write-Host "--- COMPLETED ---"
|
PowerShellCorpus/PoshCode/Feeds Module.ps1
|
Feeds Module.ps1
|
#Requires -Version 2.0
DATA loc {
# en-US
convertfrom-stringdata @'
RootName = (Root)
FolderCaption = Folder: {0}
FeedCaption = Feed: {0}
MarkReadStatus = Marking all items read
DownloadStatus = Downloading all items
AsyncDownloadStatus = Beginning download of all items
'@
}
# Import localized data (default is en-US above).
import-localizeddata -bindingVariable loc -errorAction SilentlyContinue
filter Recurse-Feeds { $_.Subfolders | Recurse-Feeds; $_.Feeds }
filter Recurse-Folders { $_.Subfolders | Recurse-Folders; $_ }
# Filter to write progress based on the number of feed items
filter Write-FeedProgress
{
param(
[scriptblock] $Script = $(throw "`$Script required."),
[string] $Activity = $(throw "`$Activity required."),
[MarshalByRefObject] $Folder = $(throw "`$Folder required."),
[switch] $WithProgress
)
begin
{
$total = $Folder.TotalItemCount
$count = 0
}
process
{
try
{
& $Script
}
finally
{
# Always report progress
if ($WithProgress)
{
$count += $_.ItemCount;
$percent = $count / $total * 100
$path = $_.Parent.Path
if ($path -eq "") { $path = $loc.RootName }
write-progress -activity $activity -status ($loc.FolderCaption -f $path) `
-current ($loc.FeedCaption -f $_.Name) -percent $percent
}
}
}
}
# Mark all feed items as read
function MarkRead-Feeds
{
<#
.Synopsis
Marks all feeds in the root or given folder as read.
.Description
Marks all the feeds in Internet Explorer 7.0 or newer as read. If no folder
is provided then this marks all feeds under the root folder.
.Parameter Folder
The name of the folder under which all items are marked read.
.Parameter WithProgress
Show a progress bar and activity details.
.Example
markread-feeds "Microsoft Feeds" -withprogress
Marks all items as read under "Microsoft Feeds" with progress.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string] $Folder = $null,
[Parameter()]
[switch] $WithProgress
)
$rss = new-object -com Microsoft.FeedsManager
$root = $rss.GetFolder($Folder)
$root | recurse-feeds | write-feedprogress -script { $_.MarkAllItemsRead() } `
-activity $loc.MarkReadStatus -folder $root -withprogress:$WithProgress
}
# Download all new feed items
function Download-Feeds
{
<#
.Synopsis
Downloads (synchronizes) all feeds in the root or given folder.
.Description
Forces the synchronization of all feeds in Internet Explorer 7.0 or newer.
If no folder is provided then this downloads all feeds under the root
folder.
.Parameter Folder
The name of the folder under which all items are marked read.
.Parameter Asynchronous
Return immediately and download all items in a separate thread.
.Parameter WithProgress
Show a progress bar and activity details.
.Example
download-feeds "Microsoft Feeds" -withprogress
Downloads all items under the "Microsoft Feeds" folder with progress.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string] $Folder = $null,
[Parameter()]
[switch] $Asynchronous,
[Parameter()]
[switch] $WithProgress
)
if ($Asynchronous)
{
$activity = $loc.AsyncDownloadStatus
$script = { $_.AsyncDownload() }
}
else
{
$activity = $loc.DownloadStatus
$script = { $_.Download() }
}
$rss = new-object -com Microsoft.FeedsManager
$root = $rss.GetFolder($Folder)
$root | recurse-feeds | write-feedprogress -script $script `
-activity $activity -folder $root -withprogress:$WithProgress
}
# Export everything for use into the current session.
export-modulemember -function "markread-feeds", "download-feeds"
|
PowerShellCorpus/PoshCode/Convert-BounceToX_2.ps1
|
Convert-BounceToX_2.ps1
|
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $
# $Revision: 610 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
#.Example
# "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress
)
BEGIN
{
Add-Type -AssemblyName System.Web|Out-Null
}
PROCESS
{
if($_) {$bounceAddress = $_}
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
}
|
PowerShellCorpus/PoshCode/SharpSSH Module_1.ps1
|
SharpSSH Module_1.ps1
|
##################################################
# cmdlets
##################################################
#-------------------------------------------------
# New-SharpSession
#-------------------------------------------------
# Usage: New-SharpSession -?
#-------------------------------------------------
function New-SharpSession {
<#
.Synopsis
Used to open an SSH or SCP Session to the specified server.
.Description
Uses SharpSSH to open an SSH or SCP Session to the specified server.
.Parameter Host
The hostname or IP address that you want to connect to.
.Parameter UserName
The username string used for the connection.
.Parameter Key
The switch that tells function to execute with key parameters.
.Parameter KeyFile
The path and file name to the key file used for key based
authentication.
.Parameter User
The switch that tells function to execute with user parameters.
.Parameter Password
The password string used for the connection.
#>
[CmdletBinding(DefaultParameterSetName="KeySet")]
param(
[Parameter(Mandatory=$True)][String]$Host,
[Parameter(Mandatory=$True)][String]$UserName,
[Parameter(ParameterSetName="KeySet")][Switch]$Key,
[Parameter(ParameterSetName="KeySet", Mandatory=$True)][String]$KeyFile,
[Parameter(ParameterSetName="User")][Switch]$User,
[Parameter(ParameterSetName="User", Mandatory=$True)][String]$Password,
[Switch]$SCP,
[Switch]$PassThru
)
try {
# Default will always be to do SSH...
if ($SCP){
$ConnectType = "Tamir.SharpSsh.scp"
}
else{
$ConnectType = "Tamir.SharpSsh.SshShell"
}
if ($Key -and (Test-Path $KeyFile)){
$Global:SharpSession = New-Object $ConnectType $Host, $UserName
$Global:SharpSession.AddIdentityFile((Resolve-Path $KeyFile))
}
else{
$Global:SharpSession = New-Object $ConnectType $Host, $UserName, $Password
}
$Global:SharpSession.Connect()
if ($ConnectType -eq "Tamir.SharpSsh.SshShell"){
$Global:SharpSession.RemoveTerminalEmulationCharacters = $True
}
if($PassThru){
return $Global:SharpSession
}
}
catch {
throw $_
}
}
#-------------------------------------------------
# Transfer-SharpFile
#-------------------------------------------------
# Usage: Transfer-SharpFile -?
#-------------------------------------------------
function Transfer-SharpFile {
<#
.Synopsis
Used to tranfser(get or put) a file using a valid SCP SharpSession.
.Description
Uses SharpSSH to tranfer (get or put) a file via SCP.
.Parameter From
The full path and file name to the file you are transferring.
.Parameter To
The full path and file name to where you want to copy the file to.
#>
param(
[Parameter(Mandatory=$True)][String]$From,
[Parameter(Mandatory=$True)][String]$To,
[Switch]$Get,
[Switch]$Put
)
try {
if (!($Get -or $Put)) {
throw Write-Host "Get or Put must be defined!" -ForeGroundColor Red
}
if ($SharpSession.GetType().Fullname -ne "Tamir.SharpSsh.Scp"){
throw Write-Host "Not currently connected using SCP!" -ForeGroundColor Red
}
else{
# The action scriptblock for an EventObject must have
# things defined in the Global scope. Yuck!
$Global:SharpSessiontransferDone = $Null
$Global:SharpSessiontotalBytes = $Null
$Global:SharpSessiontransferredBytes = $Null
[void] (Register-ObjectEvent -InputObject $SharpSession -EventName OnTransferProgress -SourceIdentifier Scp.OnTransferProgress `
-Action {$Global:SharpSessiontotalBytes = $args[3]; $Global:SharpSessiontransferredBytes = $args[2]})
[void] (Register-ObjectEvent -InputObject $SharpSession -EventName OnTransferEnd -SourceIdentifier Scp.OnTransferEnd `
-Action {$Global:SharpSessiontransferDone = $True})
# Default is always to get.
if ($Get){
$SharpSession.Get($From, $To)
try{
do {Write-Progress -Activity "Get - $($From)" -Status "Copying" `
-PercentComplete (($SharpSessiontransferredBytes/$SharpSessiontotalBytes)*100)} while ($SharpSessiontransferDone -eq $Null)
}
catch{
Write-Warning "File is not there..."
}
}
else{
$SharpSession.Put($From, $To)
try{
do {Write-Progress -Activity "Get - $($From)" -Status "Copying" `
-PercentComplete (($SharpSessiontransferredBytes/$SharpSessiontotalBytes)*100)} while ($SharpSessiontransferDone -eq $Null)
}
catch{
Write-Warning "File is not there..."
}
}
}
}
catch {
throw $_
}
finally {
if (Get-EventSubscriber -SourceIdentifier Scp.OnTransferProgress){
[void] (Unregister-Event -SourceIdentifier Scp.OnTransferProgress)
}
if (Get-EventSubscriber -SourceIdentifier Scp.OnTransferEnd){
[void] (Unregister-Event -SourceIdentifier Scp.OnTransferEnd)
}
}
}
#-------------------------------------------------
# Remove-SharpSession
#-------------------------------------------------
# Usage: Remove-SharpSession -?
#-------------------------------------------------
function Remove-SharpSession {
<#
.Synopsis
Used to close an active SSH or SCP Session.
.Description
Uses SharpSSH to close an active SSH or SCP Session.
#>
try {
if($SharpSession){
if ($SharpSession.GetType().Fullname -eq "Tamir.SharpSsh.SshShell"){
$SharpSession.WriteLine("exit")
sleep -milli 500
if($SharpSession.ShellOpened) {
Write-Warning "Shell didn't exit cleanly, closing anyway."
}
$SharpSession.Close()
}
else{
$SharpSession.Close()
}
}
else{
throw "There is no session to remove!"
}
}
catch {
throw $_
}
finally {
$Global:SharpSession = $Null
}
}
##################################################
# Main
##################################################
Export-ModuleMember New-SharpSession
Export-ModuleMember Transfer-SharpFile
Export-ModuleMember Remove-SharpSession
|
PowerShellCorpus/PoshCode/Set-ADUserRandomPassword_1.ps1
|
Set-ADUserRandomPassword_1.ps1
|
###########################################################################"
#
# NAME: Set-ADUserRandomPassword.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: This script are used to set a random password for the Active Directory user with the username provided by the user who runs the script.
# The password are set to a random password, and "User must change password at next logon" are enabled.
# At last the displayname,username,company-name,department-name and the new password are displayed.
# Script logic to check if the provided username exist are added.
#
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 29.09.2009 - Initial release
#
###########################################################################"
#requires -pssnapin Quest.ActiveRoles.ADManagement
#Creating system.random object used to generate random numbers
$random = New-Object System.Random
#Set searchroot
$searchroot = "domain.local/Example-OU"
#Get username for the user to reset password for
$username = Read-Host "Enter username for the user you want to change password for:"
$userobject = Get-QADUser $username -SearchRoot $searchroot
if ($userobject -ne $null) {
#User exist, continue
}
else
{
#User does not exist, ask user to enter username again
do { $username = Read-Host "There are no users with the username $username. Re-enter username.";$userobject = Get-QADUser $username -SearchRoot $searchroot } until ($userobject -ne $null)
$userobject = Get-QADUser $username -SearchRoot $searchroot
}
#Generate a random password for each user
$password = "Pwd"+($random.Next(1000,9999))
#Set the password for each user
Set-QADUser $userobject -UserPassword $password -UserMustChangePassword $true | Out-Null
#Select what user information we want to export to the csv-file and storing it in a variable
$userdata = Get-QADUser $userobject | Select-Object @{Name="Name"; Expression = {$_.displayname}},@{Name="Username"; Expression = {$_.samaccountname}},@{Name="Company-name"; Expression = {$_.company}},@{Name="Department-name"; Expression = {$_.department}}
#Add the password as a member to $userdata
Add-Member -InputObject $userdata -MemberType NoteProperty -Name "New password" -Value $password -Force
#Feedback
Write-Host "The password-change was successfully for the following user:"
$userdata
Write-Host "Note: The user must change the password on the next logon."
|
PowerShellCorpus/PoshCode/Start-Demo 3.3.3.ps1
|
Start-Demo 3.3.3.ps1
|
## Start-Demo.ps1
##################################################################################################
## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett
##
## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time)
## As a result, I've changed the names and keys for a lot of the operations, so that they make
## sense with only a single letter to tell them apart (sorry if you had them memorized).
##
## I've also been adding features as I come across needs for them, and you'll contribute your
## improvements back to the PowerShell Script repository as well.
##################################################################################################
## Revision History (version 3.3)
## 3.3.3 Fixed: Script no longer says "unrecognized key" when you hit shift or ctrl, etc.
## Fixed: Blank lines in script were showing as errors (now printed like comments)
## 3.3.2 Fixed: Changed the "x" to match the "a" in the help text
## 3.3.1 Fixed: Added a missing bracket in the script
## 3.3 - Added: Added a "Clear Screen" option
## - Added: Added a "Rewind" function (which I'm not using much)
## 3.2 - Fixed: Put back the trap { continue; }
## 3.1 - Fixed: No Output when invoking Get-Member (and other cmdlets like it???)
## 3.0 - Fixed: Commands which set a variable, like: $files = ls
## - Fixed: Default action doesn't continue
## - Changed: Use ReadKey instead of ReadLine
## - Changed: Modified the option prompts (sorry if you had them memorized)
## - Changed: Various time and duration strings have better formatting
## - Enhance: Colors are settable: prompt, command, comment
## - Added: NoPauseAfterExecute switch removes the extra pause
## If you set this, the next command will be displayed immediately
## - Added: Auto Execute mode (FullAuto switch) runs the rest of the script
## at an automatic speed set by the AutoSpeed parameter (or manually)
## - Added: Automatically append an empty line to the end of the demo script
## so you have a chance to "go back" after the last line of you demo
##################################################################################################
##
param(
$file=".\\demo.txt",
[int]$command=0,
[System.ConsoleColor]$promptColor="Yellow",
[System.ConsoleColor]$commandColor="White",
[System.ConsoleColor]$commentColor="Green",
[switch]$FullAuto,
[int]$AutoSpeed = 3,
[switch]$NoPauseAfterExecute
)
$RawUI = $Host.UI.RawUI
$hostWidth = $RawUI.BufferSize.Width
# A function for reading in a character
function Read-Char() {
$_OldColor = $RawUI.ForeGroundColor
$RawUI.ForeGroundColor = "Red"
$inChar=$RawUI.ReadKey("IncludeKeyUp")
# loop until they press a character, so Shift or Ctrl, etc don't terminate us
while($inChar.Character -eq 0){
$inChar=$RawUI.ReadKey("IncludeKeyUp")
}
$RawUI.ForeGroundColor = $_OldColor
return $inChar.Character
}
function Rewind($lines, $index, $steps = 1) {
$started = $index;
$index -= $steps;
while(($index -ge 0) -and ($lines[$index].Trim(" `t").StartsWith("#"))){
$index--
}
if( $index -lt 0 ) { $index = $started }
return $index
}
$file = Resolve-Path $file
while(-not(Test-Path $file)) {
$file = Read-Host "Please enter the path of your demo script (Crtl+C to cancel)"
$file = Resolve-Path $file
}
Clear-Host
$_lines = Get-Content $file
# Append an extra (do nothing) line on the end so we can still go back after the last line.
$_lines += "Write-Host 'The End'"
$_starttime = [DateTime]::now
$FullAuto = $false
Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
Write-Host -nonew -back black -fore $promptColor @"
<Demo Started :: $(split-path $file -leaf)>$(' ' * ($hostWidth -(18 + $(split-path $file -leaf).Length)))
"@
Write-Host -nonew -back black -fore $promptColor "Press"
Write-Host -nonew -back black -fore Red " ? "
Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth -17))"
Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
# We use a FOR and an INDEX ($_i) instead of a FOREACH because
# it is possible to start at a different location and/or jump
# around in the order.
for ($_i = $Command; $_i -lt $_lines.count; $_i++)
{
# Put the current command in the Window Title along with the demo duration
$Dur = [DateTime]::Now - $_StartTime
$RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i])
# Echo out the commmand to the console with a prompt as though it were real
Write-Host -nonew -fore $promptColor "[$_i]$([char]0x2265) "
if ($_lines[$_i].Trim(" ").StartsWith("#") -or $_lines[$_i].Trim(" ").Length -le 0) {
Write-Host -fore $commentColor "$($_Lines[$_i]) "
continue
} else {
Write-Host -nonew -fore $commandColor "$($_Lines[$_i]) "
}
if( $FullAuto ) { Start-Sleep $autoSpeed; $ch = [char]13 } else { $ch = Read-Char }
switch($ch)
{
"?" {
Write-Host -Fore $promptColor @"
Running demo: $file
(n) Next (p) Previous
(q) Quit (s) Suspend
(t) Timecheck (v) View $(split-path $file -leaf)
(g) Go to line by number
(f) Find lines by string
(a) Auto Execute mode
(c) Clear Screen
"@
$_i-- # back a line, we're gonna step forward when we loop
}
"n" { # Next (do nothing)
Write-Host -Fore $promptColor "<Skipping Line>"
}
"p" { # Previous
Write-Host -Fore $promptColor "<Back one Line>"
while ($_lines[--$_i].Trim(" ").StartsWith("#")){}
$_i-- # back a line, we're gonna step forward when we loop
}
"a" { # EXECUTE (Go Faster)
$AutoSpeed = [int](Read-Host "Pause (seconds)")
$FullAuto = $true;
Write-Host -Fore $promptColor "<eXecute Remaining Lines>"
$_i-- # Repeat this line, and then just blow through the rest
}
"q" { # Quit
Write-Host -Fore $promptColor "<Quiting demo>"
$_i = $_lines.count;
break;
}
"v" { # View Source
$lines[0..($_i-1)] | Write-Host -Fore Yellow
$lines[$_i] | Write-Host -Fore Green
$lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow
$_i-- # back a line, we're gonna step forward when we loop
}
"t" { # Time Check
$dur = [DateTime]::Now - $_StartTime
Write-Host -Fore $promptColor $(
"{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString()))
$_i-- # back a line, we're gonna step forward when we loop
}
"s" { # Suspend (Enter Nested Prompt)
Write-Host -Fore $promptColor "<Suspending demo - type 'Exit' to resume>"
$Host.EnterNestedPrompt()
$_i-- # back a line, we're gonna step forward when we loop
}
"g" { # GoTo Line Number
$i = [int](Read-Host "line number")
if($i -le $_lines.Count) {
if($i -gt 0) {
# extra line back because we're gonna step forward when we loop
$_i = Rewind $_lines $_i (($_i-$i)+1)
} else {
$_i = -1 # Start negative, because we step forward when we loop
}
}
}
"f" { # Find by pattern
$match = $_lines | Select-String (Read-Host "search string")
if($match -eq $null) {
Write-Host -Fore Red "Can't find a matching line"
} else {
$match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) }
if($match.Count -lt 1) {
$_i = $match.lineNumber - 2 # back a line, we're gonna step forward when we loop
} else {
$_i-- # back a line, we're gonna step forward when we loop
}
}
}
"c" {
Clear-Host
$_i-- # back a line, we're gonna step forward when we loop
}
"$([char]13)" { # on enter
Write-Host
trap [System.Exception] {Write-Error $_; continue;}
Invoke-Expression ($_lines[$_i]) | out-default
if(-not $NoPauseAfterExecute -and -not $FullAuto) {
$null = $RawUI.ReadKey("NoEcho,IncludeKeyUp") # Pause after output for no apparent reason... ;)
}
}
default
{
Write-Host -Fore Green "`nKey not recognized. Press ? for help, or ENTER to execute the command."
$_i-- # back a line, we're gonna step forward when we loop
}
}
}
$dur = [DateTime]::Now - $_StartTime
Write-Host -Fore $promptColor $(
"<Demo Complete -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s>" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString())
Write-Host -Fore $promptColor $([DateTime]::now)
Write-Host
# SIG # Begin signature block
# MIIIPgYJKoZIhvcNAQcCoIIILzCCCCsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUhnYBsMQ+7cZlmxCQp6UPJj6A
# u0GgggVbMIIFVzCCBD+gAwIBAgIRAO2rPg5HUjL4ofGGpnMP2jwwDQYJKoZIhvcN
# AQEFBQAwgZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2Fs
# dCBMYWtlIENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8G
# A1UECxMYaHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNF
# UkZpcnN0LU9iamVjdDAeFw0wODEwMDYwMDAwMDBaFw0wOTEwMDYyMzU5NTlaMIHE
# MQswCQYDVQQGEwJVUzEOMAwGA1UEEQwFMTQ2MjMxETAPBgNVBAgMCE5ldyBZb3Jr
# MRIwEAYDVQQHDAlSb2NoZXN0ZXIxFDASBgNVBAkMC01TIDA4MDEtMTdBMRowGAYD
# VQQJDBExMzUwIEplZmZlcnNvbiBSZDEaMBgGA1UECgwRWGVyb3ggQ29ycG9yYXRp
# b24xFDASBgNVBAsMC1NFRURVIFRvb2xzMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK50RXT2KUvECfWZ
# weqeXzTCykPPRh9nC3Hzur/mmvkQHA8iinnSKX4j19C1/MV0rAEeCU1bF7Sgxvov
# ORreM1Ye/wEqJLAUP/IGZI/qsmmwasGFGbnuevpA3WieNCr5cFGl8Y5Mx6ejaDFi
# O0GT9EM6gOGZaEEMRbHZc4qXT7CrWScs4Yur5bBZsowaMk5JkvZgihhnN93QolEW
# ObmtQZlbBDqLuoL9fUnIexlqqIrC/4h0K8VM26HvqhgGlQF2wf4t9xCHFJiX2F7D
# B10lef5aXzyPVrvxxrRWyBtCQuL7xdXneRanJaYG3B3kclc+4/6dq9a+s/huXjmE
# omumgGcCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBT5ITlG5CdiD+nI0uTqnXNGnd44QjAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAZxnV+BbJBohpy+wKs6U8hRiPUhDYaijzTyrZontf5
# PEyBbhAkJFIWauIaq9eSQEJeErXO/zuO6+wY/azBzOTleMM9qdGWHFtfAw5WiIuC
# 90TzDBSuP7LImZV5Pb6nxRbesDF2U7EM5sBzYSWAMfpBmYRz97EHPW5QNzpBLFJn
# Dhb/M27rDYh7FVjy1+C5E3glIa0A0q+lcxEtFuUij4JId+oMcfpSgYJZvR1Kvkjd
# GDAtWCzvALaNFd65kChbrOqcClOCacQRnP9N4DJl/RVNKZtcUcVAyTpvOlJBA5vG
# OVcsJT4TnSMjPX6d5pXMwcE1oWCUWvK99W+N81DvBBuZMYICTTCCAkkCAQEwgasw
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIRAO2rPg5HUjL4ofGGpnMP2jwwCQYFKw4DAhoFAKB4MBgGCisGAQQB
# gjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYK
# KwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFNEM/yDz
# vLFTxZZERqngy81y1rFyMA0GCSqGSIb3DQEBAQUABIIBAIi+6WT4dPUfVZyJ1Efd
# DzTqYmH2wmcGg8KncjeA2vi+F3+9EPDIMRUSNxDO+l/iAel4uiNE3CNlZDiCfi4v
# W+nc1TTpen1q33ITFLgFaUvMztgJ1D02NsEIAsGX0Qu9FHYXXGkdx6HiTyy5lfl2
# sLvmQiINVfHJnn28YhSqpEByebojR6177/VhDqk7h9vvhMhuBP+XWlzO+nwaZ84T
# BcS8Qb/JkKxkhKYhbsfViQX0Rq4/5MjhjR7ctEJvCfkb0dkY97sHddg4kWGy5amI
# ydV6EoqjHHUJatdgmCc38KIQVdXvaZyC5rTRg/uEJias4BQq3HLdUQDJ+u5l0EeY
# MbI=
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Xml Module _1.6.ps1
|
Xml Module _1.6.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
# Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
# Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
# Version 4.3 Added a Path parameter set to Format-XML so you can specify xml files for prety printing
# Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
# Work around possible variable slipping on null values by:
# 1) allowing -param:$value syntax (which doesn't fail when $value is null)
# 2) testing for -name syntax on the value and using it as an attribute instead
# Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
# Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
# Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
if(!$xlr8r::Get["Stack"]) {
$xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["Dictionary"]) {
$xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
filter Format-XML {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Path
# The path to an xml document (on disc or any other content provider).
#.Parameter Indent
# The indent level (defaults to 2 spaces)
#.Example
# [xml]$xml = get-content Data.xml
# C:\\PS>Format-Xml $xml
#.Example
# get-content Data.xml | Format-Xml
#.Example
# Format-Xml C:\\PS\\Data.xml
#.Example
# ls *.xml | Format-Xml
#
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
[xml]$Xml
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PsPath")]
[string]$Path
,
[Parameter(Mandatory=$false)]
$Indent=2
)
## Load from file, if necessary
if($Path) { [xml]$xml = Get-Content $Path }
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}
Set-Alias fxml Format-Xml -EA 0
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter XPath
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
#.Parameter RemoveNamespace
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Hashtable]$Namespace
,
[Switch]$RemoveNamespace
)
BEGIN {
function Select-Node {
PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager)
BEGIN {
foreach($node in $xml) {
if($NamespaceManager -is [Hashtable]) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Namespace.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
}
foreach($path in $xpath) {
$node.SelectNodes($path, $nsManager)
} } } }
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
$node = Remove-XmlNamespace $node
}
Select-Node $node $XPath $NSM
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
}
Set-Alias slxml Select-Xml -EA 0
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
,
[Parameter(Position=2,Mandatory=$false)]
[Alias("Parameters")]
[hashtable]$Arguments
)
PROCESS {
$output = New-Object IO.StringWriter
$argList = $null
if($Arguments) {
$argList = New-Object System.Xml.Xsl.XsltArgumentList
foreach($arg in $Arguments.GetEnumerator()) {
$namespace, $name = $arg.Key -split ":"
## Fix namespace
if(!$name) {
$name = $Namespace
$namespace = ""
}
Write-Verbose "ns:$namespace name:$name value:$($arg.Value)"
$argList.AddParam($name,"$namespace",$arg.Value)
}
}
$StyleSheet.Transform( $XmlReader, $argList, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
,
[Alias("Parameters")]
[hashtable]$Arguments
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
$OFS = "`n"
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader "$Xslt" )) ))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet $Arguments
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet $Arguments
}
}
}
Set-Alias cvxml Convert-Xml -EA 0
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
Convert-Node -Xml $Xml $StyleSheet
}
}
"Xml" {
$Xml | Convert-Node $StyleSheet
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias rmns Remove-XmlNamespace -EA 0
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [string]$xml = New-XDocument rss -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# C:\\PS>$xml.ToString()
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#
# Description
# -----------
# This example shows the creation of a complete RSS feed with a single item in it.
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.
#
#
#.Example
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
# Description
# -----------
# This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString().
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.#
#
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
# Write-Verbose "Preparsed DSL: $attrib"
$attrib = ConvertFrom-XmlDsl $attrib
Write-Verbose "Reparsed DSL: $attrib"
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) {
$value = ConvertFrom-XmlDsl $value
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} else {
Write-Verbose "XAttribute $attrib = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
))
}
}
Set-Alias xml New-XDocument -EA 0
Set-Alias New-Xml New-XDocument -EA 0
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute -EA 0
Set-Alias New-XmlAttribute New-XAttribute -EA 0
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
# BEGIN {
# if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
# $tag = $($script:NameSpaceStack.Peek()) + $tag
# if( $script:NameSpaceStack.Count -gt 0 ) {
# $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() )
# } else {
# $script:NameSpaceStack.Push( $null )
# }
# } else {
# $script:NameSpaceStack.Push( $tag.Namespace )
# }
# }
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} elseif($value -match "-(?!\\d)\\w") {
$args = @($value)+@($args)
} elseif($value -ne $null) {
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
)
}
# END {
# $null = $script:NameSpaceStack.Pop()
# }
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function ConvertFrom-XmlDsl {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) }
[Array]::Reverse( $duds )
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
######## CliXml
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [type]::gettype("System.Management.Automation.Deserializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
$sr = new-object System.IO.StringReader $xmlString
$xr = new-object System.Xml.XmlTextReader $sr
$deserializer = $ctor.invoke($xr)
$method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
while (!$done.invoke($deserializer, @()))
{
try {
$method.invoke($deserializer, "")
} catch {
write-warning "Could not deserialize $string: $_"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [type]::gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null)
$sw = new-object System.IO.StringWriter
$xw = new-object System.Xml.XmlTextWriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
}
process {
try {
[void]$method.invoke($serializer, $InputObject)
} catch {
write-warning "Could not serialize $($InputObject.gettype()): $_"
}
}
end {
[void]$done.invoke($serializer, @())
$sw.ToString()
$xw.Close()
$sw.Dispose()
}
}
######## Xaml
# if($PSVersionTable.CLRVersion -ge "4.0"){
# trap { continue }
# [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null
# if("System.Xaml.XamlServices" -as [type]) {
# }
# }
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUzDxrTxXwmegpPJOFVeVSMySS
# Qeyggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD
# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk
# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo
# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg
# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG
# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3
# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv
# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj
# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG
# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA
# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF
# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q
# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h
# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B
# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5
# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1
# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4
# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV
# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki
# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp
# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR
# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB
# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0
# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW
# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC
# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD
# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0
# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2
# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU
# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC
# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE
# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ
# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq
# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD
# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud
# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC
# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg
# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g
# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG
# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0
# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB
# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j
# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A
# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb
# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27
# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n
# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j
# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D
# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT
# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj
# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ
# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBQYoPjaFo3a
# OrUH23e74FM2yGbeQjANBgkqhkiG9w0BAQEFAASCAQAEoEa/WFrgcCGJyTXYDJn7
# TCOFYqAoNNg+dy4mtYXlzuf7v/VBDHhaoeFx4WLhONzsLGFabdfsEPZrS0FgDXX9
# QuFHhumigd1e9cLtNsjyJiPXEHO3s2U/ISnj+qFrZ9Q2CN1vBQzR0k4T9feK8GRM
# yKPsje7JV93+PTB8IbL5UpsrLVz+JGxsaWtOpWuYdXGfnvXYYELmYYcXOuJxim8v
# TTvfvJ7SA5w+3er+NChAr98uJKuqrZnkJTV1Ki+8JwYTdAtNm1kJaM/Drnbk50K4
# v0FMGeqSYRns3shmCvhlkUH0v+mXz7CpnVYztIBlgbxnio7PWmbTqknPEhNMeyjb
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Hash Checker_1.ps1
|
Hash Checker_1.ps1
|
#.Synopsis
# Test the HMAC hash(es) of a file
#.Description
# Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
#.Example
# Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
#
# Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
# and take the hash of the file (using the extension of the HashFile as the Type of Hash).
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
#
# Takes the MD5 hash and compares it to the provided hash
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
#
# Tests all of the hashes against the provided (Sha1) hash
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
PowerShellCorpus/PoshCode/Get-Uptime.ps1
|
Get-Uptime.ps1
|
Function Get-Uptime {
<#
.SYNOPSIS
Displays Uptime since last reboot
.PARAMETER Computername
.EXAMPLE
Get-Uptime Server1
.EXAMPLE
"Server1", "Server2"|Get-Uptime
.EXAMPLE
(Get-Uptime Sever1)."Time Since Last Reboot"
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$true,Position=0)]
[STRING[]]$Computername
)
Begin {Write-Verbose "Version 1.00"}
Process {
$Now=Get-Date
$LastBoot=[System.Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject win32_operatingsystem -ComputerName $computername).lastbootuptime)
$Result=@{ "Server"=$($Computername);
"Last Reboot"=$LastBoot;
"Time Since Reboot"="{0} Days {1} Hours {2} Minutes {3} Seconds" -f ($Now - $LastBoot).days, `
($Now - $LastBoot).hours,($Now - $LastBoot).minutes,($Now - $LastBoot).seconds}
Write-Output (New-Object psobject -Property $Result|select Server, "Last Reboot", "Time Since Reboot")
}
}
|
PowerShellCorpus/PoshCode/Compare-DellUpdates.ps1
|
Compare-DellUpdates.ps1
|
#Requires -version 2
#Author: Nathan Linley
#More details: http://myitpath.blogspot.com/2012/02/dell-components-check-for-updates-via.html
#OUTPUT FORMAT:
#Component : FlashBIOS Updates
#path : PE2850_BIOS_WIN_A07.EXE
#vendorVersion : A07
#currentversion : A05
#releaseDate : May 23, 2008
#Criticality : Optional
#AtCurrent : False
param(
[parameter(mandatory=$true)][ValidateScript({test-path $_ -pathtype 'leaf'})][string]$catalogpath,
[parameter(mandatory=$true,ValueFromPipeline=$true)][string]$server
)
$catalog = [xml](get-Content $catalogpath)
$oscodeid = &{
$caption = (Get-WmiObject win32_operatingsystem -ComputerName $server).caption
if ($caption -match "2003") {
if ($caption -match "x64") { return "WX64E" } else { return "WNET2"}
if ($caption -match "2008 R2") { return "W8R2"}
if ($caption -match "2008" ) {
if ($caption -match "x64") { return "WSSP2" } else {return "LHS86"}
}
}
}
$systemID = (Get-WmiObject -Namespace "root\\cimv2\\dell" -query "Select Systemid from Dell_CMInventory" -ComputerName $server).systemid
$model = (Get-WmiObject -Namespace "root\\cimv2\\dell" -query "select Model from Dell_chassis" -ComputerName $server).Model
$model = $model.replace("PowerEdge","PE").replace("PowerVault","PV").split(" ") #model[0] = Brand Prefix #model[1] = Model #
$devices = Get-WmiObject -Namespace "root\\cimv2\\dell" -Class dell_cmdeviceapplication -ComputerName $server
foreach ($dev in $devices) {
$xpathstr = $parts = $version = ""
if ($dev.Dependent -match "(version=`")([A-Z\\d.]+)`"") { $version = $matches[2] } else { $version = "unknown" }
$parts = $dev.Antecedent.split(",")
$depparts = $dev.dependent.split(",")
$componentType = $depparts[0].substring($depparts[0].indexof('"'))
if ($dev.Antecedent -match 'componentID=""') {
$xpathstr = "//SoftwareComponent[@packageType='LWXP']/SupportedDevices/Device/PCIInfo"
if ($componentType -match "DRVR") {
$xpathstr += "[@" + $parts[2] + " and @" + $parts[3] + "]/../../.."
$xpathstr += "/SupportedOperatingSystems/OperatingSystem[@osVendor=`'Microsoft`' and @osCode=`'" + $osCodeID + "`']/../.."
} else {
$xpathstr += "[@" + $parts[2] + " and @" + $parts[3] + " and @" + $parts[4] + " and @" + $parts[5] + "]/../../.."
$xpathstr += "/SupportedSystems/Brand[@prefix=`'" + $model[0] + "`']/Model[@systemID=`'" + $systemID + "`']/../../.."
}
$xpathstr += "/ComponentType[@value=" + $componentType + "]/.."
} else {
$xpathstr = "//SoftwareComponent[@packageType='LWXP']/SupportedDevices/Device[@"
$xpathstr += $parts[0].substring($parts[0].indexof("componentID"))
$xpathstr += "]/../../SupportedSystems/Brand[@prefix=`'" + $model[0] + "`']/Model[@systemID=`'"
$xpathstr += $systemID + "`']/../../.."
}
$result = Select-Xml $catalog -XPath $xpathstr |Select-Object -ExpandProperty Node
$result |Select-Object @{Name="Component";Expression = {$_.category.display."#cdata-section"}},path,vendorversion,@{Name="currentversion"; Expression = {$version}},releasedate,@{Name="Criticality"; Expression={($_.Criticality.display."#cdata-section").substring(0,$_.Criticality.display."#cdata-section".indexof("-"))}},@{Name="AtCurrent";Expression = {$_.vendorVersion -eq $version}}
}
|
PowerShellCorpus/PoshCode/Servers in Computers OU.ps1
|
Servers in Computers OU.ps1
|
function checkADSI()
{ $ADSIStat = "Servers in Computer OU"
$error.clear()
$errcnt = 0
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://CN=Computers,DC=domain,DC=com")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($objDomain)
$objSearcher.Filter = ("(operatingSystem=*Server*)")
$objSearcher.SearchScope = "OneLevel"
$colProplist = "dnshostname"
foreach ($i in $colPropList)
{$idx = $objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
for($i = 0; $i -lt ($colResults.count -1); $i++ )
{ $objResult = $colResults[$i]
$objComputer = $objResult.Properties
$cName = ($objComputer.dnshostname -replace ".domain.com","")
$ADSIStat += "`n`t! " + $cname
$errcnt += 1
}
if($error[0])
{ $ADSIStat += "`n`t Errors Occured: "
foreach($err in $error)
{ $ADSIStat += "`n`t`!" + $err }
}
elseif($errCnt -eq 0)
{$ADSIStat += " None" }
return $ADSIStat
}#function checkADSI()
|
PowerShellCorpus/PoshCode/Prevent-Screensaver_2.ps1
|
Prevent-Screensaver_2.ps1
|
#########################################################
# Prevent-Screensaver
#########################################################
# This script "presses" a keyboard key every minute
# for specified number of minutes which makes
# Windows "think" you are at your desktop
# so the screensaver does not start and the desktop
# does not get locked.
#########################################################
# Usage:
# & c:\\filepath\\Prevent-Screensaver.ps1 -Minutes 120
# Makes the script press "." for 120 minutes.
# Start notepad or another app and put focus there
# to see the dots appear and prevent beeping
########################################################
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com
########################################################
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
|
PowerShellCorpus/PoshCode/ShowUI Weather Widget_2.ps1
|
ShowUI Weather Widget_2.ps1
|
## And a slick weather widget using Yahoo's forecast and images
New-UIWidget -AsJob {
Grid {
Rectangle -RadiusX 10 -RadiusY 10 -StrokeThickness 0 -Width 170 -Height 80 -HorizontalAlignment Left -VerticalAlignment Top -Margin "60,40,0,0" -Fill {
LinearGradientBrush -Start "0.5,0" -End "0.5,1" -Gradient {
GradientStop -Color "#FF007bff" -Offset 0
GradientStop -Color "#FF40d6ff" -Offset 1
}
}
Image -Name Image -Stretch Uniform -Width 250.0 -Height 180.0 -Source "http://l.yimg.com/a/i/us/nws/weather/gr/31d.png"
TextBlock -Name Temp -Text "99°" -FontSize 80 -Foreground White -Margin "130,0,0,0" -Effect { DropShadowEffect -Color Black -Shadow 0 -Blur 8 }
TextBlock -Name Forecast -Text "Forecast" -FontSize 12 -Foreground White -Margin "120,95,0,0"
}
} -Refresh "00:10" {
# To find your WOEID, browse or search for your city from the Weather home page.
# The WOEID is the LAST PART OF the URL for the forecast page for that city.
$woEID = 14586
$channel = ([xml](New-Object Net.WebClient).DownloadString("http://weather.yahooapis.com/forecastrss?p=$woEID")).rss.channel
$h = ([int](Get-Date -f hh))
if($h -gt ([DateTime]$channel.astronomy.sunrise).Hour -and $h -lt ([DateTime]$channel.astronomy.sunset).Hour) {
$dayOrNight = 'd'
} else {
$dayOrNight = 'n'
}
$source = "http`://l.yimg.com/a/i/us/nws/weather/gr/{0}{1}.png" -f $channel.item.condition.code, $dayOrNight
$Image.Source = $source
$Temp.Text = $channel.item.condition.temp + [char]176
$Forecast.Text = "High: {0}{2} Low: {1}{2}" -f $channel.item.forecast[0].high, $channel.item.forecast[0].low, [char]176
}
|
PowerShellCorpus/PoshCode/Set-TopMost_1.ps1
|
Set-TopMost_1.ps1
|
#Requires -Version 2.0
$signature = @"
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static IntPtr FindWindow(string windowName){
return FindWindow(null,windowName);
}
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
public static void MakeTopMost (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
public static void MakeNormal (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_NOTOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
"@
$app = Add-Type -MemberDefinition $signature -Name Win32Window -Namespace ScriptFanatic.WinAPI -ReferencedAssemblies System.Windows.Forms -Using System.Windows.Forms -PassThru
function Set-TopMost
{
param(
[Parameter(
Position=0,ValueFromPipelineByPropertyName=$true
)][Alias('MainWindowHandle')]$hWnd=0,
[Parameter()][switch]$Disable
)
if($hWnd -ne 0)
{
if($Disable)
{
Write-Verbose "Set process handle :$hWnd to NORMAL state"
$null = $app::MakeNormal($hWnd)
return
}
Write-Verbose "Set process handle :$hWnd to TOPMOST state"
$null = $app::MakeTopMost($hWnd)
}
else
{
Write-Verbose "$hWnd is 0"
}
}
function Get-WindowByTitle($WindowTitle="*")
{
Write-Verbose "WindowTitle is: $WindowTitle"
if($WindowTitle -eq "*")
{
Write-Verbose "WindowTitle is *, print all windows title"
Get-Process | Where-Object {$_.MainWindowTitle} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
else
{
Write-Verbose "WindowTitle is $WindowTitle"
Get-Process | Where-Object {$_.MainWindowTitle -like "*$WindowTitle*"} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
}
Exaples:
# set powershell console on top of other windows
gps powershell | Set-TopMost
# unset
gps powershell | Set-TopMost -disable
# set an application on top of other windows by its windows title (wildcard is supported)
Get-WindowByTitle *pad* | Set-TopMost
# unset
Get-WindowByTitle textpad | Set-TopMost -Disable
|
PowerShellCorpus/PoshCode/format-iislog for AWStat_1.ps1
|
format-iislog for AWStat_1.ps1
|
param
(
[Parameter(
Mandatory=$true,
Position = 0,
ValueFromPipeline=$true,
HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log."
)]
[ValidateNotNullOrEmpty()]
[string]
$Path,
[Parameter(
Mandatory=$true,
Position = 1,
ValueFromPipeline=$true,
HelpMessage="Specifies the desired field names. Must be in the following format: #Fields: fname1 fname2"
)]
[ValidateNotNullOrEmpty()]
[string]
$NewPath,
[Parameter(
Mandatory=$true,
Position = 2,
ValueFromPipeline=$true,
HelpMessage="Specifies the output location for the modified log file."
)]
[ValidateNotNullOrEmpty()]
[string]
$OutPath,
[Parameter(
Position = 3,
HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar."
)]
[ValidateNotNullOrEmpty()]
[string]
$Delimiter = " ",
[Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")]
[Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]
$Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8
)
begin
{
$fieldNames = @()
$newfieldnames = @()
}
process
{
#add headers to new output file
(get-content $path)[0..2] | Out-File $outpath -Append -encoding Default
$newpath | Out-File $outpath -Append -encoding Default
#populate $newfieldnames from the mandatory parameter $newpath
$newfieldNames = @($newpath.Substring("#Fields: ".Length).Split($Delimiter));
foreach($line in Get-Content -Path $Path)
{
# Indentify / parse the log header to determine field names
if($line.StartsWith("#Fields: "))
{
$fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter));
}
# Identify / parse the "non log header" lines to determine field values
elseif(-not $line.StartsWith("#"))
{
$logline = ""
$fieldValues = @($line.Split($Delimiter));
#Initialize a hashtable to hold fields and values
#Default value is a hyphen
#Only fields specified in the $newpath parameter are initialized
$output = @{}
foreach ($item in $newfieldnames)
{
switch($item)
{
"date"{ $output.add("date", "-")}
"time"{ $output.add("time", "-")}
"s-ip"{ $output.add("s-ip", "-")}
"cs-method"{ $output.add("cs-method", "-")}
"cs-uri-stem"{ $output.add("cs-uri-stem", "-")}
"cs-uri-query"{ $output.add("cs-uri-query", "-")}
"s-port"{ $output.add("s-port", "-")}
"cs-username"{ $output.add("cs-username", "-")}
"c-ip"{ $output.add("c-ip", "-")}
"cs-version"{ $output.add("cs-version", "-")}
"cs(User-Agent)"{ $output.add("cs(User-Agent)", "-")}
"sc-status"{ $output.add("sc-status", "-")}
"sc-substatus"{ $output.add("sc-substatus", "-")}
"sc-win32-status"{ $output.add("sc-win32-status", "-")}
"sc-bytes"{ $output.add("sc-bytes", "-")}
"time-taken"{ $output.add("time-taken", "-")}
"cs-host"{ $output.add("cs-host", "-")}
"cs(Cookie)"{ $output.add("cs(Cookie)", "-")}
"cs(Referer)"{ $output.add("cs(Referer)", "-")}
"s-sitename"{ $output.add("s-sitename", "-")}
"s-computername"{ $output.add("s-computername", "-")}
"cs-bytes"{ $output.add("cs-bytes", "-")}
}
}
#Add every field from old log file to the $ouptuts hashtable
#Portions of the hash table which are not over written at this point retain the default value (hyphen)
for($i = 0; $i -lt $fieldnames.Length; $i++)
{
$name = $fieldNames[$i]
$value = $fieldValues[$i]
switch($name)
{
"date"{ $output['date'] = $value}
"time"{ $output['time'] = $value}
"s-ip"{ $output['s-ip'] = $value}
"cs-method"{ $output['cs-method'] = $value}
"cs-uri-stem"{ $output['cs-uri-stem'] = $value}
"cs-uri-query"{ $output['cs-uri-query'] = $value}
"s-port"{ $output['s-port'] = $value}
"cs-username"{ $output['cs-username'] = $value}
"c-ip"{ $output['c-ip'] = $value}
"cs-version"{ $output['cs-version'] = $value}
"cs(User-Agent)"{ $output['cs(User-Agent)'] = $value}
"sc-status"{ $output['sc-status'] = $value}
"sc-substatus"{ $output['sc-substatus'] = $value}
"sc-win32-status"{ $output['sc-win32-status'] = $value}
"sc-bytes"{ $output['sc-bytes'] = $value}
"time-taken"{ $output['time-taken'] = $value}
"cs-host"{ $output['cs-host'] = $value}
"cs(Cookie)"{ $output['cs(Cookie)'] = $value}
"cs(Referer)"{ $output['cs(Referer)'] = $value}
"s-sitename"{ $output['s-sitename'] = $value}
"s-computername"{ $output['s-computername'] = $value}
"cs-bytes"{ $output['cs-bytes'] = $value}
}
}
#$output
$linewriter = $null
#Write lines to new log file
#Only call upon keys (from output hash) which correspond to desired $newfieldnames as specified in $newpath parameter.
#Unwanted fields from old log are inherently dropped
#Newly included fields not present in old log are inherently replaced by hypens
foreach ($item in $newfieldnames)
{
$linewriter += $output[$item]
$linewriter += " "
}
$linewriter |%{$_ -replace " $",""}| Out-File $outpath -Append -encoding Default
}
}
}
# usage example
#.\\import-iislog-final.ps1 "C:\\Old Logs\\u_ex120218.log" "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\u_ex120218.log"
#foreach ($log in (gci "c:\\Old Logs")) {.\\import-iislog-final.ps1 $log.fullname "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\$log"}
|
PowerShellCorpus/PoshCode/WPFTableSpace.ps1
|
WPFTableSpace.ps1
|
#Usage: ./WPFTableSpace.ps1 'Z002\\SqlExpress' AdventureWorks
#Note: Requires .NET 3.5, Visifire Charts (tested on v2.1.0), Powerboots (tested on v0.1), and SQLPSX (tested on v1.5)
param($sqlserver=$(throw 'sqlserver is required.'),$dbname=$(throw 'dbname is required.'),$top=10)
$libraryDir = Convert-Path (Resolve-Path "$ProfileDir\\Libraries")
[Void][Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path "$libraryDir\\WPFVisifire.Charts.dll")) )
. $libraryDir\\LibrarySmo.ps1
if (!(Get-PSSnapin | ?{$_.name -eq 'PoshWpf'}))
{ Add-PsSnapin PoshWpf }
$qry = @"
CREATE TABLE #spaceused
(name nvarchar(128),
rows char(11),
reserved varchar(18),
data varchar(18),
index_size varchar(18),
unused varchar(18));
EXEC sp_MSforeachtable 'insert #spaceused exec sp_spaceused ''?''';
SELECT TOP $top name
, CAST(rows AS int) AS rows
, CAST(SUBSTRING(reserved,0,LEN(reserved)-2) AS int) AS reserved
, CAST(SUBSTRING(data,0,LEN(data)-2) AS int) AS data
, CAST(SUBSTRING(index_size,0,LEN(index_size)-2) AS int) AS index_size
, CAST(SUBSTRING(unused,0,LEN(unused)-2) AS int) AS unused
FROM #spaceused
ORDER BY reserved DESC;
DROP TABLE #spaceused;
"@
New-BootsWindow -Async {
$chart = New-Object Visifire.Charts.Chart
$chart.Height = 500
$chart.Width = 800
$chart.watermark = $false
$chart.Theme = "Theme2"
$chart.View3D = $true
$chart.BorderBrush = [System.Windows.Media.Brush]"Gray"
$chart.CornerRadius = [System.Windows.CornerRadius]5
$chart.BorderThickness = [System.Windows.Thickness]0.5
$chart.AnimationEnabled = $false
$ds1 = New-Object Visifire.Charts.DataSeries
$ds1.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds1.LegendText = "Data"
$ds1.LabelEnabled = $true
$ds1.LabelText = "#YValue"
$ds2 = New-Object Visifire.Charts.DataSeries
$ds2.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds2.LegendText = "Index"
$ds2.LabelEnabled = $true
$ds2.LabelText = "#YValue"
$ds2.RadiusX = 5
$ds2.RadiusY = 5
foreach ($table in Get-SqlData $sqlserver $dbname $qry)
{
$dp1 = new-object Visifire.Charts.DataPoint
$dp1.AxisXLabel = $table.name
$dp1.YValue = $table.data
$ds1.DataPoints.Add($dp1)
$dp2 = new-object Visifire.Charts.DataPoint
$dp2.YValue = $table.index_size
$ds2.DataPoints.Add($dp2)
}
$chart.Series.Add($ds1)
$chart.Series.Add($ds2)
$chart
} -Title "Table Space"
|
PowerShellCorpus/PoshCode/Resolve-Aliases _4.7.ps1
|
Resolve-Aliases _4.7.ps1
|
#requires -version 2.0
## ResolveAliases Module v 1.7
########################################################################################################################
## Sample Use:
## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1
## ls *.ps1 | Resolve-Aliases -Inplace
########################################################################################################################
## Version History
## 1.0 - First Version. "It worked on my sample script"
## 1.1 - Now it parses the $(...) blocks inside strings
## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts)
## 1.3 - I went back to processing the whole script at once (instead of a line at a time)
## Processing a line at a time makes it impossible to handle Here-Strings...
## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it
## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is
## 1.4 - Now resolves parameters too
## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem)
## - Refactored the Resolve-Line filter right out of existence
## - Created a test script for validation, and
## 1.6 - Added resolving parameter ALIASES instead of just short-forms
## 1.7 - Minor tweak to make it work in CTP3
##
## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path
## * *TODO:* Add an option to put #requires statements at the top for each snapin used
########################################################################################################################
function which {
PARAM( [string]$command )
# aliases, functions, cmdlets, scripts, executables, normal files
$cmds = @(Get-Command $command -EA "SilentlyContinue")
if($cmds.Count -gt 1) {
$cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0]
} else {
$cmd = $cmds[0]
}
if(!$cmd) {
$cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0]
}
if( $cmd.CommandType -eq "Alias" ) {
$cmd = which $cmd.Definition
}
return $cmd
}
function Resolve-Aliases
{
[CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")]
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")]
[string]$Line
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")]
[Alias("FullName","PSChildName","PSPath")]
[IO.FileInfo]$File
,
[Parameter(Position=1, ParameterSetName="Files")]
[Switch]$InPlace
)
BEGIN {
Write-Debug $PSCmdlet.ParameterSetName
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "Files") {
if($File -is [System.IO.FileInfo]){
$Line = ((Get-Content $File) -join "`n")
} else {
throw "We can't resolve a whole folder at once yet"
}
}
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null)
for($t = $Tokens.Count; $t -ge 0; $t--) {
$token = $Tokens[$t]
# DEBUG $token | fl * | out-host
switch($token.Type) {
"Command" {
$cmd = which $token.Content
Write-Debug "Command $($token.Content) => $($cmd.Name)"
#if($cmd.CommandType -eq "Alias") {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name )
#}
}
"CommandParameter" {
Write-Debug "Parameter $($token.Content)"
for($c = $t; $c -ge 0; $c--) {
if( $Tokens[$c].Type -eq "Command" ) {
$cmd = which $Tokens[$c].Content
# if($cmd.CommandType -eq "Alias") {
# $cmd = @(which $cmd.Definition)[0]
# }
$short = $token.Content -replace "^-?","^"
Write-Debug "Parameter $short"
$parameters = $cmd.ParameterSets | Select -expand Parameters
$param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique)
if($param.Count -eq 1) {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" )
}
break
}
}
}
}
}
switch($PSCmdlet.ParameterSetName) {
"Text" {
$Line
}
"Files" {
switch($File.GetType()) {
"System.IO.FileInfo" {
if($InPlace) {
$Line | Set-Content $File
} else {
$Line
}
}
default { throw "We can't resolve a whole folder at once yet" }
}
}
default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" }
}
}
}
|
PowerShellCorpus/PoshCode/Netapp SDK_1.ps1
|
Netapp SDK_1.ps1
|
#Jason Ochoa
#3/3/2010
#This script requires the DLL from the website below.
#http://communities.netapp.com/docs/DOC-1110
#connection to file filer
#$null = [reflection.assembly]::loadfile('C:\\admin\\ManageOntap.dll')
#$pvflrtst = New-Object netapp.manage.naserver('pvflrtst',1,0)
#$pvflrtst.setadminuser("z05785a",'XXXXX')
#$testfiler1 = New-Object netapp.manage.naserver('testfiler1',1,0)
#$testfiler1.setadminuser("z05785",'XXXXXX')
#-------------------functions to be remade
function global:Get-DF-s ($NaServer){#this data can be gathered directly from the volume-info package
$NaElement = New-Object NetApp.Manage.NaElement(”system-cli”)
$arg = New-Object NetApp.Manage.NaElement(”args”)
$arg.AddNewChild(’arg’,'df’)
$arg.AddNewChild(’arg’,'-s’)
$NaElement.AddChildElement($arg)
$results= $NaServer.InvokeElem($naelement).GetChildContent(”cli-output”)
$results = $results.Split("`n")
$ResultsObj = $results| ?{$_ -match "vol"}| %{$null = $_ -match "(?<FileSystem>(\\S+))\\s+(?<used>(\\d+))\\s+(?<saved>(\\d+))\\s+(?<PercentSave>(\\d+))";
$myobj = "" | Select-Object filesystem, usedGB, savedGB, percentsave;
$myobj.filesystem = $matches.Filesystem;
$myobj.usedGB = [Math]::Round([double]$matches.used /1mb, 2);
$myobj.savedGB = [Math]::Round([double]$matches.saved /1mb, 2);
$myobj.percentsave = [int]$matches.percentsave;
,$myobj}
,($ResultsObj| Sort-Object filesystem)
}
#------------------------------sis functions
function global:Get-SIS-Status ($NaServer){
$naelement = New-Object netapp.manage.naelement("sis-status")
$NaElement.AddNewChild('verbose','true')
$Output = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'.'dense-status'
$Output = $output | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $null -PassThru |
Add-Member -MemberType NoteProperty -Name "Duration" -Value $null -PassThru
$Output| %{$_.Duration =(((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-end-timestamp') - ((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-begin-timestamp') )}
$Output| %{$_.StartTime = (((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-begin-timestamp'))}
$Output
}
function global:Get-SIS-LongJobs ($NaServer){
$output = Get-SIS-Status ($NaServer)
$output |Sort-Object State, duration -descending| Select-Object path, duration, schedule, 'last-operation-size', State| ft -AutoSize
}
function global:Set-SIS-config ($NaServer, $volume, $schedule){
$naelement = New-Object netapp.manage.naelement("sis-set-config")
$NaElement.AddNewChild('path',$volume)
$NaElement.AddNewChild('schedule',$schedule)
([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:start-SIS ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("sis-start")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:stop-SIS ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("sis-stop")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:Set-SIS-ON($NaServer, $volume, [switch]$SISOFF )
{
if (-not $SISOFF){
$naelement = New-Object netapp.manage.naelement("sis-enable")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
else{
$naelement = New-Object netapp.manage.naelement("sis-disable")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
}
function global:Start-SIS-All ($NaServer, $MaxJobs = 4){
$StartTime = get-date
foreach ($path in (Get-SIS-status $NaServer|%{$_.path})){
while (@(Get-SIS-status $NaServer|?{$_.status -eq "Active"}).count -ge $MaxJobs){start-sleep 15; write-host "." -nonewline}
write-host "Starting $Path"
start-sis $NaServer $Path
Start-Sleep 5}
Write-Host "This task took: $((get-date) - $StartTime)"
}
#-----------------------Snapshot functions
function global:get-Snap-AutoDeleteInfo ($NaServer)
{
$naelement = New-Object netapp.manage.naelement("volume-list-info")
$volumes = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.volumes.'volume-info'
foreach ($vol in $volumes){
$naelement = New-Object netapp.manage.naelement("snapshot-autodelete-list-info")
$NaElement.AddNewChild('volume',$Vol.name)
$snapInfo = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.options.'snapshot-autodelete-info'
$myobj = "" | Select-Object Volume, state, commitment, trigger, target_free_space, delete_order, defer_delete, destroy_list
$myobj.Volume = $vol.name
foreach ($option in $snapInfo){$myobj.($option.'option-name') = $option.'option-value'}
$myobj
}
}
function global:set-Snap-AutoDeleteInfo ($NaServer, $volume, $state="on", $commitment="try", $trigger="volume", $targer_free_space="15", $delete_order="oldest_first", $defer_delete="user_created"){
$Options = @($state, $commitment, $trigger, $targer_free_space, $delete_order, $defer_delete)
$OptionNames = @("state", "commitment", "trigger", "target_free_space", "delete_order", "defer_delete")
foreach ($Counter in (0..5)){
$naelement = New-Object netapp.manage.naelement("snapshot-autodelete-set-option")
$NaElement.AddNewChild('volume',$volume)
$NaElement.AddNewChild('option-name', $OptionNames[$counter])
$NaElement.AddNewChild('option-value',$Options[$counter])
$null = $NaServer.invokeelem($naelement)
}
}
function global:get-Snap-List ($NaServer)
{
$naelement = New-Object netapp.manage.naelement("volume-list-info")
$volumes = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.volumes.'volume-info'
foreach ($vol in $volumes){
$naelement = New-Object netapp.manage.naelement("snapshot-list-info")
$NaElement.AddNewChild('target-type','volume’)
$NaElement.AddNewChild('target-name',$Vol.name)
$snapshots = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.snapshots.'snapshot-info'
foreach ($Snap in $snapshots){
$myobj = "" | Select-Object Volume, Name, accesstime, totalMB, CTotalMB, POfUsedB, CPOfUsedB
$myobj.Volume = $vol.name
$myobj.name = $Snap.name
$myobj.accesstime = ((get-date -date 1/1/1970).addhours(-7)).addseconds($Snap.'access-time')
$myobj.totalMB = [Math]::round($Snap.total / 1kb, 2)
$myobj.CTotalMB = [Math]::round($Snap.'cumulative-total' /1kb, 2)
$myobj.POfUsedB = $Snap.'percentage-of-used-blocks'
$myobj.CPOfUsedB = $Snap.'cumulative-percentage-of-used-blocks'
$myobj
}
}
}
function global:get-SnapList-Top-Total(){
$Snaps = (get-Snap-List $1504) + (get-Snap-List $1505)
"Top 20 Large Snapshots"
$Snaps|sort-object -prop totalMB -desc| select-object -first 20 | ft -AutoSize
"Top 20 Snapshot footprint"
$Snaps| Group-Object -Property volume|%{$_.group|sort-object -prop accesstime|select-object -First 1 }| sort-object -prop CtotalMB -desc| select-object -first 20|ft -AutoSize
"Top 5 Oldest Snapshots"
$Snaps| Group-Object -Property volume|%{$_.group|sort-object -prop accesstime|select-object -First 1 }| ?{$_.name -ne $null}|sort-object -prop accesstime| select-object -first 5 | ft -AutoSize
}
function global:rename-Snap($NaServer, $CurrentName, $newName, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-rename")
$NaElement.AddNewChild('current-name',$CurrentName)
$NaElement.AddNewChild('new-name',$newName)
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
function global:remove-Snap($NaServer, $Snapshot, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-delete")
$NaElement.AddNewChild('snapshot',$Snapshot)
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
function global:get-snap ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-list-info")
$NaElement.AddNewChild('target-type','volume’)
$NaElement.AddNewChild('target-name',$volume)
$snapshots = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.snapshots.'snapshot-info'
foreach ($Snap in $snapshots){
$myobj = "" | Select-Object Volume, Name, accesstime, totalMB, CTotalMB, POfUsedB, CPOfUsedB
$myobj.Volume = $volume
$myobj.name = $Snap.name
$myobj.accesstime = ((get-date -date 1/1/1970).addhours(-7)).addseconds($Snap.'access-time')
$myobj.totalMB = [Math]::round($Snap.total / 1kb, 2)
$myobj.CTotalMB = [Math]::round($Snap.'cumulative-total' /1kb, 2)
$myobj.POfUsedB = $Snap.'percentage-of-used-blocks'
$myobj.CPOfUsedB = $Snap.'cumulative-percentage-of-used-blocks'
$myobj
}
}
function global:New-Snap ($NaServer, $SnapPrefix, $volume, $MaxSave = 5){
if ([int]$MaxSave -lt 1) {return -1}
$CurrentSnaps = get-snap $NaServer $volume
$CurrentSnaps = @($CurrentSnaps| ?{$_.name -match "^$SnapPrefix\\.\\d+$"}| Sort-Object -Property accesstime )
#"count: $($CurrentSnaps.count) - $MaxSave = $($CurrentSnaps.count - $MaxSave)"
if ($CurrentSnaps.count -gt $MaxSave-1 -and $CurrentSnaps.count -gt 0) {#remove Oldest Snap
#"hit cleanup process"
foreach ($i in 0..($CurrentSnaps.count - $MaxSave )){
#"Removing: $($CurrentSnaps[0].Name)"
remove-snap $NaServer $CurrentSnaps[0].Name $volume
$CurrentSnaps = @($CurrentSnaps| ?{$_.name -ne $CurrentSnaps[0].Name})
}
}
#"current snaps after removals"
#$CurrentSnaps|%{$_.name}
if ($CurrentSnaps -ne $null){
foreach ($Snap in $CurrentSnaps){
$null = $Snap.name -match "^$SnapPrefix\\.(?<digit>\\d+)$"
rename-snap $NaServer $Snap.name "$SnapPrefix.$([int]$matches.digit+1)" $volume
#"Renaming: $($Snap.name) -> $SnapPrefix.$([int]$matches.digit+1)"
}
}
$naelement = New-Object netapp.manage.naelement("snapshot-create")
$NaElement.AddNewChild('snapshot',"$SnapPrefix.0")
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
# --------------- Lun functions
function Set-LUN-Caption ($NaServer, $LUNpath, $Comment){
$naelement = New-Object netapp.manage.naelement("lun-set-comment")
$NaElement.AddNewChild('comment',$comment)
$NaElement.AddNewChild('path',$LUNpath)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:get-Lun-Info ($NaServer, $LUNpattern='.*'){
$naelement = New-Object netapp.manage.naelement("lun-list-info")
$LUNs = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.luns.'lun-info'
$LUNs| ?{$_.path -match $LUNpattern}| Sort-Object path
}
function global:Map-Lun ($NaServer, $LUNpath, $iGroup, $LUNid){
$naelement = New-Object netapp.manage.naelement("lun-map")
$NaElement.AddNewChild('path',$LUNpath)
$NaElement.AddNewChild('initiator-group',$iGroup)
$NaElement.AddNewChild('lun-id',$LUNid)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:Get-LUN-Map ($NaServer, $filter ='.*'){
$LUNs = get-Lun-Info $NaServer
$Maps = foreach ($LUN in $LUNs){
$naelement = New-Object netapp.manage.naelement("lun-map-list-info")
$NaElement.AddNewChild('path',$LUN.path)
$Groups = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'initiator-groups'.'initiator-group-info'
if ($groups) {$groups | Add-Member -MemberType noteproperty -Name path -Value $LUN.path -Force -PassThru}
}
$Maps| ?{$_.'initiator-group-name' -match $filter -or $_.path -match $filter}|Sort-Object path, 'lun-id'
}
function global:copy-LUN-Map ($NaServer, $SourceiGroup, $DestinationiGroup, $filter = '.*'){
$LUNmaps = Get-LUN-Map $NaServer $SourceiGroup $filter
foreach ($LUNmap in $LUNmaps){
Map-Lun $NaServer $LUNmap.path $DestinationiGroup $LUNmap.'lun-id'
}
}
function global:online-LUN ($NaServer, $LUN){
$NaElement = New-Object netapp.manage.naelement("lun-online")
$NaElement.AddNewChild('path', $LUN)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:offline-LUN ($NaServer, $LUN){
$NaElement = New-Object netapp.manage.naelement("lun-offline")
$NaElement.AddNewChild('path', $LUN)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
#------------- Performance functions
function global:list {$args}
function global:Print-NaMatrix($values){
$c =list b c c c c d d d g g c d d d d g g g y y c d d d d g g g y y c d d d d g g g y y c d d d d g g g y y d g g g g y y y m m d g g g g y y y m m d g g g g y y y m m g y y y y m m m r r g y y y y m m m r r
$d = $c|%{ switch ($_) { "b" {"cyan"}; "c" {"cyan"}; "d" {"darkgreen"}; "g" {"Green"}; "y" {"Yellow"}; "m" {"magenta"}; "r" {"Red"}}}
$x=0;$values|%{$x=$x+$_}
1..100|%{if ($_ % 10 -eq 0){write-host ("{0:P2}" -f (($values[$_-1])/$x)) -for $d[$_-1]} else {write-host ("{0:P2}" -f (($values[$_-1])/$x)) -for $d[$_-1] -no}}
}
function global:Get-NaCounter($Filer, $counter){
$naelement = New-Object netapp.manage.naelement("perf-object-get-instances")
$NaElement.AddNewChild(’objectname’,'perf’)
$results = [xml]($Filer.invokeelem($naelement)).tostring()
$myobj = "" | Select-Object Value, Timestamp
$myobj.TimeStamp = ((get-date -date 1/1/1970).addhours(-7)).addseconds($results.results.timestamp)
$value = ($results.results.instances.'instance-data'.counters.'counter-data'|?{$_.name -eq $counter}).value
$myobj.Value = if ($value){$value} else{"Missing Counter"}
$myObj
}
function global:Get-NaCounter-TimeSlice($NaServer, $counter = 'disk_user_reads_latency_histogram', $timeSample = 10){
$values1 = (Get-NaCounter $NaServer $counter).Value
$values1= [regex]::split($values1,",")
Start-Sleep $timeSample
$values2 = (Get-NaCounter $NaServer $counter).Value
$values2= [regex]::split($values2,",")
$values =(0..($values1.count))|%{($values2[$_] - $values1[$_])}
$values
}
function global:Get-NaMatrix-Full($NaServer){
$values = (Get-NaCounter $NaServer 'cpu_disk_util_matrix').Value
$values= [regex]::split($values,",")
Print-NaMatrix $values
}
function global:Get-NaMatrix-TimeSlice($NaServer,$timeSample = 10){
Print-NaMatrix (Get-NaCounter-TimeSlice $NaServer 'cpu_disk_util_matrix' $timeSample)
}
#------------- Get and Set netapp options functions
function global:Set-NaOption ($NaServer, $OptionName, $OptionValue){
$naelement = New-Object netapp.manage.naelement("options-set")
$NaElement.AddNewChild('name',$OptionName)
$NaElement.AddNewChild('value',$OptionValue)
$null = [xml]($NaServer.invokeelem($naelement)).tostring()
Get-NaOption $NaServer "^$OptionName"
}
function global:Get-NaOption ($NaServer, $Search = '.*'){
$naelement = New-Object netapp.manage.naelement("options-list-info")
$Options = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.options.'option-info'
$Options|?{$_.name -match $Search}
}
#------------- Get and Set netapp priority
function global:get-NaPriority($NaServer, $filter=".*"){
$naelement = New-Object netapp.manage.naelement("priority-list-info-volume")
$Prioritys = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'priority-volume'.'priority-volume-info'
$Prioritys| ?{$_.volume -match $filter}| Sort-Object volume
}
function global:Set-NaPriority-AllOn($NaServer){
$naelement = New-Object netapp.manage.naelement("volume-list-info")
$volumes = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.volumes.'volume-info'
foreach ($vol in $volumes){
$naelement = New-Object netapp.manage.naelement("priority-set-volume")
$NaElement.AddNewChild('volume',$vol.name)
$NaElement.AddNewChild('service','on')
$null = [xml]($NaServer.invokeelem($naelement)).tostring()
get-NaPriority $NaServer $vol.name
}
}
function global:SetNaPriority ($NaServer, $volume, $service='on',$level='5',$system='5'){
$naelement = New-Object netapp.manage.naelement("priority-set-volume")
$NaElement.AddNewChild('volume',$volume)
$NaElement.AddNewChild('service',$service)
$NaElement.AddNewChild('level',$level)
$NaElement.AddNewChild('system',$system)
$null = [xml]($NaServer.invokeelem($naelement)).tostring()
get-NaPriority $NaServer $volume
}
#------------- Get and Create netapp iGroup
function global:get-iGroup-Info ($NaServer, $iGroupPattern='.*'){
$naelement = New-Object netapp.manage.naelement("igroup-list-info")
$iGroups = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'initiator-groups'.'initiator-group-info'
$iGroups| ?{$_.'initiator-group-name' -match $iGroupPattern}| Sort-Object 'initiator-group-name'
}
function global:Create-iGroup ($NaServer, $iGroupName, $IType="iscsi", $osType = "hyper_v"){
$naelement = New-Object netapp.manage.naelement("igroup-create")
$NaElement.AddNewChild('initiator-group-name',$iGroupName)
$NaElement.AddNewChild('initiator-group-type',$IType)
$NaElement.AddNewChild('os-type',$osType)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:add-iGroup ($NaServer, $iGroup, $IQN){
$NaElement = New-Object netapp.manage.naelement("igroup-add")
$NaElement.AddNewChild('initiator', $IQN)
$NaElement.AddNewChild('initiator-group-name', $iGroup)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:copy-iGroups ($NaServerSource, $NaServerDest, $iGroupPattern = ".*"){
$iGroups = get-iGroup-Info $NaServerSource $iGroupPattern
foreach ($iGroup in $iGroups){
"Creating iGroup $($iGroup.'initiator-group-name')"
Create-iGroup $NaServerDest $iGroup.'initiator-group-name' $iGroup.'initiator-group-type' $iGroup.'initiator-group-os-type'
foreach ($initiator in $iGroup.initiators.'initiator-info'){
"Adding IQN/WWPN: $($initiator.'initiator-name')"
add-iGroup $NaServerDest $iGroup.'initiator-group-name' $initiator.'initiator-name'
}
}
}
#------------- Volume Functions
function global:offline-volume ($NaServer, $vol){
$NaElement = New-Object netapp.manage.naelement("volume-offline")
$NaElement.AddNewChild('name', $Vol)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:online-volume ($NaServer, $vol){
$NaElement = New-Object netapp.manage.naelement("volume-online")
$NaElement.AddNewChild('name', $Vol)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:Rename-volume ($NaServer, $vol, $NewName){
$NaElement = New-Object netapp.manage.naelement("volume-rename")
$NaElement.AddNewChild('volume', $Vol)
$NaElement.AddNewChild('new-volume-name', $NewName)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
#------------- SnapMirror Functions
function global:get-SnapMirror-Destinations ($NaServer, $SourceLocations='.*'){ #point this at source filer
$naelement = New-Object netapp.manage.naelement("snapmirror-list-destinations")
$Destinations = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'destinations'.'destination-info'
$Destinations| ?{$_.'source-location' -match $SourceLocations}
}
function global:Quiesce-Snapmirror ($NaServer, $SnapVol){#point this at dest filer
$NaElement = New-Object netapp.manage.naelement("snapmirror-quiesce")
$NaElement.AddNewChild('destination-location', $SnapVol)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:Break-SnapMirror ($NaServer, $SnapVol){#point this at dest filer
$NaElement = New-Object netapp.manage.naelement("snapmirror-break")
$NaElement.AddNewChild('destination-location', $SnapVol)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:Update-Snapmirror ($NaServer, $SnapMirror){#point this at dest filer
$NaElement = New-Object netapp.manage.naelement("snapmirror-update")
$NaElement.AddNewChild('destination-location', $SnapMirror)
([xml]($NaServer.invokeelem($naelement)).tostring()).results.status
}
function global:ReSync-Snapmirror ($NaServer, $SnapMirror){#point this at dest filer
$NaElement = New-Object netapp.manage.naelement("snapmirror-resync")
$NaElement.AddNewChild('destination-location', $SnapMirror)
([xml]($NaServer.invokeelem($naelement)).tostring()).results.status
}
function global:Get-SnapMirrorInfo ($NaServer, $SnapMirror){#point this at either filer
$NaElement = New-Object netapp.manage.naelement("snapmirror-get-status")
$NaElement.AddNewChild('location', $SnapMirror)
([xml]($NaServer.invokeelem($naelement)).tostring()).results.'snapmirror-status'.'snapmirror-status-info'
}
function global:Wait-Snapmirror-Idle ($NaServer, $SnapMirror){
$Timeout = 600
$Status = 0
while ($Timeout -ge 0 -and $Status -ne 'Idle')
{
$Status = (Get-SnapmirrorInfo $NaServer $SnapMirror).status
"$Timeout $Status"
start-sleep 1
$Timeout = $Timeout - 1
}
}
#------------- SAN Migration Functions using snapmirror (vol and qtree)
function global:Failover-ClusterGroup ($NaServerSource, $NaServerDest, $SourceVolPath, $ClusterName, $ClusterResGrp, $ClusterNodeDR){
$SnapVol = get-SnapMirror-Destinations $NaServerSource $SourceVolPath
$DestVolPath = $Snapvol.'destination-location'
"Updateing Snap Mirror $NaServerDest $DestVolPath"
Update-Snapmirror $NaServerDest $DestVolPath
Wait-Snapmirror-Idle $NaServerDest $DestVolPath
"Offlineing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /off"
cmd /c "Cluster.exe $ClusterName group $ClusterResGrp /off"
"Updateing Snap Mirror $NaServerDest $DestVolPath"
Update-Snapmirror $NaServerDest $DestVolPath
Wait-Snapmirror-Idle $NaServerDest $DestVolPath
"Quiesce Snap Mirror $NaServerDest $DestVolPath"
Quiesce-Snapmirror $NaServerDest $DestVolPath
Wait-Snapmirror-Idle $NaServerDest $DestVolPath
"Breaking Snapmirror $NaServerDest $DestVolPath"
Break-SnapMirror $NaServerDest $DestVolPath
Wait-Snapmirror-Idle $NaServerDest $DestVolPath
"Takeing Lun $NaServerSource $SourceVolPath offline"
$LUN = get-Lun-Info $NaServerSource $SourceVolPath
offline-LUN $NaServerSource $LUN.path
"Moveing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /move:$ClusterNodeDR"
cmd /c "Cluster $ClusterName group $ClusterResGrp /move:$ClusterNodeDR"
"Onlineing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /on"
cmd /c "Cluster $ClusterName group $ClusterResGrp /on"
}
function global:FailBack-ClusterGroup ($NaServerSource, $NaServerDest, $SourceVolPath, $ClusterName, $ClusterResGrp, $ClusterNodeDR){
"Takeing Lun $NaServerSource $SourceVolPath online"
$LUN = get-Lun-Info $NaServerSource $SourceVolPath
online-LUN $NaServerSource $LUN.path
"Offlineing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /off"
cmd /c "Cluster.exe $ClusterName group $ClusterResGrp /off"
"Moveing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /move:$ClusterNodeDR"
cmd /c "Cluster $ClusterName group $ClusterResGrp /move:$ClusterNodeDR"
"Onlineing Cluster Group $ClusterResGrp with command :Cluster $ClusterName group $ClusterResGrp /on"
cmd /c "Cluster $ClusterName group $ClusterResGrp /on"
$SnapVol = get-SnapMirror-Destinations $NaServerSource $SourceVolPath
$DestVolPath = $Snapvol.'destination-location'
"ReSyncing Snapmirror $NaServerDest $DestVolPath"
ReSync-SnapMirror $NaServerDest $DestVolPath
Wait-Snapmirror-Idle $NaServerDest $DestVolPath
}
function global:Migrate-SnapMirror ($NaServerSource, $NaServerDest, $SourceLocations='.*'){
$SnapVols = get-SnapMirror-Destinations $NaServerSource $SourceLocations
"The following items will be migrated from the source to the destination"
$SnapVols
""
if ($SnapVols){
Foreach($SnapVol in $SnapVols){
"Quiesce $($SnapVol.'destination-location')"
Quiesce-Snapmirror $NaServerDest $SnapVol.'destination-location'
"Break $($SnapVol.'destination-location')"
Break-SnapMirror $NaServerDest $SnapVol.'destination-location'
"Finding LUN Mappings for $(([regex]::Match($SnapVol.'source-location',"(?<=.*?:).*").value)):"
$LUNs = Get-LUN-Map $NaServerSource ([regex]::Match($SnapVol.'source-location',"(?<=.*?:).*").value).tostring()
if ($LUNs) {
$VolName = [regex]::match($SnapVol.'source-location',"(?<=.*:/vol/).*(?=/.*)|(?<=.*:)[\\w\\d_]+")
"Rename old vol: $VolName -> $('Old_'+$VolName)"
Rename-volume $NaServerSource $VolName ("Old_"+$VolName)
"Offlining volume: $('Old_'+$VolName)"
offline-volume $NaServerSource ("Old_"+$VolName)
}
foreach ($LUN in $LUNs){
$LunName = [regex]::Match($LUN.path,".*/(?<LUN>.*)").groups[1].value
$DestLun = [regex]::Match($SnapVol.'destination-location',"(?<=.*?:).*").value + '/' + $LunName
if ($DestLun -notmatch "^/vol/"){
"Snap Vol must have /vol/ added to lun path: $destLun -> $('/vol/' + $DestLun)"
$DestLun = '/vol/' + $DestLun}
"Copy $($LUN.path): $($LUN.'initiator-group-name')($($LUN.'lun-id')) -> to $DestLun"
Map-Lun $NaServerDest $DestLun $LUN.'initiator-group-name' $LUN.'lun-id'
}
$VolName = [regex]::match($SnapVol.'destination-location',"(?<=.*:/vol/).*(?=/.*)|(?<=.*:)[\\w\\d_]+")
#"Online Volume: $VolName"
#online-volume $NaServerDest $VolName
#foreach ($LUN in $LUNs){
#$LunName = [regex]::Match($LUN.path,".*/(?<LUN>.*)").groups[1].value
#$DestLun = [regex]::Match($SnapVol.'destination-location',"(?<=.*?:).*").value + '/' + $LunName
#"Online LUN: $DestLun"
#online-lun $NaServerDest $DestLun
#}
if ($VolName -match "^New_"){
$VolNameNew = [regex]::Replace($VolName, "^New_","")
"Renaming new volume:$VolName -> $VolNameNew"
Rename-volume $NaServerDest $VolName $VolNameNew
}
}
}
}
|
PowerShellCorpus/PoshCode/HEX string to SID string.ps1
|
HEX string to SID string.ps1
|
Function EndianReverse ($strHex)
{
$intCounter=$strHex.length-1
do
{
$reverse=$reverse+$strHex.substring($intCounter-1, 2)
$intCounter=$intCounter-2
}
until ($intCounter -eq -1)
return $reverse
}
Function hex2sid ($strHex)
{
$intSidVersionLength = 2
$intSubAuthorityCountLength = 2
$intAuthorityIdentifierLength = 12
$intSubAuthorityLength = 8
$intStringPosition = 0
$bytSidVersion = [byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSidVersionLength),16)
$intStringPosition = $intStringPosition + $intSidVersionLength
$bytSubAuthorityCount=[byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSubAuthorityCountLength),16)
$intStringPosition = $intStringPosition + $intSubAuthorityCountLength
$lngAuthorityIdentifier=[long][convert]::ToInt32($strHex.substring($intStringPosition, $intAuthorityIdentifierLength),16)
$intStringPosition = $intStringPosition + $intAuthorityIdentifierLength
[string]$ConvertHexStringToSidString = "S-" + $bytSidVersion + "-" + $lngAuthorityIdentifier
Do
{
$lngTempSubAuthority = EndianReverse($strHex.substring($intStringPosition, $intSubAuthorityLength))
$lngTempSubAuthority = [long][convert]::ToInt32($lngTempSubAuthority,16)
$intStringPosition = $intStringPosition + $intSubAuthorityLength
if ($lngTempSubAuthority -lt 0)
{
$lngTempSubAuthority = $lngTempSubAuthority + 4294967296
}
$ConvertHexStringToSidString = $ConvertHexStringToSidString+"-"+$lngTempSubAuthority
$bytSubAuthorityCount = $bytSubAuthorityCount - 1
}
until ($bytSubAuthorityCount -eq 0)
return $ConvertHexStringToSidString
}
|
PowerShellCorpus/PoshCode/Product key_3.ps1
|
Product key_3.ps1
|
from System import Array, Char, Console
from System.Collections import ArrayList
from Microsoft.Win32 import Registry
def DecodeProductKey(digitalProductID):
map = ("BCDFGHJKMPQRTVWXY2346789").ToCharArray()
key = Array.CreateInstance(Char, 29)
raw = ArrayList()
i = 52
while i < 67:
raw.Add(digitalProductID[i])
i += 1
i = 28
while i >= 0:
if (i + 1) % 6 == 0:
key[i] = '-'
else:
k = 0
j = 14
while j >= 0:
k = (k * 256) ^ raw[j]
raw[j] = (k / 24)
k %= 24
key[i] = map[k]
j -= 1
i -= 1
return key
reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
val = reg.GetValue("DigitalProductId")
Console.WriteLine(DecodeProductKey(val))
|
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP2)_1.ps1
|
Set-Wallpaper (CTP2)_1.ps1
|
#requires -version 2.0
## Set-Wallpaper - set your windows desktop wallpaper
###################################################################################################
## Usage:
## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Wallpaper\\Dual Monitor\\mandolux-tiger.jpg" "Tile"
## ls *.jpg | get-random | Set-Wallpaper
## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch"
###################################################################################################
## History:
## v0.5 First release (on #PowerShell@irc.freenode.net)
## v1.0 Public release (http://www.poshcode.org/488)
## - Added Style: Tile|Center|Stretch
## v1.1 This Release
## - Added "NoChange" style to just use the style setting already set
## - Made the Style parameter to the cmdlet optional
###################################################################################################
add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tile, Center, Stretch, NoChange
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tile :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.NoChange :
break;
}
key.Close();
}
}
}
"@
cmdlet Set-Wallpaper {
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
[Wallpaper.Style]
$Style = "NoChange"
)
[Wallpaper.Setter]::SetWallpaper( (Convert-Path $Path), $Style )
}
|
PowerShellCorpus/PoshCode/Test-ADCredentials_1.ps1
|
Test-ADCredentials_1.ps1
|
Function Test-ADCredentials {
Param($username, $password, $domain)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct, $domain)
New-Object PSObject -Property @{
UserName = $username;
IsValid = $pc.ValidateCredentials($username, $password).ToString()
}
}
|
PowerShellCorpus/PoshCode/The PowerShell Talk Xen_1.ps1
|
The PowerShell Talk Xen_1.ps1
|
#The PowerShell Talk
#Demo 2 - VM Easy Bake Oven
#XenServer
#Connect to XenServer
Get-Credential | connect-Xenserver -Url http://XenServer_URL/sdk
#Create the new VM
Create-XenServer:VM -NameLabel "Dave" -VCPUsAtStartup 1 -MemoryDynamicMax 536870912 -MemoryStaticMax 536870912 -MemoryDynamicMin 536870912 -MemoryStaticMin 536870912 -MemoryTarget 536870912
#Get some info on said VM
Get-XenServer:VM -name "Dave" | fl * | more
#Change the Memory
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryDynamicMax -DynamicMax 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryDynamicMin -DynamicMin 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryStaticmin -StaticMin 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryStaticMax -Value 268435456
#Delete the VM
Get-XenServer:vm -name "Dave" | Destroy-XenServer:VM
|
PowerShellCorpus/PoshCode/Get-APOD.ps1
|
Get-APOD.ps1
|
<#
.SYNOPSIS
Gets the Astronomy Picture of the Day and sets it as your wallpaper.
.DESCRIPTION
Get-Apod parses the Astronomy Picture of the Day website and downloads the current day's image. It then sets the image as the desktop wallpaper for the system.
.LINK
http://antwrp.gsfc.nasa.gov/apod/astropix.html
.EXAMPLE
C:PS> Get-Apod.ps1
This example downloads the image and sets it as the desktop wallpaper.
.EXAMPLE
c:PS> Get-Apod.ps1 C:\\Images
This example also downloads the image and sets it as the desktop wallpaper, but it allows you to choose the folder to download the pictures to.
.PARAMETER Folder
The folder were you want to download the pictures to.
.NOTES
Name: Get-APOD.ps1
Author: Mark E. Schill
Date Created: 12/24/2008
Date Revised: 01/17/2010
Version: 1.1
History: 1.1 01/17/2010 - Updated Help information
1.0 12/24/2008 - Initial Revision
#requires -Version 2.0
** Licensed under a Creative Commons Attribution 3.0 License **
#>
[CmdletBinding(SupportsShouldProcess=$False)]
param
(
[Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$false)]
[String]$Folder = ((Get-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" -Name "My Pictures")."My Pictures" )
)
add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tiled, Centered, Stretched, Fit
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretched :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Centered :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tiled :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.Fit :
key.SetValue(@"WallpaperStyle", "6") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
}
key.Close();
}
}
}
"@
if ( ! (Test-Path -path "$Folder\\APODImages")) { mkdir $Folder\\APODImages | Out-Null }
$Web = New-Object System.Net.WebClient
$Page = $Web.DownloadString("http://antwrp.gsfc.nasa.gov/apod/astropix.html")
$Text = $Page.Replace("`n","")
$RegEx = [regex]'<a href="image/(?<URL>.*?)">'
$Text -match $RegEx | Out-Null
$URL = $Matches['URL']
$FileName = $Folder + "\\APODImages\\" + ($URL -split "/" | Select-Object -Last 1)
$Address = "http://antwrp.gsfc.nasa.gov/image/" + $URL
$Web.DownloadFile( $Address, $FileName )
[Wallpaper.Setter]::SetWallpaper( (Convert-Path $FileName), "Fit" )
$RegEx = [regex]'<b> Explanation: </b>(?<Text>.*?)<hr>'
$Text -match $Regex | Out-Null
$APODText = $Matches['Text']
# SIG # Begin signature block
# MIIQnAYJKoZIhvcNAQcCoIIQjTCCEIkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU+XG80NiXEeCxqMHAbaF+onXu
# SV2ggg3RMIIGwzCCBaugAwIBAgICAJYwDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNV
# BAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUg
# RGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMTgwNgYDVQQDEy9TdGFydENvbSBD
# bGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVjdCBDQTAeFw0xMDAxMTYy
# MTMxNTVaFw0xMjAxMTgxMDU1MzZaMIHAMSAwHgYDVQQNExcxMjk1MzItNFBoT1Bq
# N1dRZVd4T2RaOTELMAkGA1UEBhMCVVMxEDAOBgNVBAgTB0dlb3JnaWExDzANBgNV
# BAcTBkR1bHV0aDEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRQwEgYDVQQDEwtNYXJrIFNjaGlsbDEnMCUGCSqGSIb3DQEJARYY
# TWFyay5TY2hpbGxAY21zY2hpbGwubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
# MIIBCgKCAQEAyRfyMAfNacizoi0sN5/GWBClZpRAG9V9Sgvy+n+Hpak5JXIQBPH/
# INKyTNRriH8zyRuptwRhrTle0+IULgEZa1U3RpyaQ/mOYc3dJwvIcw/wqEisJPAm
# ZGfY+sMANnwLO4ZJsAFIsvXsqrbhmOoO+D7foB3RLiOoakoDELfR5BIonsoujOcF
# bftkjhtCaWpX65sJ/obK5A+fiEdSpWDqnm+QgG741zfCL+IKIrgQi2hPGuL0ukx5
# k7dr0xxf/ezU8dI41Ssdcadz1X4g4kPnNuddBU94ajgXgMvX0VVER/dyuoQuL323
# zTM8UYgw1tgbJEcMbHA+sqanBk/G4wVEvQIDAQABo4IC9zCCAvMwCQYDVR0TBAIw
# ADAOBgNVHQ8BAf8EBAMCB4AwOgYDVR0lAQH/BDAwLgYIKwYBBQUHAwMGCisGAQQB
# gjcCARUGCisGAQQBgjcCARYGCisGAQQBgjcKAw0wHQYDVR0OBBYEFATHxBovkt2Q
# OkyTZjEZxJODI/i4MB8GA1UdIwQYMBaAFNBOD0CZbLhLGW87KLjg44gHNKq3MIIB
# QgYDVR0gBIIBOTCCATUwggExBgsrBgEEAYG1NwECATCCASAwLgYIKwYBBQUHAgEW
# Imh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwNAYIKwYBBQUHAgEW
# KGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVkaWF0ZS5wZGYwgbcGCCsG
# AQUFBwICMIGqMBQWDVN0YXJ0Q29tIEx0ZC4wAwIBARqBkUxpbWl0ZWQgTGlhYmls
# aXR5LCBzZWUgc2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFy
# dENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0
# IGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwYwYDVR0fBFwwWjAr
# oCmgJ4YlaHR0cDovL3d3dy5zdGFydHNzbC5jb20vY3J0YzItY3JsLmNybDAroCmg
# J4YlaHR0cDovL2NybC5zdGFydHNzbC5jb20vY3J0YzItY3JsLmNybDCBiQYIKwYB
# BQUHAQEEfTB7MDcGCCsGAQUFBzABhitodHRwOi8vb2NzcC5zdGFydHNzbC5jb20v
# c3ViL2NsYXNzMi9jb2RlL2NhMEAGCCsGAQUFBzAChjRodHRwOi8vd3d3LnN0YXJ0
# c3NsLmNvbS9jZXJ0cy9zdWIuY2xhc3MyLmNvZGUuY2EuY3J0MCMGA1UdEgQcMBqG
# GGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tLzANBgkqhkiG9w0BAQUFAAOCAQEAcu8P
# T2mlw3hedsFiiLj5pl9ix0gvwwztxaM9nug3fxzmmjlNtyxRSXHsyUX66eyZ2OZG
# //q2PT+lbZ/PBjWyYFM8Q1vh+1dFcKVBz6aOb356XS4NZR9Rjg7n4YXhoP1Ui074
# A85il9SJ5fZFzI04z20CsfU+3kslWWn2K9yL8ABjqk5avDHJ8FXEh48KAQFigh70
# hUwllY7CT2Vxk8lcuuC6yUAEu9PkkF5jgMVA2N0JmtmgX8gQBkSp6vPbAEbxXQ01
# c/ESTrfhhWmD84dJ8aZDo/x/KVqyyhFTk6NyDmcOAkvC3Kj3qMAz1l6cgQOVj4Kh
# gYCBagE3NHNI/982lzCCBwYwggTuoAMCAQICARUwDQYJKoZIhvcNAQEFBQAwfTEL
# MAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNl
# Y3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0
# Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA3MTAyNDIyMDE0NVoXDTEy
# MTAyNDIyMDE0NVowgYwxCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBM
# dGQuMSswKQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5n
# MTgwNgYDVQQDEy9TdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMojiyI1
# HpqgGzydSdA/DJc4Fim6+H2JW0VY74Rw7X4RTekUMatD400MUYFs8BUDSiQnVOX7
# SqDOTeGEoyHemTWr3EmuvzHFZ4QwEJvvB9x1qA9N9DVTsW44A/yIdx2ld/8/defZ
# 578sUBHJEWX6SQdin5Omh6ltyZ0r0Xvl1WUrnw1Qnv77cRkhMCgmja7C3PaW6FKG
# CAt6Ms1qFE2eufnNB+KWkfHPHiv5gvdeJgaOjdHUOddv25EnWnmPWGkKRrVv4f1v
# xZG0EU97AqbbS1ZSI55LmOK/fs76oU6D48XHw2BH/lw/FRpAKpXvAGvIUPjNahnU
# IwMnvDs21blDsO8CAwEAAaOCAn8wggJ7MAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQD
# AgEGMB0GA1UdDgQWBBTQTg9AmWy4SxlvOyi44OOIBzSqtzCBqAYDVR0jBIGgMIGd
# gBROC+8apEBbpRdphzDKNGhD0EGu8qGBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYD
# VQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0
# aWZpY2F0ZSBTaWduaW5nMSkwJwYDVQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9u
# IEF1dGhvcml0eYIBATAJBgNVHRIEAjAAMD0GCCsGAQUFBwEBBDEwLzAtBggrBgEF
# BQcwAoYhaHR0cDovL3d3dy5zdGFydHNzbC5jb20vc2ZzY2EuY3J0MGAGA1UdHwRZ
# MFcwLKAqoCiGJmh0dHA6Ly9jZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3Js
# MCegJaAjhiFodHRwOi8vY3JsLnN0YXJ0c3NsLmNvbS9zZnNjYS5jcmwwgYIGA1Ud
# IAR7MHkwdwYLKwYBBAGBtTcBAQUwaDAvBggrBgEFBQcCARYjaHR0cDovL2NlcnQu
# c3RhcnRjb20ub3JnL3BvbGljeS5wZGYwNQYIKwYBBQUHAgEWKWh0dHA6Ly9jZXJ0
# LnN0YXJ0Y29tLm9yZy9pbnRlcm1lZGlhdGUucGRmMBEGCWCGSAGG+EIBAQQEAwIA
# ATBQBglghkgBhvhCAQ0EQxZBU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVy
# bWVkaWF0ZSBPYmplY3QgU2lnbmluZyBDZXJ0aWZpY2F0ZXMwDQYJKoZIhvcNAQEF
# BQADggIBAFCi0Jj0cEBwALZu7JaNNX17oDcaf4EyWN/miIYbPBqIPiMCLE++UNZC
# 7J531EH2xaZf1K5QdNhUEjmfuA59kvZe3sF0ISF8LbsCokINzXQ/bbgPDobt3mNX
# D5e3jmmOEKr6ko/Pjpe39GaeqkxokWcQr/2jTyG6dL96w/RnYRrT7yi0UtAqioLB
# 9p8HqL5OIX140UI6eTeT53wVtV9gwkk6po8HloZZXkNig4Pd1utU8OjOshiQBhtx
# p828GnRfQVFvPFnEbJzlhyLteO92zSgZ39TiscQENf91sCRmVieVMYQqQPsK/pfj
# Wxz+ceV2efMYYcbu1kO68CA4/Hf5RlPQOhGnl79zcMHGyKP2qLub/cvePpXgGKq/
# G2wTQBU19aU8UCcpX7Cq5AfBDiMfma5cGtFhN9gIMWioVgBoaPz4e3elF1Ep+W8N
# vrrL4XZFuJ6VKMQJN0YU9/p7qYtX4nODRu4kBvOD2dm20uWMTpmiCLCAMXJX9uRc
# LLFo4njMFdJPdZ5c1BQdR0DLhOk7qwGpEu7ZyCkyfmViQQ3blG3A9dPeF9/DrzDv
# /vh+UuOSot6/9d2E5tAFhjrzBZBABfC27hMnnCk2iTE4jUXwRjIJ6hgX6ojp88cU
# VTTsNoUkKdAfgvSI/6t++c94gCGAmylHf+UkhC3JpS5fgbjZJ1xNMYICNTCCAjEC
# AQEwgZMwgYwxCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMTgwNgYD
# VQQDEy9TdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVj
# dCBDQQICAJYwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAw
# GQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisG
# AQQBgjcCARYwIwYJKoZIhvcNAQkEMRYEFIBSURg8jh7j6tgSUPUspK1aMN0NMA0G
# CSqGSIb3DQEBAQUABIIBABUAuvWkNzcvSxxVs4uBjHp5PlV1I/uSAELiYAIPfdjI
# ctHKls5XEPdcA9fKjHWE5hGDbwLcBIvQF7IKICsZ7zsYQI7QgKY9jkV/PbSX6BF0
# MueOQHVYJ3c+u0d+sbgv340kRnhAnMrLj8DSwUentrFFX59BoPoUECpN9lVDrGx3
# nYdm/SWp4/TbISDBplsjIO1iXKerq3cnSdddXyGf7pj00ZtWhLTCGXbdXIwFmLAa
# hBlH7EVhdQWGy2gbzXRUL00IuwQaYOBzeEF+VyRVgA/t8yX2xckDBIVpw68GHT9m
# iL54PtC22Wv0FA0AOxY5L5zPVdxIQ7HnQbQUrMlmaaM=
# SIG # End signature block
|
PowerShellCorpus/PoshCode/353941de-a44d-4d1b-a022-bffae3d94ed3.ps1
|
353941de-a44d-4d1b-a022-bffae3d94ed3.ps1
|
function Select-Alive {param( [object]$InputObject,
[string]$Property,
[int32]$Requests = 3)
PROCESS {
if ($InputObject -eq $null) {$In = $_} else {$In = $InputObject}
if ($In.GetType().Name -eq "String") {
$HostName = $In
}
elseif (($In | Get-Member | Where-Object {$In.Name -eq $Property}) -ne $null) {
$HostName = $In.$Property
} else {return $null}
for ($i = 1; $i -le $Requests; $i++) {
$Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'"
Start-Sleep -Seconds 1
if ($Result.StatusCode -ne 0) {return $null}
}
return $In
}
}
|
PowerShellCorpus/PoshCode/IE Proxy Toggle (Silent)_2.ps1
|
IE Proxy Toggle (Silent)_2.ps1
|
# Process command line parameter (if present).
[bool] $DISABLE_PROXY = $false;
foreach ($param in $MyInvocation.UnboundArguments) {
if ($param -like 'disable') { $DISABLE_PROXY = $true; }
}
# Apply/refresh the organization's default proxy settings.
[string] $proxyServer = '###.###.###.###:####';
[string] $proxyOverride = '*.local;192.168.*;<local>';
[int] $migrateProxy = 1;
[int] $proxyHttp11 = 1;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyServer"" /t REG_SZ /d ""$proxyServer"" /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyOverride"" /t REG_SZ /d ""$proxyOverride"" /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""MigrateProxy"" /t REG_DWORD /d $migrateProxy /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyHttp1.1"" /t REG_DWORD /d $proxyHttp11 /f" | Out-Null;
<#
Define a function to start a 'hidden' Internet Explorer process.
This is needed since there is no easy way to programmatically 'refresh'
the user's proxy settings after they have been changed in the registry.
#>
function Start-HiddenIEProcess () {
[object] $ieProcess = $null;
# Launch Internet Explorer (use 32-bit version only) in a hidden window.
if (Test-Path "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe") {
$ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden;
} else {
$ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden;
}
# Wait for Internet Explorer to load fully.
[int] $count = 10;
do {
if (($ieProcess.WaitForInputIdle())) {
$waiting = $false; # IE is ready.
$count = 0;
} else {
Start-Sleep 1; # Sleep for another second.
$count--; # Decrement wait counter.
}
} while ($waiting -or ($count -gt 0));
# Check to see if our new process exists.
if ((Get-Process -Name iexplore -ErrorAction SilentlyContinue)) {
return $true;
} else {
return $false;
}
} # END
<#
Define a function to toggle the user's proxy settings by altering the
required registry entry and then forcing a 'refresh' of the proxy status
by utilizing a hidden/temporary Internet Explorer process.
#>
function Set-ProxyState ([bool] $disable) {
# Kill existing IE processes.
Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue;
# Toggle proxy state.
if ($disable) {
Write-Host 'DISABLING user''s proxy settings...';
REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 0 /f' | Out-Null; # Disable proxy.
} else {
Write-Host 'ENABLING user''s proxy settings...';
REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 1 /f' | Out-Null; # Enable proxy.
}
# Start a new/hidden IE process temporarily.
Start-HiddenIEProcess;
# Kill existing IE processes.
Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue;
Write-Host '[DONE]';
return $null;
} # END
# Toggle the user's proxy settings.
$null = Set-ProxyState $DISABLE_PROXY;
|
PowerShellCorpus/PoshCode/Enable-MailboxJunkEmail.ps1
|
Enable-MailboxJunkEmail.ps1
|
# Author: Jon Webster
# Name: Enable-MailboxJunkEmail
# Created: 1/27/2009
#
# Version: 1.0
# History: 1.0 01/27/2009 Initial version
#
# 18.11.2010 BRF Update for Microsoft Exchange SP3, Cookie Canary
param(
$Identity,
[string]$CasURL,
[string]$User,
[string]$Password,
$DomainController,
[switch]$help
)
BEGIN
{
Function Usage
{
Write-Host @'
Enable Server Side Junk E-mail filtering through Outlook Web Access
`n
Usage:
Enable-MailboxJunkEmail -Identity <string> -CasURL <string> -User <string> -Password <string> -DomainController <string>
`n
Parameters:
Identity: The Identity of mailbox who's server side Junk E-mail you want to enable.
CasURL: The (OWA) Client Access Server Address of the exchange server you want to use.
User: The fullaccess user's 'username' connecting to the mailbox that you want to change.
Password: The fullaccess user's 'password' connecting to the mailbox that you want to change.
DomainController: The fully qualified domain name (FQDN) of the domain controller that you want to use.
`n
Example:
Enable-MailboxJunkEmail -Identity "john.doe@consoto.com" -CasURL "mail.consoto.com" -User "CONSOTO\\Administrator" -Password "AdminPassword!"
'@
}
if($help -or $args -contains "-?")
{
Usage
return
}
Function ValidateParams
{
# These required parameters are not passed via pipeline
# $Identity
$ErrorMessage = ""
if(!$CasURL) {
$ErrorMessage += "Missing parameter: The -CasURL parameter is required. Please pass a valid Client Access Server Url`n"
}
if(!$User) {
$ErrorMessage += "Missing parameter: The -User parameter is required. Please pass a valid Username for OWA mailbox authentication`n"
}
if(!$Password) {
$ErrorMessage += "Missing parameter: The -Password parameter is required. Please pass a valid password for OWA mailbox authentication`n"
}
if($ErrorMessage)
{
throw $ErrorMessage
break
}
}
Function ValidatePipeline
{
if($_)
{
$ErrorMessage = ""
if(!$_.Identity)
{
$ErrorMessage += "Missing Pipeline property: The Identity property is required."
} else {
Set-Variable -Name Identity -Scope 1 -Value $_.Identity
}
if($ErrorMessage)
{
throw $ErrorMessage
break
}
}
}
Function UpdateJunk
{
param ([string]$mbMailbox,
[string]$CanaryNumber)
Write-Debug $mbMailbox
Write-Debug $CanaryNumber
$xmlstr = "<params><canary>" + $CanaryNumber + "</canary><fEnbl>1</fEnbl></params>" #Zwingend für SP3
#$xmlstr = "<params><fEnbl>1</fEnbl></params>" # Bei SP2 noch gültig
Write-Debug $xmlstr
$req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/ev.owa?oeh=1&ns=JunkEmail&ev=Enable", $False)
$req.setRequestHeader("Content-Type", "text/xml; charset=""UTF-8""")
$req.setRequestHeader("Content-Length", $xmlstr.Length)
$req.Send($xmlstr)
Write-Debug $req.status
Write-Debug $req.GetAllResponseHeaders()
if($req.status -ne 200)
{
Write-Error $req.responsetext
return
}
if($req.responsetext -match "name=lngFrm")
{
Write-Host "Mailbox has not been logged onto before via OWA"
$pattern = "<option selected value=""(.*?)"">"
$matches = [regex]::Matches($req.responsetext,$pattern)
if($matches.count -eq 2)
{
$lcidarry = $matches[0].Groups[1].Value
Write-Debug $lcidarry
$tzidarry = $matches[1].Groups[1].Value
Write-Debug $tzidarry
$pstring = "lcid=" + $lcidarry + "&tzid=" + $tzidarry
$req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/lang.owa", $False)
$req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
$req.setRequestHeader("Content-Length", $pstring.Length)
# not required?
#$req.setRequestHeader("cookie", $reqCadata) # Error here
$req.send($pstring)
if($req.responsetext -match "errMsg")
{
# Permission Error
Write-Error "Authentication Error"
} else {
Write-Debug $req.status
if($req.status -eq 200 -and $req.responsetext -notmatch "errMsg")
{
Write-Host "Trying to update the Junk E-mail setting again."
UpdateJunk($mbMailbox)
Write-Host "Removing OWA Language and Timezone settings..."
&{
# We'll get a warning if no properties were modified.
# That warning means replication hasn't occurred yet.
$warningPreference = "Stop"
$script:count = 0
$loop = $true
while($loop)
{
$loop = $false
Set-Mailbox $mbMailbox -Languages $null -DomainController $DomainController
trap {
if($script:count -lt 5)
{
# Try for up to 20 seconds
Write-Debug "Unable to Reset Languages trying again in 5 seconds."
Sleep 5
Set-Variable -Name loop -Scope 1 -Value $true
$script:count++
} else { Write-Debug "Failed." }
continue
}
}
$warningPreference = "Continue"
}
} else {
Write-Warning "Failed to set Default OWA settings"
}
}
} else {
Write-Warning "Script failed to retrieve default values"
}
Write-Host "Junk E-Mail setting Changed Successfully"
}
}
ValidateParams
}
PROCESS
{
ValidatePipeline
$mbx = Get-Mailbox -Identity $Identity -DomainController $DomainController -ErrorAction SilentlyContinue
if(!$mbx) {throw "Invalid Mailbox specified: $Identity"}
$szXml = "destination=https://" + $CasURL + "/owa/&flags=0&username=" + $User
$szXml = $szXml + "&password=" + $Password + "&SubmitCreds=Log On&forcedownlevel=0&trusted=0"
$req = New-Object -COMObject "MSXML2.ServerXMLHTTP.6.0"
$req.Open("POST", "https://" + $CasURL + "/owa/auth/owaauth.dll", $False)
$req.SetOption(2, 13056)
$req.Send($szXml)
Write-Debug $req.GetAllResponseHeaders()
if($req.responsetext -match "wrng")
{
Write-Error "The user name or password that you entered is not valid. Try entering it again."
return;
}
#Modifikation für Exchange SP3 Canary muss ermittelt werden
$req.Open("GET", "https://" + $CasURL + "/owa/" + $mbx.PrimarySMTPAddress +"", $False)
$req.SetOption(2, 13056)
$req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
$req.setRequestHeader("Content-Length", $szXml.Length)
$req.Send($szXml)
Write-Debug $req.GetAllResponseHeaders()
$cookie=$req.GetResponseHeader("Set-Cookie")
Write-Debug $cookie
$slen=$cookie.IndexOf("=")+1
$elen=$cookie.IndexOf("&")
$canary=$cookie.Substring($slen,$elen-$slen)
Write-Debug "CANARY: $canary"
#Modifikation
UpdateJunk -mbMailbox $mbx.PrimarySMTPAddress -CanaryNumber $canary
}
|
PowerShellCorpus/PoshCode/SCOM-CreatePortMonitor.ps1
|
SCOM-CreatePortMonitor.ps1
|
param($serverName,$portNumber,$pollIntervalSeconds,$watcherNodes,$displayName,$targetMp)
function GetPortMonitoringTemplate
{
$criteria = "Name = 'Microsoft.SystemCenter.SyntheticTransactions.TCPPortCheck.Template'";
$templateCriteria = new-object Microsoft.EnterpriseManagement.Configuration.MonitoringTemplateCriteria($criteria);
$template = (Get-ManagementGroupConnection).ManagementGroup.GetMonitoringTemplates($templateCriteria)[0];
$template;
}
function GetManagementPack([string]$mpDisplayName)
{
$criteria = [string]::Format("DisplayName = '{0}'", $mpDisplayName);
$mpCriteria = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackCriteria($criteria);
$mg = (Get-ManagementGroupConnection).ManagementGroup;
$mp = $mg.GetManagementPacks($mpCriteria)[0];
$mp;
}
function AddChildElement([System.Xml.XmlElement]$parentElement,[string]$newElementName,[string]$value)
{
$document = $parentElement.get_OwnerDocument();
$newElement = $document.CreateElement($newElementName);
$newElement.set_InnerText($value);
$parentElement.AppendChild($newElement);
}
function CreateWatcherComputerList($watcherNodes)
{
if($watcherNodes.Count -eq $null)
{
$watcherNodesList = $watcherNodes;
}
else
{
$watcherNodesString = ""
for($i = 0; $i -le $watcherNodes.Count; $i++)
{
$watcherNodesList += $watcherNodes[$i];
if($i -le ($watcherNodes.Count - 2))
{
$watcherNodesList += " | "
}
}
$watcherNodesList = [string]::Format("({0})",$watcherNodesList);
}
$watcherNodesList
}
function AddWatcherNodesIds([system.Xml.XmlElement]$rootNode,$watcherNodes)
{
$nodeIdsAdded = $true;
$doc = $rootNode.get_OwnerDocument();
$includeListElement = $doc.CreateElement("IncludeList");
$rootNode.AppendChild($includeListElement)
if($watcherNodes.Count -eq $null)
{
$computerMonitoringObject = GetComputerMonitoringObject $watcherNodes;
$computerMonitoringObject;
if($computerMonitoringObject -eq $null)
{
$watcherNodes + " not found";
$nodeIdsAdded = $false;
}
else
{
AddChildElement $includeListElement "MonitoringObjectId" $computerMonitoringObject.Id.ToString()
}
}
else
{
foreach($watcherNode in $watcherNodes)
{
$computerMonitoringObject = GetComputerMonitoringObject $watcherNode
if($computerMonitoringObject -eq $null)
{
$watcherNodes + " not found";
$nodeIdsAdded = $false;
}
else
{
AddChildElement $includeListElement "MonitoringObjectId" $computerMonitoringObject.Id.ToString()
}
}
}
}
function GetComputerMonitoringObject($computerFQDN)
{
$mg = (Get-ManagementGroupConnection).ManagementGroup;
$windowsComputerClass = Get-MonitoringClass -Name:"Microsoft.Windows.Computer"
$criteriaFormatString = "[Microsoft.Windows.Computer].[PrincipalName]='{0}'"
$criteriaString = [string]::Format($criteriaFormatString,$computerFQDN)
$criteria = new-object Microsoft.EnterpriseManagement.Monitoring.MonitoringObjectCriteria($criteriaString,$windowsComputerClass);
$monitoringObjects = $mg.GetMonitoringObjects($criteria);
$monitoringObjects[0];
}
$configDoc = new-object System.Xml.XmlDocument;
$rootNode = $configDoc.CreateElement("Configuration");
$configDoc.AppendChild($rootNode);
$typeId = [string]::Format("PortMonitoring_{0}", [System.Guid]::NewGuid().ToString("N"))
AddChildElement $rootNode "TypeId" $typeId
AddChildElement $rootNode "Name" $displayName
AddChildElement $rootNode "Description" ""
AddChildElement $rootNode "LocaleId" "ENU"
AddChildElement $rootNode "ServerName" $serverName
AddChildElement $rootNode "Port" $portNumber
AddChildElement $rootNode "PollIntervalInSeconds" $pollIntervalSeconds
AddWatcherNodesIds $rootNode $watcherNodes
$watcherNodesList = CreateWatcherComputerList $watcherNodes
AddChildElement $rootNode "WatcherComputersList" $watcherNodesList
$uniqueKey = [System.Guid]::NewGuid().ToString();
AddChildElement $rootNode "UniquenessKey" $uniqueKey
$template = GetPortMonitoringTemplate
$mp = GetManagementPack $targetMp
$configDoc.get_InnerXml()
$mp.ProcessMonitoringTemplate($template,$configDoc.get_InnerXml(),"PortMon" + [System.Guid]::NewGuid().ToString("N"),$displayName,"")
|
PowerShellCorpus/PoshCode/SSL Oblivious Web Client.ps1
|
SSL Oblivious Web Client.ps1
|
function New-TrustAllWebClient {
# Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy {
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
## The ESX Upload requires the Preauthenticate value to be true which is not the default
## for the System.Net.WebClient class which has very simple-to-use downloadFile and uploadfile
## methods. We create an override class which simply sets that Preauthenticate value.
## After creating an instance of the Local.ToolkitExtensions.Net.WebClient class, we use it just
## like the standard WebClient class.
$WCSource=@'
namespace Local.ToolkitExtensions.Net {
class WebClient : System.Net.WebClient {
protected override System.Net.WebRequest GetWebRequest(System.Uri uri) {
System.Net.WebRequest webRequest = base.GetWebRequest(uri);
webRequest.PreAuthenticate = true;
webRequest.Timeout = 10000;
return webRequest;
}
}
}
'@
$WCResults=$Provider.CompileAssemblyFromSource($Params,$WCSource)
$WCAssembly=$WCResults.CompiledAssembly
## Now return the custom WebClient. It behaves almost like a normal WebClient.
$WebClient=$WCAssembly.CreateInstance("Local.ToolkitExtensions.Net.WebClient")
return $WebClient
}
# Example of using this function to upload a file over SSL.
# Notice that the object you get back from New-TrustAllWebClient is almost identical
# to what you would get from new-object system.net.webclient.
# $wc = New-TrustAllWebClient
# $credential = get-credential
# $wc.set_Credentials($credential.GetNetworkCredential())
# $URL = "https://192.168.25.129/folder/VM%201/VM%201.vmx?dcPath=ha-datacenter&dsName=datastore1"
# $wc.UploadString($URL, "PUT", "Testing")
|
PowerShellCorpus/PoshCode/Get-Exception.ps1
|
Get-Exception.ps1
|
<#
.Synopsis
Outputs .NET exception information along with their summary information if available.
.Description
Spins all loaded types in all loaded assemblies and will return any Exception types that
match the filter if specified. Because the script only spins loaded assemblies, if you want
the script to search additional assemblies, you must load them yourself using
[System.Reflection.Assembly]::Load or related method.
.Notes
NAME: Get-Exception
AUTHOR: David Mohundro
URL: http://www.mohundro.com/blog/
#>
param (
$filter = ''
)
if ($filter -ne '') {
$filter = ".*$filter"
}
$exceptions = [System.AppDomain]::CurrentDomain.GetAssemblies() | foreach {
$_.GetTypes() | where { $_.FullName -match "System$filter.*Exception$" }
}
$exceptions | foreach {
$type = $_
$doc = $_.Assembly.Location.Replace("dll", "xml")
$summary = 'No summary found.'
if (Test-Path $doc) {
$xpath = "/doc/members/member[@name='T:$_']"
Write-Verbose "Found: $doc"
Write-Verbose "XPath to use is: $xpath"
$xml = [xml]$(Get-Content $doc)
$nodes = $xml.SelectNodes($xpath)
$nodes | foreach {
$summary = $_.summary
}
}
$result = New-Object PSObject
$result |
Add-Member NoteProperty Name $type.FullName -pass |
Add-Member NoteProperty Summary $summary
$result
}
|
PowerShellCorpus/PoshCode/VM Performance Report - .ps1
|
VM Performance Report - .ps1
|
<#
.SYNOPSIS
The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address.
.DESCRIPTION
The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3491) or run interactively.
.NOTES
File Name : Get-VMPeformanceReport.ps1
Author : Samuel Mulhearn
Version History:
Version 1.0
28 Jun 2012.
Release
Version 1.1
11 July 2012
Andy Helsby - Modified for US formatting of date and time
.LINK
http://poshcode.org/3494
.EXAMPLE
Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt>
#>
#Change These Values
$VC = "vc.domain.local" #VirtualCenter
$SMTPServer = "192.168.1.100" #SMTP Server
$SendersAddress = "noreply@domain.com" #The report comes from this address
$SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3491
$CompanyLogo = "http://placehold.it/150x50"
function Out-LogFile {
#Log File Function http://poshcode.org/3232
[CmdletBinding(DefaultParameterSetName='Message')]
param(
[Parameter(ParameterSetName='Message',
Position=0,
ValueFromPipeline=$true)]
[object[]]$Message,
[Parameter(ParameterSetName='Message')]
[string]$LogFile = $global:DefaultLogPath,
[Parameter(ParameterSetName='Message')]
[int]$BlankLine = 0,
[switch]$WriteHost = $global:WriteHostPreference,
[string]$Severity = "I",
[Parameter(ParameterSetName='Message')]
[switch]$DontFormat,
[Parameter(ParameterSetName='Message')]
[string]$DateFormat = "dd-MM-yyyy HH:mm:ss",
#[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)]
[string]$Title,
[System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor,
[System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor,
[ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')]
[string]$Encoding = 'Unicode',
[switch]$Force
)
begin {
Write-Verbose "Log File: $LogFile"
if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break}
if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break}
if ( $Title ) {
$text = $Title
$Title = $null
Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
}
}
process {
if ( $Message ) {
$text = $Message
foreach ( $text in $Message ) {
if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" }
if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor}
$text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
}
}
if ( $BlankLine -gt 0 ){
for ($i = 0; $i -lt $BlankLine; $i++ ) {
"" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor }
}
}
}
end {
}
}
#end of logfile function
#New Line Variable
$nl = [Environment]::NewLine
#INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential)
#NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3491), and retrive as below
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3491)
$VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3491
$VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key)
$VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password)
#Get Datafile, this wil contain VM's to report on, and an email address to send the report to
#Datafile format: first line is email address, subsequent lines are VM's, one per line)
if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error!
{ Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)"
#$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file
}
else
{ $Datafile = $args[0] }
#From Datafile, get a log file, and a
$LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log"
$Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm"
$global:WriteHostPreference = $true
$global:DefaultLogPath = $LogFile
Out-LogFile -Message "Starting script with $datafile"
#Load PowerCLI
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{ Add-PsSnapin VMware.VimAutomation.Core }
If (!(Get-PSSnapin -Name VMware.VimAutomation.Core))
{Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E"
Exit(1)
}
#Static HTML
$HTMLPreString=@"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css">
<style type="text/css">
body {
padding: 20px;
}
h2 {
color: #3A87AD;
}
.mytable {
width: 776px;
margin: 12px;
}
.alert-info {
color: #3A87AD;
background-color: #D9EDF7;
border-color: #BCE8F1;
padding: 8px 8px 8px 14px;
margin-top: 12px;
margin-left: 12px;
margin-right: 12px;
margin-bottom: 12px;
border: 1px solid;
border-radius: 4px;
}
.chart_wrap {
width: 800px;
border-style:solid;
border-width:1px;
border-color: #DDDDDD;
margin: 0px 0px 10px 0px;
}
.chart {
text-align: center;
width: 800px;
height: 400px;
}
</style>
<title>
Virtual Machine Performance statistics
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
"@
$HTMLPreString += "$nl"
$HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl"
$HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl"
$HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl"
$HTMLPostString=@"
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script>
</body>
</html>
"@
#Functions for dynamic HTML
Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title)
{
#https://developers.google.com/chart/interactive/docs/examples#custom_table_example
$mystring = "<script type=`"text/javascript`">$nl"
$mystring += "function drawVisualization$UID() {$nl"
$mystring += "// Create and populate the data table. $nl"
$mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl"
$mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl"
$VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"}
$mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl"
$ColumnCount = 0
$RowCount = 0
$Statistics | % {
$ColumnCount = 0
######Changed for US date format
######was $formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null)
@@ $formatteddate = [datetime]::ParseExact(([string]$_.Name),"M/d/yyyy h:mm:ss tt",$null)
$JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0)
$formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm")
$formatteddate = "new Date($formatteddate)"
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl"
$_.Group |
% {
$ColumnCount = 0
foreach ($VM in $VMs)
{
$ColumnCount += 1
If ($_.Entity.Name -eq $VM )
{ if ($Summation -eq $true)
{ $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181
$strPercent = [system.math]::round($strPercent,2)
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl"
}
else
{ $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" }
}
}
}
$RowCount += 1
}
$mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl"
$VisParam = "`
{ `
legend: {position: 'in',alignment:`"center`"}, `
lineWidth:`"2`", `
curveType: `"none`",`
chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},`
focusTarget:`"category`", `
hAxis: {slantedText:`"true`", format:`"E, d MMM`"},`
vAxis: {textPosition:`"out`"},`
width: 800, `
height: 400, `
title:`"$Title`"}"
$mystring += "draw(" + "$UID" + "data, $VisParam);$nl"
$mystring +="}$nl"
$mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl"
return $mystring
}
function Get-DivHTML ($UID, $Notes)
{
$tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl"
$tempHTML += " <div class=`"chart_wrap`">$nl"
$tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl"
$tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl"
$tempHTML += " </div>$nl"
$tempHTML += "</div>$nl"
return $tempHTML
}
#Main Code
#Process datafile, get VM's to report on, and an email address to send the report to
$DataTable = @(Get-Content $Datafile)
$email = $DataTable[0]
$VMs = @($DataTable[1..($DataTable.Count)])
#Connect to VC
Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null
if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails.
{ Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost
Exit (1)
}
else
{Out-LogFile -Message "Connected to vCenter ($VC)"}
#Validate VM's exist
$VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue)
$VMs | % {
$tmpvm = $_
$Exists = $false
$VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}}
If ($Exists){
Out-LogFile -Message "$_ found in vCenter inventory"
}
Else {
Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W"
$VMs = $VMs |? {$_ -ne $tmpvm}
}
}
#To add new Stat
#1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics)
#2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#3. Invent a new UID - MyUID ?
#4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title")
#5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li>
#6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart")
#Start and Finish times
$todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1)
$metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average"
$start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart
$finish = $todayMidnight
$startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm")
$finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm")
Out-LogFile -Message "Getting stats from vCenter"
#Variable for all stats combined
$Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average
Out-LogFile -Message "Got stats from vCenter"
Out-LogFile -Message "Sorting and filtering stats"
#Split stats out by each indivial metric into individual variable
$CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#Creates HTML inside of <head> for javascript for the charts
Out-LogFile -Message "Creating HTML"
$HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)")
$HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)")
$HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)")
$HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)")
$HTMLOut += "</head>$nl"
$HTMLOut += $HTMLBodyBegin + $nl
#Navigation Tabs...
#Edit below to add a tab, when adding a new metric
$HTMLOut += @"
<div id="content">
<ul class="nav nav-tabs">
<li class="active"><a href="#Info" data-toggle="tab">Information</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#CPU" data-toggle="tab">CPU Usage</a></li>
<li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#Memory" data-toggle="tab">Memory Usage</a></li>
<li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li>
</ul>
<li>
<li><a href="#Disk" data-toggle="tab">Disk</a></li>
<li><a href="#Net" data-toggle="tab">Network</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane fade in active" id="Info">
<div class="chart_wrap">
<div class="alert alert-info">
<strong>Information: </strong>
"@
#Info for fist tab
$HTMLOut += "Each datapoint represents resource consumption since the last datapoint `
and its value is either an average, maximum, or summation of all usage in that interval. `
Any values that are zero may actually be zero, or may indicate statistics were not `
collected over that period (for example, if a virtual machine was powered off). $nl `
The statistics displayed are from $startstring to $finishstring</div>$nl"
#Table that contains VM resource config & limits.
$HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl"
$VCVMs | % {
$tmpname =$_.Name
$tmpNumCpu = $_.NumCpu
$TmpMemoryMB = $_.MemoryMB
$tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None")
$tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None")
$HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl"
}
$HTMLOut += "</tbody></table>$nl"
$HTMLOut +=@"
</div>
</div>
"@
#Div elements that contain each chart
$HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval")
$HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory")
$HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps")
$HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval")
$HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal")
$HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0")
$HTMLOut += @"
</div>
</div>
</div>
"@
$datenow = Get-Date -Format "F"
$HTMLOut += "<h6>Report generated at $datenow<h6>$nl"
$HTMLOut += $HTMLPostString
#Finished HTML
Out-LogFile -Message "Finished building HTML, writing to $Outfile"
$HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8"
#Build Email
$body =@"
<P>Performance statistics for the Virtual Machines listed below are attached</p>
"@
$body += "<p>Statistics are from $startstring to $finishstring<p>"
$VMs | % {$body+= "<li>$_</li>" }
Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer"
#Send email
Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer
Disconnect-VIServer -Confirm:$false
Out-LogFile -Message "Disconnected from vCenter"
Out-LogFile -Message "Finished"
|
PowerShellCorpus/PoshCode/finddupe_8.ps1
|
finddupe_8.ps1
|
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$files=$null
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
for ($i=0;$i -ne $args.count; $i++)
{
if ($args[$i] -eq "-delete")
{
$del=$true;continue
}
else
{
if ($args[$i] -eq "-noprompt")
{
$noprompt=$true;continue
}
else
{
$files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true})
}
}
}
if ($files -eq $null) {write-host "No files found." -f red; exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$md5 = $null
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)}
if ($md5 -eq (get-md5 $files[$c]))
{
write-host "Size and MD5 match: " -fore red -nonewline
"{0} and {1}" -f $filecheck.fullname, $files[$c].fullname
$matches++
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname;write-host "$($files[$c].fullname) deleted." -f Red
}
else
{
del $files[$c].fullname -confirm
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $($matches)."
write-host ""
|
PowerShellCorpus/PoshCode/Exporting SQLData to CSV.ps1
|
Exporting SQLData to CSV.ps1
|
#Connection Strings
$Database = "Database"
$Server = "SQLServer"
#SMTP Relay Server
$SMTPServer = "smtp.domain.com"
#Export File
$AttachmentPath = "C:\\SQLData.csv"
# Connect to SQL and query data, extract data to SQL Adapter
$SqlQuery = "SELECT * FROM dbo.Test_Table"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$nRecs = $SqlAdapter.Fill($DataSet)
$nRecs | Out-Null
#Populate Hash Table
$objTable = $DataSet.Tables[0]
#Export Hash Table to CSV File
$objTable | Export-CSV $AttachmentPath
#Send SMTP Message
$Mailer = new-object Net.Mail.SMTPclient($SMTPServer)
$From = "email1@domain.com"
$To = "email2@domain.com"
$Subject = "Test Subject"
$Body = "Body Test"
$Msg = new-object Net.Mail.MailMessage($From,$To,$Subject,$Body)
$Msg.IsBodyHTML = $False
$Attachment = new-object Net.Mail.Attachment($AttachmentPath)
$Msg.attachments.add($Attachment)
$Mailer.send($Msg)
|
PowerShellCorpus/PoshCode/Tag-Alert (SCOM).ps1
|
Tag-Alert (SCOM).ps1
|
# Tags alert with PrincipalName, Severity and MP name in Custom fields.
# Use in OpsMgr Command Shell.
# Original script from Marco Shaw.
# Changed by Stefan Stranger
# Date created 13-09-2008
$alerts = get-alert | where {$_.principalname -ne $null -and $_.resolutionstate -eq "0"}
foreach($alert in $alerts)
{
$alert.CustomField1 = $alert.PrincipalName
$alert.CustomField2 = $alert.Severity
if ($alert.IsMonitorAlert -like 'False')
{
$alert.CustomField3 = ((get-rule $alert.monitoringruleid).getmanagementpack()).displayname
}
else
{
$alert.CustomField3 = ((get-monitor $alert.problemid).getmanagementpack()).displayname
}
$alert.Update("")
}
|
PowerShellCorpus/PoshCode/WPF PingMonitor for 2.0.ps1
|
WPF PingMonitor for 2.0.ps1
|
if(!(Get-Command New-BootsWindow -EA SilentlyContinue)) {
# Add-PsSnapin PoshWpf
Import-Module PowerBoots
Add-BootsContentProperty 'DataPoints', 'Series'
#[Void][Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll")) )
Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll"
Add-BootsFunction ([System.Windows.Threading.DispatcherTimer])
}
if(Get-Command Ping-Host -EA SilentlyContinue) {
$pingcmd = { (Ping-Host $args[0] -count 1 -Quiet).AverageTime }
} else {
$pingcmd = { [int]([regex]"time=(\\d+)ms").Match( (ping $args[0] -n 1) ).Groups[1].Value }
}
$global:onTick = {
$window = $this.Tag
# Invoke-BootsWindow $window {
try {
foreach($s in $window.Content.Series.GetEnumerator()) {
$ping = &$pingcmd $s.LegendText
$points = $s.DataPoints
foreach($dp in 0..$($points.Count - 1))
{
if(($dp+1) -eq $points.Count) {
$points[$dp].YValue = $ping
} else {
$points[$dp].YValue = $points[$dp+1].YValue
}
}
}
} catch {
Write-Output $_
}
# }
}
function Add-PingHost {
[CmdletBinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$true)]
[string[]]$target
,
[Parameter(Position=1)]
[Visifire.Charts.RenderAs]$renderAs="Line"
,
[Parameter(Position=2)]
[System.Windows.Window]$window = $global:pingWindow
,
[Parameter()]
[Switch]$Passthru
)
PROCESS {
if($Window) {
Invoke-BootsWindow $Window {
$target | Add-PingHostInternal -render $renderAs -window $window
}
return $Window
} else {
return New-PingMonitor -Hosts $target -RenderAs $renderAs
}
}
}
function Add-PingHostInternal {
[CmdletBinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$true)]
[string]$target
,
[Parameter(Position=1)]
[Visifire.Charts.RenderAs]$renderAs="Line"
,
[Parameter(Position=2)]
[System.Windows.Window]$window = $global:pingWindow
)
Process {
$start = $(get-random -min 10 -max 20)
$window.Content.Series.Add( $(
DataSeries { 1..25 | %{DataPoint -YValue $start} } -LegendText $target -RenderAs $renderAs
) )
}
}
function New-PingMonitor {
[CmdletBinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$true)]
[string[]]$hosts = $(Read-Host "Please enter the name of a computer to ping")
,
[Parameter(Position=1)]
[Visifire.Charts.RenderAs]$renderAs="Line"
,
[Parameter()]
[Switch]$Passthru
)
Process {
$script:renderAs = $renderAs
$script:Hosts = $Hosts
$global:pingWindow = New-BootsWindow -Async {
Param($window) # New-Boots passes the window to us ...
# Make a new scriptblock of the OnTick handle, passing it ourselves
# Make a timer, and stick it in the window....
$window.Tag = @((DispatcherTimer -Interval "00:00:01.0" -On_Tick $global:onTick -Tag $window), $global:onTick)
Chart {
foreach($h in $hosts) {
$script:start = get-random -min 10 -max 20
DataSeries {
foreach($i in 1..25) {
DataPoint -YValue $script:start
}
} -LegendText $h -RenderAs $renderAs
}
} -watermark $false
} -On_ContentRendered {
$this.tag[0].Start()
} -On_Closing {
$this.tag[0].Remove_Tick($this.tag[1])
$this.tag[0].Stop()
$global:pingWindow = $null
Remove-BootsWindow $this
} -Title "Ping Monitor" -Passthru -height 300 -width 800
if($Passthru) {
return $global:pingWindow
}
}
}
|
PowerShellCorpus/PoshCode/Boots Hierarchical Bind.ps1
|
Boots Hierarchical Bind.ps1
|
######## CSV DATA #############
# Save the following data to a csv.
City,Team
"Los Angeles","Lakers"
"Los Angeles","Clippers"
"New York","Knicks"
"New York","Liberty"
"Sacramento","Kings"
######## CODE #################
$teams = Import-Csv "C:\\testdata.csv"
[array]$cities = $teams | %{$_.City} | Sort -Unique
[Object[]]$test = foreach ($city in $cities){
New-Object psobject -Property @{
City = $city
Teams = @(foreach($team in $($teams | ?{$_.City -eq $city} | %{$_.Team} | Sort -Unique)){
New-Object psobject -Property @{
Team = $Team
IsSelected = "True"
}
})
}
}
Import-Module PowerBoots
# Xaml layout -- this is where binding is set.
$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window">
<Grid>
<TreeView Name="treeview1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Teams}">
<TextBlock Foreground="Green" Text="{Binding City}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Team}" />
<CheckBox IsChecked="{Binding IsSelected}" IsEnabled="False"/>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
"@
$MainWindow= New-BootsWindow -Title "Treeview Binding" -Width 100 -Height 150 -SourceTemplate $xaml -Async -Passthru -On_Loaded {
Export-NamedElement
$treeView1.ItemsSource = $test
}
|
PowerShellCorpus/PoshCode/Get-NaNfsExport.ps1
|
Get-NaNfsExport.ps1
|
# Glenn Sizemore ~ www . Get-Admin . Com
# Example Powershell function to get the NFS Exports from a NetApp Filer
# First you'll need to download the OnTap SDK 3.5 : http://communities.netapp.com/docs/DOC-1365
# within the download your interested in .\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll
# Next load the library...
# $Path = 'C:\\Users\\glnsize\\Downloads\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll'
# [Reflection.Assembly]::LoadFile($Path)
#
# Almost there next step create a NaServer connection object
# Here we are connecting to the NetApp Filer TOASTER1, and setting the api to V1.8
# $NaServer = New-Object NetApp.Manage.NaServer("TOASTER1",1,8)
# Call the setAdminUser Method and supply some credentials
# $NaServer.SetAdminUser('root', 'password')
#
# Now we're ready to go simply call the function passing your NAServer object as a parameter.
# Get-NaNfsExport -Server $NaServer
#
# Get-NaNfsExport -Server $NaServer -Path /vol/vol0
Function Get-NaNfsExport {
Param(
[NetApp.Manage.NaServer]
$Server,
[String]
$Path
)
Begin {
$out = @()
}
Process {
trap [NetApp.Manage.NaAuthException] {
# Example trap to catch bad credentials
Write-Error "Bad login/password".
break
}
#generate a new naelement request
$NaOut = New-Object NetApp.Manage.NaElement("nfs-exportfs-list-rules")
# $NaServer.InvokeElem($NaOut) -> retrieve the results of the $NaOut request
# ..($NaOut).GetChildByName("rules") -> select the rules element from results
# ..GetChildByName("rules").getchildren() -> get any child elements under rules.
$NaResults = $Server.InvokeElem($NaOut).GetChildByName("rules").getchildren()
#ForEach NFS Rule returned, serialize the output into a PSObject.
foreach ($NaElement in $NaResults) {
$NaNFS = "" | Select-Object Path, ActualPath, ReadOnly, ReadWrite, Root, Security
$NaNFS.Path = $NaElement.GetChildContent("pathname")
# This is where the OnTap SDK can get a little nuts...
# if you perfer XML then simply try $NaElement.ToPrettyString('')
switch ($NaElement) {
# if Read-Only is present
{$_.GetChildByName("read-only")}
{
# Get all child elements
$ReadOnly = ($_.GetChildByName("read-only")).getchildren()
#Foreach elm in read-only
foreach ($read in $ReadOnly) {
# [bool] if exists "all-hosts"
If ($read.GetChildContent("all-hosts")) {
$roList = 'All-Hosts'
}
# Else get the name of the export!
Elseif ($read.GetChildContent("name")) {
$roList += $read.GetChildContent("name")
}
}
# add our new list to the output
$NaNFS.ReadOnly = $roList
}
# if Read-write is present
{$_.GetChildByName("read-write")}
{
$ReadWrite = ($_.GetChildByName("read-write")).getchildren()
foreach ($write in $ReadWrite) {
If ($write.GetChildContent("all-hosts")) {
$rwList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rwList += $write.GetChildContent("name")
}
}
$NaNFS.ReadWrite = $rwList
}
# if root is present
{$_.GetChildByName("root")}
{
$Root = ($_.GetChildByName("root")).getchildren()
foreach ($r in $Root) {
If ($r.GetChildContent("all-hosts")) {
$rrList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rrList += $r.GetChildContent("name")
}
}
$NaNFS.Root = $rrList
}
{$_.GetChildByName("sec-flavor")}
{
$Security = ($_.GetChildByName("sec-flavor")).getchildren()
foreach ($s in $Security) {
if ($r.GetChildContent("flavor")) {
$SecList += $r.GetChildContent("flavor")
}
}
$NaNFS.Security = $SecList
}
{$_.GetChildByName("actual-pathname")}
{
$NaNFS.ActualPath = $_.GetChildByName("actual-pathname")
}
}
$out += $NaNFS
}
}
End {
If ($Path) {
return $out | ?{$_.Path -match $Patch}
}
else {
return $out
}
}
}
|
PowerShellCorpus/PoshCode/ConvertTo-Hex_9.ps1
|
ConvertTo-Hex_9.ps1
|
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx
param ( [string]$SidString )
# Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring
# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength
#Convert to bytes
$sid.GetBinaryForm( $sidBytes, 0 )
# Iterate through bytes, converting each to the hexidecimal equivalent
$hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") }
# Join the hex array into a single string for output
$hexArr -join ''
|
PowerShellCorpus/PoshCode/HttpRest.ps1
|
HttpRest.ps1
|
## Http Rest
####################################################################################################
## The first implementation of the HttpRest module, as a bunch of script functions
## Based on the REST api from MindTouch's Dream SDK
##
## INSTALL:
## You need log4net.dll mindtouch.core.dll mindtouch.dream.dll and SgmlReaderDll.dll from the SDK
## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
## Unpack it, and you can find these dlls in the "dist" folder.
## Make sure to put them in the folder with the module.
##
## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream
####################################################################################################
## Usage:
## function Get-Google {
## Invoke-Http GET http`://www.google.com/search @{q=$args} |
## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
## }
## #########################################################################
## function Get-WebFile($url,$cred) {
## Invoke-Http GET $url -auth $cred | Receive-Http File
## }
## #########################################################################
## function Send-Paste {
## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
## PROCESS {
## if($_){[IO.FileInfo]$file=$_}
##
## if($file.Exists) {
## $ofs="`n"
## $result = Invoke-Http POST $PastebinURI @{
## format="posh" # PowerShell
## expiry="d" # (d)ay or (m)onth or (f)orever
## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1])
## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
## paste="Send"
## } -Type FORM_URLENCODED -Wait
## $xml = $result.AsDocument().ToXml()
## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
## } else { throw "File Not Found" }
## }}
##
####################################################################################################
if(!$PSScriptRoot){
Write-Debug $($MyInvocation.MyCommand | out-string)
$PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
}
# Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
# Write-Debug "Invocation: $($MyInvocation.MyCommand)"
# Write-Debug "Invocation: $($MyInvocation)"
Write-Debug "PSScriptRoot: '$PSScriptRoot'"
# This Module depends on MindTouch.Dream
$null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" )
# MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
# This Module also depends on utility functions from System.Web
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
## Some utility functions are defined at the bottom
[uri]$global:url = ""
[System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
function Get-DreamMessage($Content,$Type) {
if(!$Content) {
return [MindTouch.Dream.DreamMessage]::Ok()
}
if( $Content -is [System.Xml.XmlDocument]) {
return [MindTouch.Dream.DreamMessage]::Ok( $Content )
}
if(Test-Path $Content -EA "SilentlyContinue") {
return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
}
if($Type -is [String]) {
$Type = [MindTouch.Dream.MimeType]::$Type
}
if($Type -is [MindTouch.Dream.DreamMessage]) {
return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
} else {
return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
}
}
function Get-DreamPlug {
PARAM ( $Url, [hashtable]$With )
if($Url -is [array]) {
if($Url[0] -is [hashtable]) {
$plug = [MindTouch.Dream.Plug]::New($global:url)
foreach($param in $url.GetEnumerator()) {
if($param.Value) {
$plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
} else {
$plug = $plug.At($param.Key)
}
}
} else {
[URI]$uri = Join-Url $global:url $url
$plug = [MindTouch.Dream.Plug]::New($uri)
}
} elseif($url -is [string]) {
[URI]$uri = $url
if(!$uri.IsAbsoluteUri) {
$uri = Join-Url $global:url $url
}
$plug = [MindTouch.Dream.Plug]::New($uri)
} else {
$plug = [MindTouch.Dream.Plug]::New($global:url)
}
if($with) { foreach($param in $with.GetEnumerator()) {
if($param.Value) {
$plug = $plug.With($param.Key,$param.Value)
}
} }
return $plug
}
#CMDLET Receive-Http {
Function Receive-Http {
PARAM(
# [Parameter(Position=1, Mandatory=$false)]
# [ValidateSet("Xml", "File", "Text","Bytes")]
# [Alias("As")]
$Output = "Xml"
,
# [Parameter(Position=2, Mandatory=$false)]
[string]$Path
,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
# [Alias("IO")]
# [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
$InputObject
#,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
# [MindTouch.Dream.DreamMessage]
# $response
)
BEGIN {
if($InputObject) {
Write-Output $inputObject | Receive-Http $Output $Path
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
$response = $null
if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
$response = $_.Wait()
} elseif($_ -is [MindTouch.Dream.DreamMessage]) {
$response = $_
} elseif($_) {
throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
}
if($response) {
Write-Debug $($response | Out-String)
if(!$response.IsSuccessful) {
Write-Error $($response | Out-String)
Write-Verbose $response.AsText()
throw "ERROR: '$($response.Status)' Response Status."
} else {
switch($Output) {
"File" {
## Joel's magic filename guesser ...
if(!$Path) {
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
$Path = $fileName.trim("\\/""'")
if(!$Path) {
$fileName = $response.ResponseUri.Segments[-1]
$Path = $fileName.trim("\\/")
if(!([IO.FileInfo]$Path).Extension) {
$Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
}
}
}
$File = Get-FileName $Path
[StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
Get-ChildItem $File
}
"XDoc" {
if($Path) {
$response.AsDocument()[$Path]
} else {
$response.AsDocument()#.ToXml()
}
}
"Xml" {
if($Path) {
$response.AsDocument().ToXml().SelectNodes($Path)
} else {
$response.AsDocument().ToXml()
}
}
"Text" {
if($Path) {
$response.AsDocument()[$Path] | % { $_.AsText }
} else {
$response.AsText()
}
}
"Bytes" {
$response.AsBytes()
}
}
}
}
}
}
## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
## Nobody actually uses HEAD or OPTIONS, right?
## And nobody's even heard of TRACE or CONNECT ;)
# CMDLET Invoke-Http {
Function Invoke-Http {
PARAM(
# [Parameter(Position=0, Mandatory=$false)]
# [ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
[string]$Verb = "Get"
,
# [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]
# [string]
$Path
,
# [Parameter(Position=2, Mandatory=$false)]
[hashtable]$with
,
# [Parameter(Position=3, Mandatory=$false)]
$Content
,
$Type # Of Content
,
$authenticate
,
[switch]$waitForResponse
)
BEGIN {
$Verbs = "Post", "Get", "Put", "Delete", "Head", "Options"
if($Verbs -notcontains $Verb) {
Write-Warning "The specified verb '$Verb' is NOT one of the common verbs: $Verbs"
}
if($Path) {
if($Content) {
Write-Output ($Path | Invoke-Http $Verb -With $With -Content $Content -Type $Type -Authenticate $authenticate -waitForResponse:$WaitForResponse)
} else {
Write-Output ($Path | Invoke-Http $Verb -With $With -Type $Type-Authenticate $authenticate -waitForResponse:$WaitForResponse)
}
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
if($_) {
$Path = $_
$plug = Get-DreamPlug $Path $With
Write-Verbose "Content Type: $Type"
Write-Verbose "Content: $Content"
## Special Handling for FORM_URLENCODED
if($Type -like "Form*" -and !$Content) {
$dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
$Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
} else {
$dream = Get-DreamMessage $Content $Type
}
if(!$plug -or !$dream) {
throw "Can't come up with a request!"
}
Write-Verbose $( $dream | Out-String )
if($authenticate){
Write-Verbose "AUTHENTICATE AS $($authenticate.UserName)"
if($authenticate -is [System.Management.Automation.PSCredential]) {
Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
$plug = $plug.WithCredentials($authenticate.UserName, ($authenticate.GetNetworkCredential().Password))
} elseif($authenticate -is [System.Net.NetworkCredential]) {
Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
$plug = $plug.WithCredentials($authenticate.UserName, $authenticate.Password)
} else {
Get-HttpCredential
Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
$plug = $plug.WithCredentials($global:HttpRestCredential.UserName, $global:HttpRestCredential.Password)
}
}
Write-Verbose $plug.Uri
## DEBUG:
Write-Debug "URI: $($Plug.Uri)"
Write-Debug "Verb: $($Verb.ToUpper())"
Write-Debug $($dream | Out-String)
$result = $plug.InvokeAsync( $Verb.ToUpper(), $dream )
Write-Debug $($result | Out-String)
# if($DebugPreference -eq "Continue") {
# Write-Debug $($result.Wait() | Out-String)
# }
if($waitForResponse) {
$result = $result.Wait()
}
write-output $result
trap [MindTouch.Dream.DreamResponseException] {
Write-Error @"
TRAPPED DreamResponseException
$($_.Exception.Response | Out-String)
$($_.Exception.Response.Headers | Out-String)
"@
break;
}
}
}
}
# function Get-Http { return Invoke-Http "GET" @args }
# function New-Http { return Invoke-Http "PUT" @args }
# function Update-Http { return Invoke-Http "POST" @args }
# function Remove-Http { return Invoke-Http "DELETE" @args }
# new-alias Set-Http Update-Http
# new-alias Put-Http New-Http
# new-alias Post-Http Update-Http
# new-alias Delete-Http Remove-Http
function Set-HttpDefaultUrl {
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
$global:url = $baseUri
}
function Set-HttpCredential {
param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $($global:url.Host)) )
if($Credential -is [System.Management.Automation.PSCredential]) {
$global:HttpRestCredential = $Credential
} elseif($Credential -is [System.Net.NetworkCredential]) {
$global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
}
}
function Get-HttpCredential([switch]$Secure) {
if(!$global:url) { Set-HttpDefaultUrl }
if(!$global:HttpRestCredential) { Set-HttpCredential }
if(!$Secure) {
return $global:HttpRestCredential.GetNetworkCredential();
} else {
return $global:HttpRestCredential
}
}
# function Authenticate-Http {
# PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
# $plug = [MindTouch.Dream.Plug]::New( $global:url )
# $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
# }
function Encode-Twice {
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
function Join-Url ( [uri]$baseUri=$global:url ) {
$ofs="/";$BaseUrl = ""
if($BaseUri -and $baseUri.AbsoluteUri) {
$BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
}
return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
}
function ConvertTo-SecureString {
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
## Unit-Test Get-FileName ## Should return TRUE
## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and
## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe"
function Get-FileName {
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
## if the $Path has a file name, and it's folder exists:
if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
$path
## if the $Path is just a folder (and it exists)
} elseif($Path -and (Test-Path $path -Type Container)) {
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
## If there's no valid $Path, and the $FileName has a folder...
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
$fileName
} else {
Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
}
}
function Get-UtcTime {
Param($Format="yyyyMMddhhmmss")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
## Get-CredentialBetter
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-CredentialBetter{
PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
$ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds"
## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
$cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
## Compare to $True, because by default it's $null ...
$cp = $cp.ConsolePrompting -eq $True
if($Console -and !$cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $True
} elseif(!$Console -and $Console.IsPresent -and $cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $False
}
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
$Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
Set-ItemProperty $ShellIdKey ConsolePrompting $cp
}
# Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl
|
PowerShellCorpus/PoshCode/ScheduleGPOBackups.ps1
|
ScheduleGPOBackups.ps1
|
Import-Module grouppolicy
#region ConfigBlock
# What domain are we going to backup GPOs for?
$domain = "psd267.wednet.edu"
# Where are we going to store the backups?
$gpoBackupRootDir = "c:\\gpoBackups"
# As I plan to do a new backup set each month I'll setup the directory names to reflect
# the year and month in a nice sortable way.
# Set this up and format to your liking, I prefer $gpoBackupRootDir\\yyyy-MM
$backupDir = "$gpoBackupRootDir\\{0:yyyy-MM}" -f (Get-Date)
# Perform a full backup how often? Day/Week/Month/Year?
#$fullBackupFrequency = "Day"
#$fullBackupFrequency = "Week"
$fullBackupFrequency = "Month"
#$fullBackupFrequency = "Year"
# Perform Incremental backups how often? Hour/Day/Week/Month?
$IncBackupFreqency = "Hour"
# $IncBackupFreqency = "Day"
# $IncBackupFreqency = "Week"
# $IncBackupFreqency = "Month"
# How many full sets to keep?
# Alternatively, how far back do we keep our backup sets?
$numKeepBackupSets = 12
# On what day do we want to consider the start of Week?
#$startOfWeek = "Sunday"
$startOfWeek = "Monday"
#$startOfWeek = "Tuesday"
#$startOfWeek = "Wednesday"
#$startOfWeek = "Thursday"
#$startOfWeek = "Friday"
#$startOfWeek = "Saturday"
# On what day do we want to consider the start of Month?
$startOfMonth = 1
# On what day do we want to consider the start of Year?
$startOfYear = 1
#endregion
$currentDateTime = Get-Date
$doFull = $false
$doInc = $false
# Does our backup directory exist?
# If not attempt to create it and fail the script with an approprate error
if (-not (Test-Path $backupDir))
{
try
{
New-Item -ItemType Directory -Path $backupDir
}
catch
{
Throw $("Could not create directory $backupDir")
}
}
# If we're here then our backup directory is in good shape
# Check if we need to run a full backup or not
# if we do, then run it
if ( Test-Path $backupDir\\LastFullTimestamp.xml )
{
# Import the timestamp from the last recorded complete full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run a full
if ( $lastFullTimestamp -isnot [datetime] )
{
$doFull = $true
Remove-Item $backupDir\\LastFullTimestamp.xml
}
else # $lastfulltimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$fullDelta = $currentDateTime - $lastFullTimestamp
switch ($fullBackupFrequency)
{
Day
{
if ( $fullDelta.days -gt 0 )
{
$doFull = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($fullDelta.days -gt 7) )
{
$doFull = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($fullDelta.days -gt 30) )
{
$doFull = $true
}
}
Year
{
if ( ($currentDateTime.dayofyear -eq $startOfYear) `
-or ($fullDelta.days -gt 365) )
{
$doFull = $true
}
}
}
}
}
else # There is no recorded last completed full so we want to run one
{
$doFull = $true
}
if ($doFull)
{
# Run Backup of All GPOs in domain
$GPOs = Get-GPO -domain $domain -All
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastFullTimestamp.xml -InputObject ($currentDateTime)
}
else # If we're not running a full check if we need to run an incremental backup
{
if ( Test-Path $backupDir\\LastIncTimestamp.xml )
{
# Import the timestamp from the last recorded complete Incremental
$lastIncTimestamp = Import-Clixml $backupDir\\LastIncTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run an inc
if ( $lastIncTimestamp -isnot [datetime] )
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
$doInc = $true
Remove-Item $backupDir\\LastIncTimestamp.xml
}
else # $lastIncTimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$IncDelta = $currentDateTime - $lastIncTimestamp
}
}
else # There is no recorded last Incremental
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
}
# If we have already determined to run an Inc we want to skip this part
if ($doInc = $false)
{
switch ($IncBackupFreqency)
{
Hour
{
if ($IncDelta.hours -gt 0)
{
$doInc = $true
}
}
Day
{
if ($IncDelta.days -gt 0)
{
$doInc = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($IncDelta.days -gt 7) )
{
$doInc = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($IncDelta.days -gt 30) )
{
$doInc = $true
}
}
}
}
# Time to check our Incremental flag and run the backup if we need to
if ($doInc)
{
# Run Incremental Backup
$GPOs = Get-GPO -domain $domain -All | Where-Object { $_.modificationTime -gt ($currentDateTime - $incDelta) }
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastIncTimestamp.xml -InputObject ($currentDateTime)
}
}
#TODO: Cleanup old backup sets
|
PowerShellCorpus/PoshCode/Get-TopProcess.ps1
|
Get-TopProcess.ps1
|
## poll-process.ps1
## Continuously display a process list, sorted
## by the desired criteria.
##
## usage: poll-process [sortCriteria] [pollInterval]
##
## sortCriteria must be one of "Id", "ProcessName", "MainWindowTitle",
## "Processor", "Disk", or "WorkingSet"
## pollInterval is specified in milliseconds
##
param(
[string] $sortCriteria = "Processor",
[int] $Count = 5
)
function main
{
## Store the performance counters we need
## for the CPU, and Disk I/O numbers
$cpuPerfCounters = @{}
$ioOtherOpsPerfCounters = @{}
$ioOtherBytesPerfCounters = @{}
$ioDataOpsPerfCounters = @{}
$ioDataBytesPerfCounters = @{}
$processes = $null
$lastPoll = get-date
$lastSnapshotCount = 0
$lastWindowHeight = 0
$processes = get-process | sort Id
## Go through all of the processes we captured
foreach($process in $processes)
{
## Get the disk activity, based on I/O Perf Counters,
## for the process in question. Then, add it as a note.
$cpuPercent = @(for($i=0;$i -lt 10;$i++)
{
get-cpuPercent $process
}) | measure-object -average
[int]$Percent = $cpuPercent.Average
#$process | add-member NoteProperty Disk $activity -force
$process | add-member NoteProperty Processor $Percent -force
}
$output = $processes | sort -desc $sortCriteria | select -first $Count
$output | format-table Id,ProcessName,MainWindowTitle,WorkingSet
}
## As a heuristic, gets the total IO and Data operations per second, and
## returns their sum.
function get-diskActivity (
$process = $(throw "Please specify a process for which to get disk usage.")
)
{
$processName = get-processName $process
## We store the performance counter objects in a hashtable. If we don't,
## then they fail to return any information for a few seconds.
if(-not $ioOtherOpsPerfCounters[$processName])
{
$ioOtherOpsPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Other Operations/sec",$processName)
}
if(-not $ioOtherBytesPerfCounters[$processName])
{
$ioOtherBytesPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Other Bytes/sec",$processName)
}
if(-not $ioDataOpsPerfCounters[$processName])
{
$ioDataOpsPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Data Operations/sec",$processName)
}
if(-not $ioDataBytesPerfCounters[$processName])
{
$ioDataBytesPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Data Bytes/sec",$processName)
}
## If a process exits between the time we capture the processes and now,
## then we will be unable to get its NextValue(). This trap simply
## catches the error and continues.
trap { continue; }
## Get the performance counter values
$ioOther = (100 * $ioOtherOpsPerfCounters[$processName].NextValue()) + ($ioOtherBytesPerfCounters[$processName].NextValue())
$ioData = (100 * $ioDataOpsPerfCounters[$processName].NextValue()) + ($ioDataBytesPerfCounters[$processName].NextValue())
return [int] ($ioOther + $ioData)
}
## Get the percentage of time spent by a process.
## Note: this is multiproc "unaware." We need to divide the
## result by the number of processors.
function get-cpuPercent (
$process = $(throw "Please specify a process for which to get CPU usage.")
)
{
$processName = get-processName $process
## We store the performance counter objects in a hashtable. If we don't,
## then they fail to return any information for a few seconds.
if(-not $cpuPerfCounters[$processName])
{
$cpuPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","% Processor Time",$processName)
}
## If a process exits between the time we capture the processes and now,
## then we will be unable to get its NextValue(). This trap simply
## catches the error and continues.
trap { continue; }
## Get the performance counter values
$cpuTime = ($cpuPerfCounters[$processName].NextValue() / $env:NUMBER_OF_PROCESSORS)
return [int] $cpuTime
}
## Performance counters are keyed by process name. However,
## processes may share the same name, so duplicates are named
## <process>#1, <process>#2, etc.
function get-processName (
$process = $(throw "Please specify a process for which to get the name.")
)
{
## If a process exits between the time we capture the processes and now,
## then we will be unable to get its information. This simply
## ignores the error.
$errorActionPreference = "SilentlyContinue"
$processName = $process.ProcessName
$localProcesses = get-process -ProcessName $processName | sort Id
if(@($localProcesses).Count -gt 1)
{
## Determine where this one sits in the list
$processNumber = -1
for($counter = 0; $counter -lt $localProcesses.Count; $counter++)
{
if($localProcesses[$counter].Id -eq $process.Id) { break }
}
## Append its unique identifier, if required
$processName += "#$counter"
}
return $processName
}
. main
|
PowerShellCorpus/PoshCode/Easy Migration Tool v2.0.ps1
|
Easy Migration Tool v2.0.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: Richard Yaw
# Generated On: 09/12/2010
#
# Easy Migration Script for VMware (Version 2.0)
# - Added a "Reload Tasks" feature.
# - Fixed issue with the Undo feature for SVMotions.
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$MigrationForm = New-Object System.Windows.Forms.Form
$Header = new-object System.Windows.Forms.Label
$MigrateButton = New-Object System.Windows.Forms.Button
$ClusterListBox = New-Object System.Windows.Forms.ListBox
$SourceHostListBox = New-Object System.Windows.Forms.ListBox
$SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox
$SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox
$DestinationListBox = New-Object System.Windows.Forms.ListBox
$vCenterLabel = New-Object System.Windows.Forms.Label
$VCTextBox = New-Object System.Windows.Forms.TextBox
$LoginButton = New-Object System.Windows.Forms.Button
$ClearMsgButton = New-Object System.Windows.Forms.Button
$UndoButton = New-Object System.Windows.Forms.Button
$UndoALLButton = New-Object System.Windows.Forms.Button
$ReloadTaskButton = New-Object System.Windows.Forms.Button
$SaveTaskButton = New-Object System.Windows.Forms.Button
$ClusterLabel = New-Object System.Windows.Forms.Label
$HostToHostButton = New-Object System.Windows.Forms.Button
$VMToHostButton = New-Object System.Windows.Forms.Button
$DBtoDBButton = New-Object System.Windows.Forms.Button
$VMtoDBButton = New-Object System.Windows.Forms.Button
$SourceButton = New-Object System.Windows.Forms.Button
$DestinationButton = New-Object System.Windows.Forms.Button
$ResetButton = New-Object System.Windows.Forms.Button
$ChangeVCButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$MessagesLabel = New-Object System.Windows.Forms.Label
$MessagesListBox = New-Object System.Windows.Forms.ListBox
$TaskLabel = New-Object System.Windows.Forms.Label
$TaskListBox = New-Object System.Windows.Forms.ListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$LoginButton_Click=
{
#TODO: Place custom script here
If ($VCTextBox.Text -eq "")
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Enter a Valid vCenter Server.')
}
Else
{
if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $VCTextBox.Text
$ClusterListBox.Enabled = $true
#Get Cluster
Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) }
If ($ClusterListBox.items -ne $null)
{
$LoginButton.Enabled = $false
$VCTextBox.Enabled = $false
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$ResetButton.Enabled = $true
$ChangeVCButton.Enabled = $true
$ReloadTaskButton.Enabled = $true
#Generate a log file for this session
#$logfile = "C:\\TEMP\\EasyMigrate{0:dd-MM-yyyy_HHmmss}" -f (Get-Date) + ".log"
#$logheader = "Easy Migration Tool v1.0 - Log generated on " + (Get-Date)
#Out-File -InputObject $logheader -FilePath $logfile
#Out-File -InputObject "" -Append -FilePath $logfile
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$HostToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$SourceHostListBox.Enabled = $true
$SourceHostListBox.Items.Clear()
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select One Host'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$HostToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$VMToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$DBtoDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceDBListBox)
$SourceDBListBox.Enabled = $true
$SourceDBListBox.Items.Clear()
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select a Datastore'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$SourceButton_OnClick=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
If ($SourceHostname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Source Host.')
}
Else
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceHostListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$SourceVMname = $SourceVMListBox.SelectedItem
If ($SourceVMname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.')
}
Else
{
if ($DestinationButton.Text -like "Destination Host")
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) }
}
$DestinationListBox.Enabled = $true
$SourceVMListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -like "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
If ($SourceDBname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One Datastore.')
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceDBListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
}
$DestinationButton_OnClick=
{
#TODO: Place custom script here
$DestinationName = $DestinationListBox.SelectedItem
If ($DestinationName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Destination.')
}
Else
{
$DestinationListBox.Enabled = $false
$DestinationButton.Enabled = $false
$MigrateButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$MigrateButton_OnClick=
{
#TODO: Place custom script here
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-VMHost $SourceHostname | Get-VM
foreach($VM in $VMs)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$DestinationName = $DestinationListBox.SelectedItem
If($DestinationButton.Text -eq "Destination Host")
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
Else
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-Datastore -Name $SourceDBname | Get-VM
If($VMs.count -gt 0)
{
foreach($VM in $VMs)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBFreeSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - No VM is present on the source datastore $SourceDBname."
[void]$MessagesListBox.items.add($MsgLine)
}
$SourceDBListBox.enabled = $true
$SourceButton.enabled = $true
$DestinationListBox.Items.Clear()
$MigrateButton.Enabled = $false
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
$RESETButton_OnClick=
{
#TODO: Place custom script here
$ClusterListBox.Enabled = $true
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
}
$ChangeVCButton_OnClick=
{
#TODO: Place custom script here
$VCTextBox.Text = ""
$VCTextBox.Enabled = $true
$LoginButton.Enabled = $true
$ClusterListBox.Items.Clear()
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$ResetButton.Enabled = $false
$ChangeVCButton.Enabled = $false
$MessagesListBox.Items.Clear()
$TaskListBox.Items.Clear()
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
If ($VCTextBox.Text -ne "")
{
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
#Close Form
$MigrationForm.close()
}
$ClearMsgButton_Click=
{
#TODO: Place custom script here
If($MessagesListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('No messages to clear.')
}
Else
{
$MessagesListBox.items.clear()
}
}
$UndoButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
If ($TaskListBox.SelectedItems.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please select one or more tasks.')
}
Else
{
foreach($Task in $TaskListBox.SelectedItems)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
While($TaskListBox.SelectedItems.Count -gt 0)
{
$TaskListBox.Items.Remove($TaskListBox.SelectedItems[0])
}
}
}
}
$UndoALLButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
foreach($Task in $TaskListBox.Items)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$TaskListBox.Items.Clear()
}
}
$SaveTaskButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Nothing to save to log file.')
}
Else
{
$SaveFileD = new-object System.Windows.Forms.SaveFileDialog
$SaveFileD.Filter = "Log Files (*.log)|*.log";
$SaveFileD.Title = "Save to a log file";
$SaveFileD.FilterIndex = 2;
$SaveFileD.RestoreDirectory = $true;
if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $SaveFileD.FileName
$Tasks = $TaskListBox.items
$logheader = "Easy Migration Tool v1.0 - Log generated on " + (Get-Date)
#Save a log file for this session to a location selected by the user
Out-File -InputObject $logheader -FilePath $Filename
Out-File -InputObject "" -Append -FilePath $FileName
Out-File -InputObject $Tasks -Append -FilePath $FileName
}
}
}
$ReloadTaskButton_Click=
{
#TODO: Place custom script here
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
#$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Log Files (*.log)|*.log"
if ($OpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $OpenFileDialog.FileName
$LinesCount = (Get-Content $FileName).Count
$LogLines = Get-Content $FileName | Select -Last ($LinesCount - 2)
$TaskListBox.Items.Clear()
foreach ($LogLine in $LogLines)
{
[void]$TaskListBox.items.add($LogLine)
}
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
#----------------------------------------------
#region Generated Form Code
# Start Main Form
$MigrationForm.Text = 'Easy Migration Tool v1.0'
$MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MigrationForm.Name = 'EasyMigrationForm'
$MigrationForm.StartPosition = "CenterScreen"
$MigrationForm.FormBorderStyle = "FixedDialog"
$MigrationForm.MaximizeBox = $false
$MigrationForm.MinimizeBox = $false
$MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1030
$System_Drawing_Size.Height = 500
$MigrationForm.ClientSize = $System_Drawing_Size
# End Main Form
#Start Easy_Migration Header
$Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold)
$Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$Header.Text = 'Easy Migration Tool v1.0'
$Header.Location = new-object System.Drawing.Point(150,15)
$Header.Size = new-object System.Drawing.Size(230, 20)
$MigrationForm.Controls.Add($Header)
#End Easy_Migration Header
# Start vCenter Server Label
$vCenterLabel.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$vCenterLabel.Size = $System_Drawing_Size
$vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$vCenterLabel.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 15
$System_Drawing_Point.Y = 50
$vCenterLabel.Location = $System_Drawing_Point
$vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$vCenterLabel.Name = 'vCenterLabel'
$MigrationForm.Controls.Add($vCenterLabel)
# End vCenter Server Label
# Start vCenter Textbox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 20
$VCTextBox.Size = $System_Drawing_Size
$VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8)
$VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$VCTextBox.Name = 'VCTextBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 50
$VCTextBox.Location = $System_Drawing_Point
$VCTextBox.TabIndex = 1
$MigrationForm.Controls.Add($VCTextBox)
# End vCenter Textbox
# Start Login Button
$LoginButton.TabIndex = 0
$LoginButton.Name = 'LoginButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$LoginButton.Size = $System_Drawing_Size
$LoginButton.Font = new-object System.Drawing.Font("Tahoma",8)
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.Text = 'Login'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 48
$LoginButton.Location = $System_Drawing_Point
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$LoginButton.add_Click($LoginButton_Click)
$MigrationForm.Controls.Add($LoginButton)
# End Login Button
# Start Change VC Button
$ChangeVCButton.TabIndex = 19
$ChangeVCButton.Name = 'ChangeVCButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$ChangeVCButton.Size = $System_Drawing_Size
$ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ChangeVCButton.UseVisualStyleBackColor = $True
$ChangeVCButton.Text = 'Change vCenter'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 355
$System_Drawing_Point.Y = 48
$ChangeVCButton.Location = $System_Drawing_Point
$ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ChangeVCButton.add_Click($ChangeVCButton_OnClick)
$ChangeVCButton.Enabled = $false
$MigrationForm.Controls.Add($ChangeVCButton)
# End Change VC Button
# Start Cluster Listbox
$ClusterLabel.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 85
$System_Drawing_Size.Height = 20
$ClusterLabel.Size = $System_Drawing_Size
$ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$ClusterLabel.Text = 'Select Cluster:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 90
$ClusterLabel.Location = $System_Drawing_Point
$ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterLabel.Name = 'ClusterLabel'
$MigrationForm.Controls.Add($ClusterLabel)
$ClusterListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 100
$ClusterListBox.Size = $System_Drawing_Size
$ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterListBox.Name = 'ClusterListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 90
$ClusterListBox.Location = $System_Drawing_Point
$ClusterListBox.MultiColumn = $false
$ClusterListBox.TabIndex = 5
$ClusterListBox.Sorted = $True
$MigrationForm.Controls.Add($ClusterListBox)
# End Cluster Listbox
# Start Host to Host Button
$HostToHostButton.TabIndex = 3
$HostToHostButton.Name = 'HostToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$HostToHostButton.Size = $System_Drawing_Size
$HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$HostToHostButton.UseVisualStyleBackColor = $True
$HostToHostButton.Text = 'Host to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 90
$HostToHostButton.Location = $System_Drawing_Point
$HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$HostToHostButton.add_Click($HostToHostButton_Click)
$HostToHostButton.Enabled = $false
$MigrationForm.Controls.Add($HostToHostButton)
# End Host to Host Button
# Start VM to Host Button
$VMToHostButton.TabIndex = 3
$VMToHostButton.Name = 'VMToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMToHostButton.Size = $System_Drawing_Size
$VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMToHostButton.UseVisualStyleBackColor = $True
$VMToHostButton.Text = 'VM to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 115
$VMToHostButton.Location = $System_Drawing_Point
$VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMToHostButton.add_Click($VMToHostButton_Click)
$VMToHostButton.Enabled = $false
$MigrationForm.Controls.Add($VMToHostButton)
# End VM to Host Button
# Start Datastore to Datastore Button
$DBtoDBButton.TabIndex = 3
$DBtoDBButton.Name = 'DBtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$DBtoDBButton.Size = $System_Drawing_Size
$DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DBtoDBButton.UseVisualStyleBackColor = $True
$DBtoDBButton.Text = 'Datastore to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 140
$DBtoDBButton.Location = $System_Drawing_Point
$DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DBtoDBButton.add_Click($DBtoDBButton_Click)
$DBtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($DBtoDBButton)
# End Datastore to Datastore Button
# Start VM to Datastore Button
$VMtoDBButton.TabIndex = 3
$VMtoDBButton.Name = 'VMtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMtoDBButton.Size = $System_Drawing_Size
$VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMtoDBButton.UseVisualStyleBackColor = $True
$VMtoDBButton.Text = 'VM to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 165
$VMtoDBButton.Location = $System_Drawing_Point
$VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMtoDBButton.add_Click($VMtoDBButton_Click)
$VMtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($VMtoDBButton)
# End VM to Datastore Button
# Start Source Host List Box
$SourceHostListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceHostListBox.Size = $System_Drawing_Size
$SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceHostListBox.Name = 'SourceHostListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceHostListBox.Location = $System_Drawing_Point
$SourceHostListBox.MultiColumn = $false
$SourceHostListBox.TabIndex = 5
$SourceHostListBox.Sorted = $True
$MigrationForm.Controls.Add($SourceHostListBox)
# End Source Host List Box
# Start Source Datastore List Box
$SourceDBListBox.FormattingEnabled = $True
$SourceDBListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceDBListBox.Size = $System_Drawing_Size
$SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceDBListBox.Name = 'SourceDBListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceDBListBox.Location = $System_Drawing_Point
$SourceDBListBox.MultiColumn = $false
$SourceDBListBox.HorizontalScrollBar = $true
$SourceDBListBox.TabIndex = 5
$SourceDBListBox.Sorted = $True
# End Source Datastore List Box
# Start Source VM List Box
$SourceVMListBox.FormattingEnabled = $True
$SourceVMListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceVMListBox.Size = $System_Drawing_Size
$SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceVMListBox.Name = 'SourceVMListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceVMListBox.Location = $System_Drawing_Point
$SourceVMListBox.MultiColumn = $false
$SourceVMListBox.TabIndex = 5
$SourceVMListBox.Sorted = $True
# End Source VM List Box
# Start Source Button
$SourceButton.TabIndex = 7
$SourceButton.Name = 'Source Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$SourceButton.Size = $System_Drawing_Size
$SourceButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceButton.UseVisualStyleBackColor = $True
$SourceButton.Text = 'Source'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 415
$SourceButton.Location = $System_Drawing_Point
$SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceButton.add_Click($SourceButton_OnClick)
$SourceButton.Enabled = $false
$MigrationForm.Controls.Add($SourceButton)
# End Source Button
# Start Destination List Box
$DestinationListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$DestinationListBox.Size = $System_Drawing_Size
$DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationListBox.Name = 'DestinationListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 210
$DestinationListBox.Location = $System_Drawing_Point
$DestinationListBox.HorizontalScrollBar = $true
$DestinationListBox.MultiColumn = $false
$DestinationListBox.TabIndex = 5
$DestinationListBox.Sorted = $True
$MigrationForm.Controls.Add($DestinationListBox)
# End Destination List Box
# Start Destination Button
$DestinationButton.TabIndex = 7
$DestinationButton.Name = 'Destination Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$DestinationButton.Size = $System_Drawing_Size
$DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationButton.UseVisualStyleBackColor = $True
$DestinationButton.Text = 'Destination'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 415
$DestinationButton.Location = $System_Drawing_Point
$DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationButton.add_Click($DestinationButton_OnClick)
$DestinationButton.Enabled = $false
$MigrationForm.Controls.Add($DestinationButton)
# End Destination Button
# Start Migrate Button
$MigrateButton.TabIndex = 7
$MigrateButton.Name = 'MigrateButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$MigrateButton.Size = $System_Drawing_Size
$MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8)
$MigrateButton.UseVisualStyleBackColor = $True
$MigrateButton.Text = 'Migrate'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 450
$MigrateButton.Location = $System_Drawing_Point
$MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0
$MigrateButton.add_Click($MigrateButton_OnClick)
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Add($MigrateButton)
# End Migrate Button
# Start RESET Button
$ResetButton.TabIndex = 19
$ResetButton.Name = 'ResetButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 140
$System_Drawing_Size.Height = 25
$ResetButton.Size = $System_Drawing_Size
$ResetButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ResetButton.UseVisualStyleBackColor = $True
$ResetButton.Text = 'Reset'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 450
$ResetButton.Location = $System_Drawing_Point
$ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ResetButton.add_Click($ResetButton_OnClick)
$ResetButton.Enabled = $false
$MigrationForm.Controls.Add($ResetButton)
# End RESET Button
# Start CLOSE Button
$CloseButton.TabIndex = 19
$CloseButton.Name = 'CloseButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$CloseButton.Size = $System_Drawing_Size
$CloseButton.Font = new-object System.Drawing.Font("Tahoma",8)
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.Text = 'Close'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 320
$System_Drawing_Point.Y = 450
$CloseButton.Location = $System_Drawing_Point
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$CloseButton.add_Click($CloseButton_OnClick)
$MigrationForm.Controls.Add($CloseButton)
# End CLOSE Button
# Start Messages ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$MessagesLabel.Size = $System_Drawing_Size
$MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MessagesLabel.Text = 'Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 50
$MessagesLabel.Location = $System_Drawing_Point
$MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesLabel.Name = 'MessagesLabel'
$MigrationForm.Controls.Add($MessagesLabel)
$MessagesListBox.FormattingEnabled = $True
$MessagesListBox.SelectionMode = "None"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 140
$MessagesListBox.Size = $System_Drawing_Size
$MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesListBox.Name = 'MessagesListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 70
$MessagesListBox.Location = $System_Drawing_Point
$MessagesListBox.MultiColumn = $false
$MessagesListBox.HorizontalScrollbar = $true
$MigrationForm.Controls.Add($MessagesListBox)
# End Messages ListBox
# Start Task ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$TaskLabel.Size = $System_Drawing_Size
$TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$TaskLabel.Text = 'Recent Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 215
$TaskLabel.Location = $System_Drawing_Point
$TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskLabel.Name = 'TaskLabel'
$MigrationForm.Controls.Add($TaskLabel)
$TaskListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 200
$TaskListBox.Size = $System_Drawing_Size
$TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskListBox.Name = 'TaskListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 235
$TaskListBox.Location = $System_Drawing_Point
$TaskListBox.MultiColumn = $false
$TaskListBox.HorizontalScrollbar = $true
$TaskListBox.SelectionMode = "MultiExtended"
$MigrationForm.Controls.Add($TaskListBox)
# End Task ListBox
# Start Clear Messages Button
$ClearMsgButton.TabIndex = 0
$ClearMsgButton.Name = 'ClearMsgButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ClearMsgButton.Size = $System_Drawing_Size
$ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ClearMsgButton.UseVisualStyleBackColor = $True
$ClearMsgButton.Enabled = $false
$ClearMsgButton.Text = 'Clear Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 450
$ClearMsgButton.Location = $System_Drawing_Point
$ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ClearMsgButton.add_Click($ClearMsgButton_Click)
$MigrationForm.Controls.Add($ClearMsgButton)
# End Clear Messages Button
# Start Undo Button
$UndoButton.TabIndex = 0
$UndoButton.Name = 'UndoButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoButton.Size = $System_Drawing_Size
$UndoButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoButton.UseVisualStyleBackColor = $True
$UndoButton.Enabled = $false
$UndoButton.Text = 'Undo'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 588
$System_Drawing_Point.Y = 450
$UndoButton.Location = $System_Drawing_Point
$UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoButton.add_Click($UndoButton_Click)
$MigrationForm.Controls.Add($UndoButton)
# End Undo Button
# Start UndoALL Button
$UndoALLButton.TabIndex = 0
$UndoALLButton.Name = 'UndoALLButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoALLButton.Size = $System_Drawing_Size
$UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoALLButton.UseVisualStyleBackColor = $True
$UndoALLButton.Enabled = $false
$UndoALLButton.Text = 'Undo ALL'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 696
$System_Drawing_Point.Y = 450
$UndoALLButton.Location = $System_Drawing_Point
$UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoALLButton.add_Click($UndoALLButton_Click)
$MigrationForm.Controls.Add($UndoALLButton)
# End UndoALL Button
# Start Save Task Button
$SaveTaskButton.TabIndex = 0
$SaveTaskButton.Name = 'SaveTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$SaveTaskButton.Size = $System_Drawing_Size
$SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SaveTaskButton.UseVisualStyleBackColor = $True
$SaveTaskButton.Enabled = $false
$SaveTaskButton.Text = 'Save Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 804
$System_Drawing_Point.Y = 450
$SaveTaskButton.Location = $System_Drawing_Point
$SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SaveTaskButton.add_Click($SaveTaskButton_Click)
$MigrationForm.Controls.Add($SaveTaskButton)
# End Save Task Button
# Start Load Task Button
$ReloadTaskButton.TabIndex = 0
$ReloadTaskButton.Name = 'ReloadTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ReloadTaskButton.Size = $System_Drawing_Size
$ReloadTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ReloadTaskButton.UseVisualStyleBackColor = $True
$ReloadTaskButton.Enabled = $false
$ReloadTaskButton.Text = 'Reload Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 912
$System_Drawing_Point.Y = 450
$ReloadTaskButton.Location = $System_Drawing_Point
$ReloadTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ReloadTaskButton.add_Click($ReloadTaskButton_Click)
$MigrationForm.Controls.Add($ReloadTaskButton)
# End Load Task Button
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $MigrationForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$MigrationForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$MigrationForm.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Invoke-MoveRequest.ps1
|
Invoke-MoveRequest.ps1
|
###########################################################################
#
# NAME: Invoke-MoveRequest.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jer@powershell.no
#
# COMMENT: Script to use when migrating mailboxes to Microsoft Exchange Server 2010 Cross-Forest. Prepares user objects already
# moved to the target forest using Active Directory Migration Tool or other tools, and then invokes the mailbox move request.
# For more information, see the following blog-post: http://blog.powershell.no/2010/04/23/exchange-server-2010-cross-forest-migration
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 23.04.2010 - Initial release
#
###########################################################################
#Adding Quest AD PowerShell Commands Snapin and Microsoft Exchange Server 2010 PowerShell Snapin
Add-PSSnapin Quest.ActiveRoles.ADManagement
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
#Custom variables, edit this section
$TargetDatabase = "Mailbox Database A"
$TargetDeliveryDomain = "domain.com"
$TargetForest="DomainA.local"
$SourceForest="domainB.local"
$SourceForestGlobalCatalog = "dc-01.domainB.local"
$SourceForestCredential = Get-Credential -Credential "Domain\\SourceForestAdministrator"
#Connect to source forest to collect users to migrate
Connect-QADService -Service $SourceForest | Out-Null
$SourceForestUsersToMigrate = Get-QADUser -SearchRoot "DomainA.local/Department A/Users"
foreach ($user in $SourceForestUsersToMigrate) {
Write-Host "Processing user $user" -ForegroundColor Yellow
#Connect to source forest to collect source object attributes
Connect-QADService -Service $SourceForest | Out-Null
$TargetObject=$user.samaccountname
$SourceObject=Get-QADUser $samaccountname -IncludeAllProperties
$mail=$SourceObject.Mail
$mailNickname=$SourceObject.mailNickname
[byte[]]$msExchMailboxGUID=(Get-QADuser $samaccountname -IncludedProperties msExchMailboxGUID -DontConvertValuesToFriendlyRepresentation).msExchMailboxGUID
$msExchRecipientDisplayType="-2147483642"
$msExchRecipientTypeDetails="128"
$msExchUserCulture=$SourceObject.msExchUserCulture
$msExchVersion="44220983382016"
$proxyAddresses=$SourceObject.proxyAddresses
$targetAddress=$SourceObject.Mail
$userAccountControl=514
#Connect to target forest to set target object attributes
Connect-QADService -Service $TargetForest | Out-Null
Set-QADUser -Identity $TargetObject -ObjectAttributes @{mail=$mail;mailNickname=$mailNickname;msExchMailboxGUID=$msExchMailboxGUID;msExchRecipientDisplayType=$msExchRecipientDisplayType;msExchRecipientTypeDetails=$msExchRecipientTypeDetails;msExchUserCulture=$msExchUserCulture;msExchVersion=$msExchVersion;proxyAddresses=$proxyAddresses;targetAddress=$targetAddress;userAccountControl=$userAccountControl;msExchUserCulture=$msExchUserCulture} | Out-Null
#Update Exchange-attributes (LegacyExchangeDN etc.)
Get-MailUser $TargetObject | Update-Recipient
#Invoking a new move-request
New-MoveRequest -Identity $TargetObject -RemoteLegacy -TargetDatabase $TargetDatabase -RemoteGlobalCatalog $SourceForestGlobalCatalog -RemoteCredential $SourceForestCredential -TargetDeliveryDomain $TargetDeliveryDomain
#Enable target object and unset "User must change password at next logon"
Enable-QADUser -Identity $TargetObject | Out-Null
Set-QADUser -Identity $TargetObject -UserMustChangePassword $false | Out-Null
}
|
PowerShellCorpus/PoshCode/Google Chromium Download_2.ps1
|
Google Chromium Download_2.ps1
|
<#
.Synopsis
Download Google Chromium if there is a later build.
.Description
Download Google Chromium if there is a later build.
http://poshcode.org/2422
#>
Set-StrictMode -Version Latest
Import-Module bitstransfer
# comment out when not debugging
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"
$versionFile = "$Env:temp\\latestChromiumVersion.txt"
$installedChromiumVersion = 0
trap [Exception] {
write-host
write-error $("TRAPPED: " + $_.Exception.GetType().FullName);
write-error $("TRAPPED: " + $_.Exception.Message);
[string]($installedChromiumVersion) > $versionFile
exit;
}
if (Test-Path $versionFile)
{ $installedChromiumVersion = [int32] (cat $versionFile) }
#$latestChromiumBuildURL ="http://build.chromium.org/f/chromium/snapshots/chromium-rel-xp"
#$latestChromiumBuildURL ="http://build.chromium.org/f/chromium/snapshots/Win"
$latestChromiumBuildURL ="http://commondatastorage.googleapis.com/chromium-browser-snapshots/Win"
Start-BitsTransfer "$latestChromiumBuildURL/LAST_CHANGE" $versionFile
$latestChromiumVersion = [int32] (cat $versionFile)
if ($installedChromiumVersion -eq $latestChromiumVersion)
{
Write-Verbose "Exiting... Version $installedChromiumVersion is the latest. (from $latestChromiumBuildURL/LAST_CHANGE)"
return
}
$installerAppName = "mini_installer"
$installer = "$Env:temp\\$installerAppName.exe"
Write-Verbose "Initiating download of new version $latestChromiumVersion"
Start-BitsTransfer "$latestChromiumBuildURL/$latestChromiumVersion/mini_installer.exe" $installer
Write-Verbose "Installing new version of Chromium"
Invoke-Item $installer
$installerRunning = 1
while (!($installerRunning -eq $null))
{
sleep 5
$installerRunning = ( Get-Process | ? {$_.ProcessName -match "$installerAppName"} )
}
Write-Verbose "New Chromium Installed! Please restart the Chromium browser"
|
PowerShellCorpus/PoshCode/Remove diacritics.ps1
|
Remove diacritics.ps1
|
### Grťgory Schiro, 2009
### <summary>
### Removes diacritics from string.
### </summary>
### <param name="String">String containing diacritics</param>
function Remove-Diacritics([string]$String)
{
$objD = $String.Normalize([Text.NormalizationForm]::FormD)
$sb = New-Object Text.StringBuilder
for ($i = 0; $i -lt $objD.Length; $i++) {
$c = [Globalization.CharUnicodeInfo]::GetUnicodeCategory($objD[$i])
if($c -ne [Globalization.UnicodeCategory]::NonSpacingMark) {
[void]$sb.Append($objD[$i])
}
}
return("$sb".Normalize([Text.NormalizationForm]::FormC))
}
|
PowerShellCorpus/PoshCode/Get-CryptoBytes_2.ps1
|
Get-CryptoBytes_2.ps1
|
function Get-CryptoBytes {
#.Synopsis
# Generate Cryptographically Random Bytes
#.Description
# Uses RNGCryptoServiceProvider to generate arrays of random bytes
#.Parameter Count
# How many bytes to generate
#.Parameter AsString
# Output hex-formatted strings instead of byte arrays
param(
[Parameter(ValueFromPipeline=$true)]
@@# - array indicator not required
[int]$count = 64
,
[switch]$AsString
)
begin {
$RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$OFS = ""
}
process {
foreach($length in $count) {
$bytes = New-Object Byte[] $length
$RNGCrypto.GetBytes($bytes)
if($AsString){
Write-Output ("{0:X2}" -f $bytes)
} else {
Write-Output $bytes
}
}
}
end {
$RNGCrypto = $null
}
}
|
PowerShellCorpus/PoshCode/Get-NaNfsExport_1.ps1
|
Get-NaNfsExport_1.ps1
|
# Glenn Sizemore ~ www . Get-Admin . Com
# Example Powershell function to get the NFS Exports from a NetApp Filer
# First you'll need to download the OnTap SDK 3.5 : http://communities.netapp.com/docs/DOC-1365
# within the download your interested in .\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll
# Next load the library...
# $Path = 'C:\\Users\\glnsize\\Downloads\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll'
# [Reflection.Assembly]::LoadFile($Path)
#
# Almost there next step create a NaServer connection object
# Here we are connecting to the NetApp Filer TOASTER1, and setting the api to V1.8
# $NaServer = New-Object NetApp.Manage.NaServer("TOASTER1",1,8)
# Call the setAdminUser Method and supply some credentials
# $NaServer.SetAdminUser('root', 'password')
#
# Now we're ready to go simply call the function passing your NAServer object as a parameter.
# Get-NaNfsExport -Server $NaServer
#
# Get-NaNfsExport -Server $NaServer -Path /vol/vol0
Function Get-NaNfsExport {
Param(
[NetApp.Manage.NaServer]
$Server,
[String]
$Path
)
Begin {
$out = @()
}
Process {
trap [NetApp.Manage.NaAuthException] {
# Example trap to catch bad credentials
Write-Error "Bad login/password".
break
}
#generate a new naelement request
$NaOut = New-Object NetApp.Manage.NaElement("nfs-exportfs-list-rules")
# $NaServer.InvokeElem($NaOut) -> retrieve the results of the $NaOut request
# ..($NaOut).GetChildByName("rules") -> select the rules element from results
# ..GetChildByName("rules").getchildren() -> get any child elements under rules.
$NaResults = $Server.InvokeElem($NaOut).GetChildByName("rules").getchildren()
#ForEach NFS Rule returned, serialize the output into a PSObject.
foreach ($NaElement in $NaResults) {
$NaNFS = "" | Select-Object Path, ActualPath, ReadOnly, ReadWrite, Root, Security
$NaNFS.Path = $NaElement.GetChildContent("pathname")
# This is where the OnTap SDK can get a little nuts...
# if you perfer XML then simply try $NaElement.ToPrettyString('')
switch ($NaElement) {
# if Read-Only is present
{$_.GetChildByName("read-only")}
{
# Get all child elements
$ReadOnly = ($_.GetChildByName("read-only")).getchildren()
#Foreach elm in read-only
foreach ($read in $ReadOnly) {
# [bool] if exists "all-hosts"
If ($read.GetChildContent("all-hosts")) {
$roList = 'All-Hosts'
}
# Else get the name of the export!
Elseif ($read.GetChildContent("name")) {
$roList += $read.GetChildContent("name")
}
}
# add our new list to the output
$NaNFS.ReadOnly = $roList
}
# if Read-write is present
{$_.GetChildByName("read-write")}
{
$ReadWrite = ($_.GetChildByName("read-write")).getchildren()
foreach ($write in $ReadWrite) {
If ($write.GetChildContent("all-hosts")) {
$rwList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rwList += $write.GetChildContent("name")
}
}
$NaNFS.ReadWrite = $rwList
}
# if root is present
{$_.GetChildByName("root")}
{
$Root = ($_.GetChildByName("root")).getchildren()
foreach ($r in $Root) {
If ($r.GetChildContent("all-hosts")) {
$rrList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rrList += $r.GetChildContent("name")
}
}
$NaNFS.Root = $rrList
}
{$_.GetChildByName("sec-flavor")}
{
$Security = ($_.GetChildByName("sec-flavor")).getchildren()
foreach ($s in $Security) {
if ($r.GetChildContent("flavor")) {
$SecList += $r.GetChildContent("flavor")
}
}
$NaNFS.Security = $SecList
}
{$_.GetChildByName("actual-pathname")}
{
$NaNFS.ActualPath = $_.GetChildByName("actual-pathname")
}
# needed for mixed vol reporting...
{!$_.GetChildByName("actual-pathname")}
{
$NaNFS.ActualPath = $_.GetChildContent("pathname")
}
}
$out += $NaNFS
}
}
End {
If ($Path) {
return $out | ?{$_.Path -match $Patch}
}
else {
return $out
}
}
}
|
PowerShellCorpus/PoshCode/Hack ESX MOTD_1.ps1
|
Hack ESX MOTD_1.ps1
|
$screen = @"
You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
"@
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/DS L Order brneanew game.ps1
|
DS L Order brneanew game.ps1
|
# Version: 0.1
# Author: Stefan Stranger
# Description: Retrieve Dell Order Status
# Start Page Order Status USA: https://support.dell.com/support/order/status.aspx?c=us&cs=19&l=en&s=dhs&~ck=pn
# Start Page Order Status EMEA(nl): http://support.euro.dell.com/support/index.aspx?c=nl&l=nl&s=gen&~ck=bt
# Example Dell Order Status URL: http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=[IR Number]&ea=[emailaddress]'
#param ([string]$url = $(read-host "Please enter Dell Order Status URL"))
$wc = New-Object System.Net.WebClient
$url = 'http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=NL0131-8510-29070&ea=stefan.stranger@getronics.com'
$RawResult = $wc.DownloadString($url)
# $RawResult = gc orderstatus.txt
# Search for the Estimated Delivery Date in the url that starts with the word "lever" (Levering is the Dutch word for Delivery" and
# and ends with </B></TD></TR>
# You should probable need to change the string "Lever" in "Deliv" or something
$r = New-Object regex('Lever.*?(\\d+-\\d+-\\d{4})</B></TD></TR>','SingleLine' )
# String block with the Estimated Delivery Date
$m = $r.Matches($RawResult)
# Extract Delivery Date from string block
$date = ($m |% {$_.groups[1].value })
# Search for Current Order Status ("In preproduction" is Dutch for "In preproduction"
$r = New-Object regex('target="popup:640x480">(.*?)</a>' )
$m = $r.Matches($RawResult)
$status = ($m |% {$_.groups[1].value })
$Orderstatus = 1 | select @{name='Status';expression={$status[0]}},@{name='Estimated Delivery Date';expression={$date}}
$Orderstatus | ft -a
#[string]$output = $orderstatus
$startdate = "16-09-2007"
$startdate
$currentdate = (get-date).ToString('MM-dd-yyyy')
$currentdate
$date
|
PowerShellCorpus/PoshCode/Findup_9.ps1
|
Findup_9.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace Findup
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
}
public byte[] SHA512_1st1K = new byte[64];
public byte[] SHA512_All = new byte[64];
public FileInfo FI { get; private set; }
public bool Checked { get; set; }
public bool SHA512_1st1KSet { get; set; }
public bool SHA512_AllSet { get; set; }
}
class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (E.G. *.txt), and in directories in pathRec, to returnList
{
public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
foreach (string d in pathRec)
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
return;
}
public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
if (File.Exists(pathRec))
{
try
{
returnList.Add(new FileInfoExt(new FileInfo(pathRec)));
}
catch (Exception e)
{
Console.WriteLine("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
returnList.Add(new FileInfoExt(addf));
}
}
catch (Exception e)
{
Console.WriteLine("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
foreach (string d in (Directory.GetDirectories(pathRec)))
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
}
catch (Exception e)
{
Console.WriteLine("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
string filePart = Path.GetFileName(pathRec);
string dirPart = Path.GetDirectoryName(pathRec);
if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
Recursive(dirPart, filePart, recursiveFlag, returnList);
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
catch (Exception e)
{
Console.WriteLine("Parse error on: " + pathRec);
Console.WriteLine("Make sure you don't end a directory with a \\\\ when using quotes. The console arg parser doesn't accept that.");
Console.WriteLine("Exception: " + e.Message);
return;
}
}
return;
}
}
class Findup
{
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
System.Boolean b4b = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long bytesInDupes = 0; // bytes in all the duplicates
long numOfDupes = 0; // number of duplicate files found.
long bytesRec = 0; // number of bytes recovered.
long delFiles = 0; // number of files deleted.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Might be much slower, but most secure.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" findup.exe c:\\\\data .\\\\*.txt c:\\\\reports\\\\quarter.doc -recurse -b4b");
Console.WriteLine(" ");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
continue;
}
if (System.String.Compare(args[i], "-delete", true) == 0)
{
delete = true;
continue;
}
if (System.String.Compare(args[i], "-noprompt", true) == 0)
{
noprompt = true;
continue;
}
if (System.String.Compare(args[i], "-b4b", true) == 0)
{
b4b = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
return;
}
Recurse recurseMe = new Recurse();
recurseMe.Recursive(paths, "*.*", recurse, fs);
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
return;
}
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomNumber); // get 512-bit SHA-512 salt.
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Checked == true) // If file was already matched, then skip to next.
continue;
for (c = i + 1; c < fs.Count; c++)
{
if (fs[c].Checked == true) // skip already matched inner loop files.
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1KSet == false) // check/hash first 1K first.
if (Compute1KHash(fs[i]) == false)
continue;
if (fs[c].SHA512_1st1KSet == false)
if (Compute1KHash(fs[c]) == false)
continue;
if (CompareHash(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash..
continue;
if (b4b == true) // byte for byte comparison specified?
{
if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function
continue;
}
else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_AllSet == false) // check/hash the rest of the files.
if (ComputeFullHash(fs[i]) == false)
continue;
if (fs[c].SHA512_AllSet == false)
if (ComputeFullHash(fs[c]) == false)
continue;
if (CompareHash(fs[i].SHA512_All, fs[c].SHA512_All) == false)
continue;
}
Console.WriteLine("Match : " + fs[i].FI.FullName);
Console.WriteLine("with : " + fs[c].FI.FullName);
fs[c].Checked = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates.
if (delete != true) // if delete is specified, try to delete the duplicate file.
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y'))
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length;
delFiles++;
}
catch (Exception e)
{
Console.WriteLine("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("Files checked : {0:N0}", fs.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes);
Console.WriteLine("Duplicates deleted : {0:N0}", delFiles);
Console.WriteLine("Recovered bytes : {0:N0}", bytesRec);
return;
}
private static Boolean B4b(string path1, string path2)
{
try
{
using (var stream = File.OpenRead(path1))
{
using (var stream2 = File.OpenRead(path2))
{
System.Boolean EOF = false;
do
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length);
if (length != length2)
return false;
if (length != largeBuf.Length)
EOF = true;
int i = 0;
while (i < length)
{
if (largeBuf[i] != largeBuf2[i])
return false;
i++;
}
} while (EOF == false);
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine("Byte for Byte comparison failed: " + e.Message);
return false;
}
}
private static Boolean CompareHash(byte[] hash1, byte[] hash2)
{
int i = 0;
while (i < hash1.Length)
{
if (hash1[i] != hash2[i])
return false;
i++;
}
return true ;
}
private static readonly byte[] readBuf = new byte[1024 + 64];
private static readonly byte[] largeBuf = new byte[10240 + 64];
private static readonly byte[] largeBuf2 = new byte[10240 + 64];
private static readonly byte[] randomNumber = new byte[64];
private static byte[] hash = new byte[64];
private static bool Compute1KHash(FileInfoExt path)
{
Buffer.BlockCopy(randomNumber, 0, readBuf, 0, randomNumber.Length);
try
{
using (var stream = File.OpenRead(path.FI.FullName))
{
var length = stream.Read(readBuf, hash.Length, readBuf.Length - hash.Length);
hash = SHA512.Create().ComputeHash(readBuf, 0, length + hash.Length);
Buffer.BlockCopy(hash, 0, path.SHA512_1st1K, 0, hash.Length);
path.SHA512_1st1KSet = true;
return true;
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return false;
}
}
private static bool ComputeFullHash(FileInfoExt path)
{
Buffer.BlockCopy(randomNumber, 0, largeBuf, 0, randomNumber.Length);
try
{
var _SHA = SHA512.Create();
using (var stream = File.OpenRead(path.FI.FullName))
{
System.Boolean EOF = false;
while (EOF == false)
{
var length = stream.Read(largeBuf, hash.Length, largeBuf.Length - hash.Length);
if (length != (largeBuf.Length - hash.Length))
EOF = true;
hash = _SHA.ComputeHash(largeBuf, 0, length + hash.Length);
Buffer.BlockCopy(hash, 0, largeBuf, 0, hash.Length);
}
}
Buffer.BlockCopy(hash, 0, path.SHA512_All, 0, hash.Length);
path.SHA512_AllSet = true;
return true;
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return false;
}
}
}
}
|
PowerShellCorpus/PoshCode/Asp.net-Using httpConext.ps1
|
Asp.net-Using httpConext.ps1
|
@@ Default.aspx
@@----------------
Partial Class _Default
Inherits System.Web.UI.Page
Dim var1 As String
Dim var2 As String
Protected Sub lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnk.Click
Context.Items("Nome") = var1
Context.Items("Email") = var2
Server.Transfer("pagina3.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
var1 = "20091005"
var2 = "20091106"
End Sub
End Class
@@pagina3.aspx
@@--------------------------
Partial Class pagina3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim context As HttpContext = HttpContext.Current
Label1.Text = CStr(context.Items("Nome"))
Label2.Text = CStr(context.Items("Email"))
End Sub
End Class
|
PowerShellCorpus/PoshCode/Script logging_1.ps1
|
Script logging_1.ps1
|
#region Log File Management
$ScriptName = $MyInvocation.mycommand.name
$LocalAppDir = "$(gc env:LOCALAPPDATA)\\PS_Data"
$LogName = $ScriptName.replace(".ps1", ".log")
$MaxLogFileSizeMB = 5 # After a log file reaches this size it will archive the existing and create a new one
trap
[Exception] {
sendl
"error: $($_.Exception.GetType().Name) - $($_.Exception.Message)"
}
function LogFileCheck
{
if (!(Test-Path $LocalAppDir)) # Check if log file directory exists - if not, create and then create log file for this script.
{
mkdir $LocalAppDir
New-Item "$LocalAppDir\\$LogName" -type file
break
}
if
(Test-Path "$LocalAppDir\\$LogName") {
if (((gci "$LocalAppDir\\$LogName").length/1MB) -gt $MaxLogFileSizeMB) # Check size of log file - to stop unweildy size, archive existing file if over limit and create fresh.
{
$NewLogFile = $LogName.replace(".log", " ARCHIVED $(Get-Date -Format dd-MM-yyy-hh-mm-ss).log")
ren "$LocalAppDir\\$LogName" "$LocalAppDir\\$NewLogFile"
}
}
}
function sendl ([string]$message) # Send to log file
{
$toOutput
= "$(get-date) > $message " | Out-File "$LocalAppDir\\$LogName" -append -NoClobber
}
LogFileCheck
#endregion Log File Management
|
PowerShellCorpus/PoshCode/NPS Server Synchronize_1.ps1
|
NPS Server Synchronize_1.ps1
|
###Network Policy Server Synchronization Script
#This script copies the configuration from the NPS Master Server and imports it on this server.
#The Account that this script runs under must have Local Administrator rights to the NPS Master.
#This was designed to be run as a scheduled task on the NPS Secondary Servers on an hourly,daily, or as-needed basis.
#Last Modified 01 Dec 2009 by JGrote <jgrote AT enpointe NOSPAM-DOTCOM>
###Variables
#NPSMaster - Your Primary Network Policy Server you want to copy the config from.
$NPSMaster = "Server1"
#NPSConfigTempFile - A temporary location to store the XML config. Use a UNC path so that the primary can save the XML file across the network. Be sure to set secure permissions on this folder, as the configuration including pre-shared keys is temporarily stored here during the import process.
$NPSConfigTempFile = "\\\\server2\\C$\\Temp\\NPSConfigTemp\\NPSConfig-$NPSMaster.xml"
#Create an NPS Sync Event Source if it doesn't already exist
if (!(get-eventlog -logname "System" -source "NPS-Sync")) {new-eventlog -logname "System" -source "NPS-Sync"}
#Write an error and exit the script if an exception is ever thrown
trap {write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Error" -Message "An Error occured during NPS Sync: $_. Script run from $($MyInvocation.MyCommand.Definition)"; exit}
#Connect to NPS Master and export configuration
$configExportResult = invoke-command -ComputerName $NPSMaster -ArgumentList $NPSConfigTempFile -scriptBlock {param ($NPSConfigTempFile) netsh nps export filename = $NPSConfigTempFile exportPSK = yes}
#Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script.
$NPSConfigTest = Get-Item $NPSConfigTempFile
#Clear existing configuration and import new NPS config
$configClearResult = netsh nps reset config
$configImportResult = netsh nps import filename = $NPSConfigTempFile
#Delete Temporary File
remove-item -path $NPSConfigTempFile
#Compose and Write Success Event
$successText = "Network Policy Server Configuration successfully synchronized from $NPSMaster.
Export Results: $configExportResult
Import Results: $configImportResult
Script was run from $($MyInvocation.MyCommand.Definition)"
write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Information" -Message $successText
|
PowerShellCorpus/PoshCode/Ping Alert Script_2.ps1
|
Ping Alert Script_2.ps1
|
#Email Alert Parameters
$to = "user@mydomain.com"
$from = "unreachable@mydomain.com"
$smtpserver = "my_exchange_server"
#Array of computers to test
$Computers = ("comp1" , "comp2" , "comp3" , "comp4")
#Variable to hold INT value 0
$zero = 0
Foreach ($Computer in $Computers)
{
if
(
#Checks for a file with the host computers name in the Reports folder and if it doesn't exist creates it with content 0
Test-Path $("C:\\Reports\\" + $Computer + ".txt")
)
{
}
else
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
}
#Reads the content of the file and saves to variable as text
$FailedPings = Get-Content $("C:\\Reports\\" + $Computer + ".txt")
#Converts the value to INT
$INT_FailedPings = [INT]$FailedPings
#Actually runs the ping test
$PingTest = Test-Connection -ComputerName $Computer -count 1
if
(
#If ping is unsuccessful
$PingTest.StatusCode -ne "0"
)
{
if
(
#If previous failed pings value is less or equal to 3
$INT_FailedPings -le 3
)
{
#Increment the value by 1
$INT_FailedPings++
#Write the value out to the reports folder file for this host
$INT_FailedPings > $("C:\\Reports\\" + $Computer + ".txt")
#Send an alert of failed ping
Send-MailMessage -to $to -subject "Warning, Host $Computer is down. You will only receive 4 of these messages!" -from $from -body "Ping to $Computer failed, you will only receive 3 of these messages!" -smtpserver $smtpserver
}
}
elseif
(
#If previous checks have failed the value will be non zero, as checks are now working sets the value back to zero and alerts that host is back up
$INT_FailedPings -ne 0
)
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
Send-MailMessage -to $to -subject "Host $Computer is back up" -from $from -body "Panic over" -smtpserver $smtpserver
}
else
#If ping is successful and past pings were successful do nothing
{
}
}
|
PowerShellCorpus/PoshCode/Windows Startup Script_4.ps1
|
Windows Startup Script_4.ps1
|
<#======================================================================================
File Name : Startup.ps1
Original Author : Kenneth C. Mazie
:
Description : This is a Windows start-up script with pop-up notification and checks to
: assure things are not executed if already running or set. It can be run
: as a personal start-up script or as a domain start-up (with some editing).
: It is intended to be executed from the Start Menu "All Programs\\Startup" folder.
:
: The script will Start programs, map shares, set routes, and can email the results
: if desired. The email subroutine is commented out. You'll need to edit it yourself.
: When run with the "debug" variable set to TRUE it also displays status in the
: PowerShell command window. Other wise all operation statuses are displayed in pop-up
: balloons near the system tray.
:
: To call the script use the following in a shortcut or in the RUN registry key.
: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden –Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}"
: Change the script name and path as needed to suit your environment.
:
: Be sure to edit all sections to suit your needs before executing. Be sure to
: enable sections you wish to run by un-commenting them at the bottom of the script.
:
: Route setting is done as a function of selecting a specific Network Adapter with the intent
: of manually altering your routes for hardline or WiFi connectivity. This section you will
: need to customize to suit your needs or leave commented out. This allowed me to
: alter the routing for my office (Wifi) or lab (hardline) by detecting whether my
: laptop was docked or not. The hardline is ALWAYS favored as written.
:
: To identify process names to use run "get-process" by itself to list process
: names that PowerShell will be happy with, just make sure each app you want to
: identify a process name for is already running first.
:
: A 2 second sleep delay is added to smooth out processing but can be removed if needed.
:
Notes : Sample script is safe to run as written, it will only load task manager and Firefox.
: In general, I did not write this script for ease of readability. Most commands are
: one-liner style, sorry if that causes you grief.
:
Warnings : Drive mapping passwords are clear text within the script.
:
:
Last Update by : Kenneth C. Mazie (kcmjr AT kcmjr.com to report issues)
Version History : v1.0 - 05-03-12 - Original
Change History : v2.0 - 11-15-12 - Minor edits
: v3.0 - 12-10-12 - Converted application commands to arrays
: v4.0 - 02-14-13 - Converted all other sections to arrays
: v4.1 - 02-17-13 - Corrected error with pop-up notifications
=======================================================================================#>
clear-host
$Debug = $True
$CloudStor = $False
$ScriptName = "Startup Script"
#--[ Prep Pop-up Notifications ]--
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Icon = [System.Drawing.SystemIcons]::Information
$Notify = new-object system.windows.forms.notifyicon
$Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none
$Notify.visible = $true
#--[ Force to execute with admin priviledge ]--
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object Security.Principal.WindowsPrincipal $identity
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) {$Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path;Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs;exit}
if ($debug){write-host "`n------[ Running with Admin Privileges ]------`n" -ForegroundColor DarkCyan}
$Notify.ShowBalloonTip(2500,$ScriptName,"Script is running with full admin priviledges",[system.windows.forms.tooltipicon]::Info)
if ($debug){write-host "Running in DEBUG Mode..." -ForegroundColor DarkCyan}
function Pause-Host { #--[ Only use if you need a countdown timer ]--
param($Delay = 10)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($Delay-- -ne $counter )) #--count down
#While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay )) #--count up
{
clear-host
if ($debug){Write-Host "testing... $Delay"} #--count down
#Write-Host "testing... $counter" #--count up
[Threading.Thread]::Sleep(1000)
}
}
Function SetRoutes { #--[ Array consists of Network, Mask ]--
$RouteArray = @()
$RouteArray += , @("10.0.0.0","255.0.0.0")
$RouteArray += , @("172.1.0.0","255.255.0.0")
$RouteArray += , @("192.168.1.0","255.255.255.0")
#--[ Add more route entries here... ]--
$Index = 0
Do {
$RouteNet = $ShareArray[$Index][0]
$RouteMask = $ShareArray[$Index][1]
iex "route delete $RouteNet"
Sleep (2)
iex "route add $RouteNet mask $RouteMask $IP"
Sleep (2)
$Index++
}
While ($Index -lt $RouteArray.length)
}
Function SetMappings { #--[ Array consists of Drive Letter, Path, User, and Password ]--
$ShareArray = @()
$ShareArray += , @("J:","\\\\192.168.1.250\\Share1","username","password")
$ShareArray += , @("K:","\\\\192.168.1.250\\Share2","username","password")
#--[ Add more mapping entries here... ]--
$Index = 0
Do {
$MapDrive = $ShareArray[$Index][0]
$MapPath = $ShareArray[$Index][1]
$MapUser = $ShareArray[$Index][2]
$MapPassword = $ShareArray[$Index][3]
$net = $(New-Object -Com WScript.Network)
if ( Exists-Drive $MapDrive){$Notify.ShowBalloonTip(2500,$ScriptName,"Drive $MapDrive is already mapped...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Drive $MapDrive already mapped" -ForegroundColor DarkRed}}else{if (test-path $MapPath){$net.MapNetworkDrive($MapDrive, $MapPath, "False",$MapUser,$MapPassword);$Notify.ShowBalloonTip(2500,$ScriptName,"Mapping Drive $MapDrive...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Mapping Drive $MapDrive" -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Cannot Map Drive $MapDrive - Target Not Found...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cannot Map Drive $MapDrive - Target Not Found" -ForegroundColor DarkRed}}}
Sleep (2)
$Index++
}While ($Index -lt $ShareArray.length)
}
Function Exists-Drive {
param($driveletter)
(New-Object System.IO.DriveInfo($driveletter)).DriveType -ne 'NoRootDirectory'
}
Function LoadApps { #--[ Array consists of Process Name, File Path, Arguements, Title ]--
$AppArray = @()
$AppArray += , @("firefox","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe","https://www.google.com","FireFox")
#--[ Add more app entries here... ]--
#--[ Cloud Storage Provider Subsection ]--
if (!$CloudStor ){$Notify.ShowBalloonTip(2500,$ScriptName,"Cloud Providers Bypassed...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cloud Providers Bypassed..." -ForegroundColor Magenta;}}
else
{
$AppArray += , @("googledrivesync","C:\\Program Files (x86)\\Google\\Drive\\googledrivesync.exe","/autostart","GoogleDrive")
#--[ Add more cloud entries here... ]--
}
$AppArray += , @("taskmgr","C:\\Windows\\System32\\taskmgr.exe"," ","Task Manager")
#--[ Add more app entries here... ]--
$Index = 0
Do {
$AppProcess = $AppArray[$Index][0]
$AppExe = $AppArray[$Index][1]
$AppArgs = $AppArray[$Index][2]
$AppName = $AppArray[$Index][3]
If((get-process -Name $AppProcess -ea SilentlyContinue) -eq $Null){start-process -FilePath $AppExe -ArgumentList $AppArgs ;$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is loading...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Loading" $AppName "..." -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is already running...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "$AppName Already Running..." -ForegroundColor DarkRed } }
Sleep (2)
$Index++
}
While ($Index -lt $AppArray.length)
}
<#
function SendMail {
#param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
param($To, $From, $Subject, $Body, $smtpServer)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $From
$msg.To.Add($To)
$msg.Subject = $Subject
$msg.IsBodyHtml = 1
$msg.Body = $Body
$smtp.Send($msg)
}
#>
Function IdentifyNics {
$Domain1 = "LabDomain.com"
$Domain2 = "OfficeDomain.com"
#--[ Detect Network Adapters ]--
$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" }
#--[ Alternate detection methods]--
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } | where {$_.DNSDomainSuffixSearchOrder -match $Domain2}
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller" }
$WiredIP = ([string]$Wired.IPAddress).split(" ")
$WiredDesc = $Wired.Description
if ($debug){
write-host "Name: " $Wired.Description`n"DNS Domain: " $Wired.DNSDomainSuffixSearchOrder`n"IPv4: " $WiredIP[0]`n"IPv6: " $WiredIP[1]`n""
if ($WiredIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiredDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Hardline not detected",[system.windows.forms.tooltipicon]::Info)}
}
sleep (2)
$WiFi = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Intel(R) Centrino(R) Advanced-N 6250 AGN" }
$WiFiIP = ([string]$WiFi.IPAddress).split(" ")
$WiFiDesc = $WiFi.Description
write-host "Name: " $WiFi.Description`n"DNS Domain: " $WiFi.DNSDomainSuffixSearchOrder`n"IPv4: " $WiFiIP[0]`n"IPv6: " $WiFiIP[1]
if ($WiFiIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiFiDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"WiFi not detected",[system.windows.forms.tooltipicon]::Info)}
sleep (2)
#--[ Set Routes ]--
if ($WiredIP[0]) { #--[ The hardline is connected. Favor the hardline if both connected ]--
$IP = $WiredIP[0]
if ($Wired.DNSDomainSuffixSearchOrder -like $Domain1 -or $Wired.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ the hardline is connected ]--
write-host ""`n"Setting routes for hardline"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for hardline...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
} else {
if ($WiFiIP[0]) {
if ($WiFi.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ The wifi is connected --]
$IP = $WiFiIP[0]
write-host ""`n"Setting routes for wifi"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for wifi...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
}
}
}
#Write-Host $IP
#IdentifyNics
#SetMappings
#Pause-Host
LoadApps
If ($debug){write-host "Completed All Operations..." -ForegroundColor DarkCyan}
|
PowerShellCorpus/PoshCode/LibraryInputComparison.p.ps1
|
LibraryInputComparison.p.ps1
|
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nSet-StrictMode -Version Latest\n\n## Process each element in the pipeline, using a\n## foreach statement to visit each element in $input\nfunction Get-InputWithForeach($identifier)\n{\n Write-Host "Beginning InputWithForeach (ID: $identifier)"\n\n foreach($element in $input)\n {\n Write-Host "Processing element $element (ID: $identifier)"\n $element\n }\n\n Write-Host "Ending InputWithForeach (ID: $identifier)"\n}\n\n## Process each element in the pipeline, using the\n## cmdlet-style keywords to visit each element in $input\nfunction Get-InputWithKeyword($identifier)\n{\n begin\n {\n Write-Host "Beginning InputWithKeyword (ID: $identifier)"\n }\n\n process\n {\n Write-Host "Processing element $_ (ID: $identifier)"\n $_\n }\n\n end\n {\n Write-Host "Ending InputWithKeyword (ID: $identifier)"\n }\n}
|
PowerShellCorpus/PoshCode/Invoke-Switch v0.9.ps1
|
Invoke-Switch v0.9.ps1
|
New-Variable castDictionaryEntries
[System.Func[System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[System.Collections.DictionaryEntry]]] `
$castDictionaryEntries = [System.Delegate]::CreateDelegate(
[System.Func[System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[System.Collections.DictionaryEntry]]],
[System.Linq.Enumerable].GetMethod(
'Cast', @('Public, Static')).MakeGenericMethod(
@([System.Collections.DictionaryEntry])))
Set-Variable castDictionaryEntries -Option ReadOnly
function Invoke-Switch {
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Collections.IDictionary] $CaseMap,
[Parameter(Position=1, Mandatory=$false)]
[ValidateSet('Regex', 'Wildcard', 'Exact')]
[string] $SwitchMode,
[Parameter(Position=2, Mandatory=$false)]
$DefaultCase,
[Parameter(Position=3, Mandatory=$true, ValueFromPipeline=$true)]
[AllowNull()]
$InputObject,
[Parameter()]
[switch] $CaseSensitive)
begin {
New-Variable mode; [string] $mode = $null
if($PSBoundParameters.ContainsKey('SwitchMode')) {
$mode = " -$SwitchMode"
}
New-Variable caseOption; [string] $caseOption = $null
if($CaseSensitive.IsPresent) {
$caseOption = ' -CaseSensitive'
}
Set-Variable mode, caseOption -Option ReadOnly
New-Variable value
New-Variable cases; [string] $cases =
$castDictionaryEntries.Invoke($CaseMap) `
| % { $value = $_.Value; return $_.Key } `
| repr `
| % { return $_ } `
-End {
if($PSBoundParameters.TryGetValue(
'DefaultCase', [ref] $value))
{
Write-Output default
}
} `
| % { return "$_ { Write-Output (,$(repr $value)) }" } `
| Join-String -Separator ' '
Set-Variable cases -Option ReadOnly
New-Variable switchScript; [scriptblock] `
$switchScript = $PSCmdlet.InvokeCommand.NewScriptBlock(
"switch$mode$caseOption (`$InputObject) { $cases }")
Set-Variable switchScript -Option ReadOnly
$PSCmdlet.WriteDebug($switchScript)
}
process {
. $switchScript | % { $PSCmdlet.WriteObject($_) }
}
}
|
PowerShellCorpus/PoshCode/Test-Server_1.ps1
|
Test-Server_1.ps1
|
Function Test-Server{
[cmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$ComputerName,
[parameter(Mandatory=$false)]
[switch]$CredSSP,
[Management.Automation.PSCredential] $Credential)
begin{
$total = Get-Date
$results = @()
if($credssp){if(!($credential)){Write-Host "must supply Credentials with CredSSP test";break}}
}
process{
foreach($name in $computername)
{
$dt = $cdt= Get-Date
Write-verbose "Testing: $Name"
$failed = 0
try{
$DNSEntity = [Net.Dns]::GetHostEntry($name)
$domain = ($DNSEntity.hostname).replace("$name.","")
$ips = $DNSEntity.AddressList | %{$_.IPAddressToString}
}
catch
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$results += $rst
$failed = 1
}
Write-verbose "DNS: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($failed -eq 0){
foreach($ip in $ips)
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$rst.ip = $ip
$rst.domain = $domain
####RDP Check (firewall may block rest so do before ping
try{
$socket = New-Object Net.Sockets.TcpClient($name, 3389)
if($socket -eq $null)
{
$rst.RDP = $false
}
else
{
$rst.RDP = $true
$socket.close()
}
}
catch
{
$rst.RDP = $false
}
Write-verbose "RDP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
#########ping
if(test-connection $ip -count 1 -Quiet)
{
Write-verbose "PING: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
$rst.ping = $true
try{############wsman
Test-WSMan $ip | Out-Null
$rst.WSMAN = $true
}
catch
{$rst.WSMAN = $false}
Write-verbose "WSMAN: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($rst.WSMAN -and $credssp) ########### credssp
{
try{
Test-WSMan $ip -Authentication Credssp -Credential $cred
$rst.CredSSP = $true
}
catch
{$rst.CredSSP = $false}
Write-verbose "CredSSP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
try ########remote reg
{
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $ip) | Out-Null
$rst.remotereg = $true
}
catch
{$rst.remotereg = $false}
Write-verbose "remote reg: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
try ######### wmi
{
$w = [wmi] ''
$w.psbase.options.timeout = 15000000
$w.path = "\\\\$Name\\root\\cimv2:Win32_ComputerSystem.Name='$Name'"
$w | select none | Out-Null
$rst.RPC = $true
}
catch
{$rst.rpc = $false}
Write-verbose "WMI: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
else
{
$rst.ping = $false
$rst.wsman = $false
$rst.credssp = $false
$rst.remotereg = $false
$rst.rpc = $false
}
$results += $rst
}}
Write-Verbose "Time for $($Name): $((New-TimeSpan $cdt ($dt)).totalseconds)"
Write-Verbose "----------------------------"
}
}
end{
Write-Verbose "Time for all: $((New-TimeSpan $total ($dt)).totalseconds)"
Write-Verbose "----------------------------"
return $results
}
}
|
PowerShellCorpus/PoshCode/IniFile Functions 1.0.ps1
|
IniFile Functions 1.0.ps1
|
function Get-IniSection($inifile,$section)
{
$sections = select-string "^\\[.*\\]" $inifile
if(!$section) {
return $sections | %{$_.Line.Trim("[]")}
}
$start = 0
switch($sections){
{$_.Line.Trim() -eq "[$section]"}{
$start = $_.LineNumber -1
}
default {
if($start){
return (gc $inifile)[($start)..($start + ($_.LineNumber-2 - $start))]
}
}
}
$lines = gc $inifile
return $lines[$start..($lines.length-1)]
}
function Get-IniValue($inifile,$section,$name)
{
$section = Get-IniSection $inifile $section
($section | Select-String "^\\s*$name\\s*=").Line.Split("=",2)[1]
}
function Set-IniValue($inifile,$section,$name,$value)
{
$lines = gc $inifile
$sections = select-string "^\\[.*\\]" $inifile
$start,$end = 0,0
for($l=0; $l -lt $sections.Count; ++$l){
if($sections[$l].Line.Trim() -eq "[$section]") {
$start = $sections[$l].LineNumber
if($l+1 -ge $sections.Count) {
$end = $lines.length-1;
} else {
$end = $sections[$l+1].LineNumber -2
}
}
}
if($start -and $end) {
$done = $false
for($l=$start;$l -le $end;++$l){
if( $lines[$l] -match "^\\s*$name\\s*=" ) {
$lines[$l] = "{0} = {1}" -f $name, $value
$done = $true
break;
}
}
if(!$done) {
$output = $lines[0..$start]
$output += "{0} = {1}" -f $name, $value
$output += $lines[($start+1)..($lines.Length-1)]
$lines = $output
}
}
Set-Content $inifile $lines
}
##
## This is a ... different way of doing it,
## which will be faster if you need to read lots of values
#### HOWEVER ####
## I don't recommend using Set-IniFile, because it will loose any comments etc
##
function Get-IniFile {
param([string]$inifile=$(Throw "You must specify the name of an ini file!"))
$INI = @{}
$s,$k,$v = $null
foreach($line in (gc $inifile | ? {$_[0] -ne ";" -and $_.Trim().Length -gt 0})) {
$k,$v = $line.Split("=",2)
if($v -eq $null) {
$s = $k.Trim("[]")
$INI[$s] = @{}
} else {
$INI[$s][$k.Trim()] = $v.Trim()
}
}
return $INI
}
function Set-IniFile {
param([HashTable]$ini,[string]$inifile=$(Throw "You must specify the name of an ini file!"))
[string[]]$inistring = @()
foreach($section in $ini.Keys) {
#Add-Content $inifile ("[{0}]" -f $section)
$inistring += ("`n[{0}]" -f $section)
foreach($key in $ini[$section].Keys) {
$inistring += ("{0} = {1}" -f $key, $ini[$section][$key])
}
}
# make the write be atomic ...
Set-Content $inifile $inistring
}
|
PowerShellCorpus/PoshCode/Get-LeaderBoard.ps1
|
Get-LeaderBoard.ps1
|
<#
.SYNOPSIS
Pulls down the leaderboards for the 2011 Scripting Games
.DESCRIPTION
Quick and dirty script to pull down the leaderboards for the 2011 scripting games.
Can choose either beginner or advanced via a command line switch.
.PARAMETER Level
The leaderboard to parse
.EXAMPLE
Get-LeaderBoard -Level Beginner
Retrieves the beginner leaderboard.
.EXAMPLE
Get-LeaderBoard -Level Advanced
Retrieves the advanced leaderboard
#>
function Get-LeaderBoard
{
param(
[Parameter(
Position = 0,
Mandatory = $true,
HelpMessage = "Leaderboard to parse. Advanced, or Beginner")]
[ValidateSet("Advanced","Beginner")]
[String]$Level="Advanced"
)
# create a webclient
$WebClient = New-Object System.Net.WebClient
# download the page
$LeaderPage = $WebClient.DownloadString("http://2011sg.poshcode.org/Reports/TopUsers?filter=$Level")
# create a horrific looking regular expression
$RegEx = '<a href="/Scripts/By/\\d{1,3}">(?<UserName>[\\w\\s]*)</a>\\s*</td>\\s*<td>\\s*(?<TotalPoints>\\d{1,2}\\.\\d{1,2})\\s*</td>\\s*<td>\\s*(?<ScriptsRated>\\d*)'
# split the page into seperate objects so we can parse each invidual
$LeaderPage -split "<tr>" | ForEach {
# match the regex
$_ -match $RegEx | Out-Null
# create a new PSObject, supply a hashtable with the properties
New-Object PSObject -Property @{
"UserName" = $Matches.UserName
"ScriptsRated" = $Matches.ScriptsRated
"TotalPoints" = $Matches.TotalPoints
"AverageRating" = if ($Matches.ScriptsRated -gt 0)
{
# get average round to two decimal places
"{0:N2}" -f ($Matches.TotalPoints / $Matches.ScriptsRated)
}
}
# clear matches
if ($Matches) { $Matches.Clear() }
# get our objects in a specific order.
} | select -Unique UserName,ScriptsRated,AverageRating,TotalPoints
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.