2012/04/02

Leveraging Proxy Functions in PowerShell

@DSotnikov just released the video recording of the session from the PowerShell Deep Dive in Frankfurt (last year). In this video, MVP Kirk Munro (poshoholic) and I demoed a project we've been working on that let's you create proxy functions. Here's a reminder of the session abstract.

In this session as they take a deep dive into proxy functions in PowerShell. Shay and Kirk have been working together on PowerShell Proxy Extensions, a powerful module that leverages proxy functions and makes it easier than ever to create these powerful extensions to PowerShell. They will demonstrate what proxy functions are and why they are important, and then show how a little scripting savvy (and a really long script) can make your life easier by allowing you to create everything from very simple proxy functions that extend PowerShell to more complex proxy functions that override existing commands, fixing bugs and adding missing features at the same time, all while leveraging inline help as much as possible.

The module we demoed is available at http://pspx.codeplex.com/. Unfortunately I won't be able to make it this year to the Deep Dive in San Diego, but if you're attending you'll get the chance to see the module in action, plus a very cool project, written on top of the PowerShell Proxy Extensions (PSPX) module.

Video: Richard Siddaway – PowerShell Events

Video: Richard Siddaway – PowerShell Events:
See @rsiddaway / Richard Siddaway (PowerShell MVP and the founder of UK PowerShell usergroup) giving a great overview of PowerShell eventing in this recording from last year’s PowerShell Deep Dive.
Windows is an event driven system. PowerShell is the automation engine for the Microsoft platform. Version 2.0 introduced the ability to work with system events. Many system events do not require action on our part. There are some events that we really need to be aware of and act upon. Gaining access to these events has not been an easy task for the administrator — up until now. 


PowerShell can work with events generated by: 

WMI 

.NET 

• The PowerShell engine 


Between them they give a handle into the inner workings of your system. A customizable, generic approach to handling events will be presented that enables you to perform actions based on the events detected. Events don’t just provide an insight into what’s happening. We can use them to trigger system actions for us — a self-healing system anyone 


The key take aways from this session will be: 

• The PowerShell event engine enables you to interact at a closer level with your system 

• The consumption and processing of events can be as simple or complicated as you require 

• You can use events to teach your system to react a fix things on its own 

This is a live recording from European TEC 2011 PowerShell Deep Dive conference. See more PowerShell Deep Dive recordings here.
By the way, TEC US is just around the corner – April 29 – May 2, 2012 in San DiegoThe agenda has already been published and is absolutely fantastic. :)
Register now - this is the best PowerShell event you can find!



Source:
Code powershell

2012/03/23

Video: James O’Neill and his PowerShell profile

Video: James O’Neill and his PowerShell profile:
Here’s another cool tips and tricks recording from last PowerShell Deep Dive – James O’Neill is sharing the cool functions that he has in his PowerShell profile:

See more PowerShell Deep Dive recordings here.
This is a live recording from European TEC 2011 PowerShell Deep Dive conference. TEC US is just around the corner – April 29 – May 2, 2012 in San DiegoRegister now - this is the best PowerShell event you can find!

2012/03/15

Powershell 3.0 - Workflows (video by Bruce Payette)

This is a live recording from European TEC 2011 PowerShell Deep Dive conference.
Bruce Payette gives a tour of PowerShell Workflows.

 


What is Workflow

















Powershell Worflow Architecture

Powershell Workflow Editor



2012/03/14

Powershell - My Script Template

Here is my powershell script template.
Hope that's help someone out there.


# #############################################################################
# COMPANY INC - SCRIPT - POWERSHELL
# NAME: script.ps1
# 
# AUTHOR:  Francois-Xavier Cat, Company Inc
# DATE:  2012/03/14
# EMAIL: info@lazywinadmin.com
# 
# COMMENT:  This script will....
#
# VERSION HISTORY
# 1.0 2011.05.25 Initial Version.
# 1.1 2011.06.14 Upgrade with...
#
# TO ADD
# -Add a Function to ...
# -Fix the...
# #############################################################################


#--- CONFIG ---#
#region Configuration
 # Script Path/Directories
  $ScriptPath   = (Split-Path ((Get-Variable MyInvocation).Value).MyCommand.Path)
  $ScriptPluginPath  = $ScriptPath + "\plugin\"
  $ScriptToolsPath  = $ScriptPath + "\tools\"
  $ScriptOutputPath  = $ScriptPath + "\Output\"
 # Date Format
  $DateFormat   = Get-Date -Format "yyyyMMdd_HHmmss"

#end region configuration

#--- MODULE/SNAPIN/DOT SOURCING/REQUIREMENTS ---#
#region Module/Snapin/Dot Sourcing
 # DOT SOURCING Examples
  #. $ScriptPath\FUNCTION1.ps1
  #. $ScriptPath\FUNCTION2.ps1
  #. $ScriptPath\FUNCTION3.ps1
 # SNAPIN or MODULE Examples
  #if (-not(Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction Silentlycontinue)){Add-PSSnapin Quest.ActiveRoles.ADManagement}
  #if (-not(Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction Silentlycontinue)){Add-PSSnapin Quest.ActiveRoles.ADManagement}
  #if (-not(Get-Module -Name BSonPosh -ErrorAction Silentlycontinue)){Import-Module BSonPosh}
 # REQUIREMENTS
  # see the help: "get-help about_requires -full"
  # The Requires statement prevents a script from running unless the Windows
  # PowerShell version, snap-in, and snap-in version prerequisites are met. If
  # the prerequisites are not met, Windows PowerShell does not run the script.
  
#end region Module/Snapin/Dot Sourcing

#--- HELP ---#
#region help

<#
.SYNOPSIS
Cmdlet help is awesome.
.DESCRIPTION
This Script does a ton of beautiful things!
.PARAMETER
.PARAMETER
.INPUTS
.OUTPUTS
.EXAMPLE
.EXAMPLE
.LINK
http://www.lazywinadmin.com
#>
#end region help

#--- FUNCTIONS ---#
#region functions

#end region functions

#--- SCRIPT ---#
#region script

#end region script

Powershell - Monitor Active Directory Groups membership change

UPDATE: The most recent update is available on Github


See also those related BlogPosts:




A couple of weeks back, my boss asked me to set a quick monitoring tool to check membership change made on Active Directory groups.
In my case here i'm talking about "Domain Admins" and "Enterprise Admins"

Unfortunately we currently don't have a tool in place to do this.

So why not taking advantage of Powershell ? :-)

Required
-A Script to monitor a list of Groups
-Create a Scheduled Task to run every minutes
(if you set the Scheduled task on a Windows Server 2008R2 or a Windows 7, you might want to take a look at my previous post: Run this task every minute !!!)

Description
This script will first check the members and export the result to a CSV file (if it does not exist yet) If a file already exist, it content will be compared with the result of $Members If different an email is sent to $EmailTo email with the member who has been added or removed.

Script
http://gallery.technet.microsoft.com/Monitor-Active-Directory-4c4e04c7

#requires -version 2.0 

# ############################################################################# 
# NAME: TOOL-Monitor-AD_DomainAdmins_EnterpriseAdmins.ps1 
#  
# AUTHOR:  Francois-Xavier CAT 
# DATE:  2012/02/01 
# EMAIL: info@lazywinadmin.com 
#  
# COMMENT:  This script is monitoring group(s) in Active Directory and send an email when  
#     someone is added or removed 
# 
# REQUIRES:  
#  -Quest AD Snapin 
#  -A Scheduled Task 
# 
# VERSION HISTORY 
# 1.0 2012.02.01 Initial Version. 
# 1.1 2012.03.13 CHANGE to monitor both Domain Admins and Enterprise Admins
# 1.2 2013.09.23 FIX issue when specifying group with domain 'DOMAIN\Group'
#                CHANGE Script Format (BEGIN, PROCESS, END)
#                ADD Minimal Error handling. (TRY CATCH)
# 
# ############################################################################# 
  

BEGIN {
    TRY{
        # Monitor the following groups 
        $Groups =  "Domain Admins","Enterprise Admins"

        # The report is saved locally 
        $ScriptPath = (Split-Path ((Get-Variable MyInvocation).Value).MyCommand.Path) 
        $DateFormat = Get-Date -Format "yyyyMMdd_HHmmss" 

        # Email information
        $Emailfrom   = "sender@company.local" 
        $Emailto   = "receive@company.local" 
        $EmailServer  = "emailserver.company.local" 
  
        # Quest Active Directory Snapin 
         if (!(Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction Silentlycontinue)) 
          {Add-PSSnapin Quest.ActiveRoles.ADManagement}
        }
    CATCH{Write-Warning "BEGIN BLOCK - Something went wrong"}
}

PROCESS{

    TRY{
        FOREACH ($item in $Groups){

            # Let's get the Current Membership
            $GroupName = Get-Qadgroup $item
            $Members = Get-QADGroupMember $item -Indirect | Select-Object Name, SamAccountName, DN 
            $EmailSubject = "PS MONITORING - $GroupName Membership Change" 
   
            # Store the group membership in this file 
            $StateFile = "$($GroupName.domain.name)_$($GroupName.name)-membership.csv" 
   
            # If the file doesn't exist, create one
            If (!(Test-Path $StateFile)){  
                $Members | Export-csv $StateFile -NoTypeInformation 
                }
   
            # Now get current membership and start comparing it to the last lot we recorded 
            # catching changes to membership (additions / removals) 
            $Changes =  Compare-Object $Members $(Import-Csv $StateFile) -Property Name, SamAccountName, DN | 
                Select-Object Name, SamAccountName, DN,
                    @{n='State';e={
                        If ($_.SideIndicator -eq "=>"){
                            "Removed" } Else { "Added" }
                        }
                    }
  
            # If we have some changes, mail them to $Email 
            If ($Changes) {  
                $body = $($Changes | Format-List | Out-String) 
                $smtp = new-object Net.Mail.SmtpClient($EmailServer) 
                $smtp.Send($emailFrom, $emailTo, $EmailSubject, $body) 
                } 
            #Save current state to the csv 
            $Members | Export-csv $StateFile -NoTypeInformation -Encoding Unicode
        }
    }
    CATCH{Write-Warning "PROCESS BLOCK - Something went wrong"}

}#PROCESS
END{"Script Completed"}



#end region script

2012/03/13

Run this Scheduled Task every minute !!!


Description
This is a weird one... This post will show you how to configure a Scheduled task every single minute.

By default on Microsoft Windows Server 2008 R2, You have the options to run a task every: "5 minutes", "10 minutes", "15 minutes", "30 minutes","1 hour".




How to Schedule a task to run every minute ?
Today I was configuring a new Scheduled task on Windows Server 2008 R2. In my case i wanted the task to run every minute...

Using the CLI
I know this is easily possible using the tool Schtasks.exe
The command would look like something like that

schtasks /create /sc minute /mo 1 /tn "Hello World" /tr \\Server\scripts\helloworld.vbs

See Technet: Schtasks.exe for more details.

Using the GUI
I realize that i couldn't set the task to repeat under 5 minutes ;-(

So here is the trick:

  • Edit the Trigger of your task. And as you can see ... nothing below 5 minutes :-(





  • I realized the Repeat Task Every's Textbox could be edited... All you need to do is to set the value to "1 minute" manually, (manually type "1 minutes") and press OK. VOILA! :-)


Verifying your Trigger settings

Here you can see the task repeat every minute.



Hope that's help someone out there.

2012/02/20

New version : LazyWinAdmin 0.3.20120220

LazyWinAdmin was created using ONLY Powershell scripting language
I used SAPIEN PrimalForms to create the GUI.


This tool requires Powershell 2.0 and permissions on local or remote computers to be able to manage those.
 LazyWinAdmin 0.3.20120220

Download








-FIX some problem with Uptime Button
-FIX Modified The Service Query/start/stop

-ADD Restart Service Button
-ADD TextBox with AutoCompletion on some Services i added
-ERROR AutoCompletion in the TEXTBOX of Services seems to make the thing crash :-(
-REMOVE AutoCompletion in Service Tab, in ServiceName TextBox
-ADD Get Local Hosts File (Menu: LocalHost/Hosts File)
-ADD Get Remote Hosts File (in General Tab,need permission on remote c$)
-REMOVE Computers.txt auto-completion, seems buggy :-(
-FIX ENTER-PSSESSION button
-REPLACED some function by button with icons below ComputerName textbox
-MOVED the TEST-PSSESSION button to TOOL tab
-ADD the TEST-PSSESSION inside the ENTER-PSSESSION button. (2 in 1 :)
-MODIFY Inventory button and output (add more info)
-MODIFY IpConfig to use the one from BSonPosh module
-ADD button IPCONFIG, DISK USAGE
 -ADD START COMMANDS in General Tab
-ADD SYDI option (dropdown) to choose DOC or XML format.
-ADD Combobox in TOOLS Tab, and ADD the present tools in combobox
-REMOVE Buttons in TOOLS tab (the ones placed in Combobox)
-FIX the ContextMenuStrip on TextBox SERVERNAME.
-ADD option of type for SYDI (DOC or XML)
-FIX the names of all the variables (for Winforms controls only)
-ADD Qwinsta and Rwinsta to contextmenu of computername textbox
-FIX SYDI (DOC and XML now work) auto-save on Desktop of Current User and Open the folder
-FIX "Installed Applications" show the full names of each application,vendors and versions.
-ADD Connectivity Testing Button (Remote registry, ping, RPC, RDP, WsMan)
-ADD more info to ipconfig button