2012/12/31

Get-LocalGroupMembership (Using ADSI/WinNT)

Updated (2013/06/03): I added some error handeling/verbose/testing. You are now able to pass multiple computers to the ComputerName parameter.

Intro

Recently I had to do an Audit at my work to find who was Local Administrators on a bunch of Servers.
That might sounds easy when you just have to check 2 or 3 servers... but what if you have to get the information for hundreds! Plus ... I know the Auditor would ask me this same question every few months to prove that the list did not change...Arghhh!

Once again PowerShell saved me so much time on that one!!

Get-LocalGroupMembership

Get the specified local group membership on a local or remote computer.
By default, if you don't specify any parameter, It will query the local group "Administrators" on the localhost.

For some reason WMI bug with some of my Windows Server 2003 and does not return some Domain Groups where Windows Server 2008/2012 work just fine.

Here is my ADSI/WinNT version, It fixed my problem.
In the next post I will go a bit further and get the membership from the domain groups ;-)

Running the Function


The Code

Function Get-LocalGroupMembership {
<#
.Synopsis
    Get the local group membership.
            
.Description
    Get the local group membership.
            
.Parameter ComputerName
    Name of the Computer to get group members. Default is "localhost".
            
.Parameter GroupName
    Name of the GroupName to get members from. Default is "Administrators".
            
.Example
    Get-LocalGroupMembership
    Description
    -----------
    Get the Administrators group membership for the localhost
            
.Example
    Get-LocalGroupMembership -ComputerName SERVER01 -GroupName "Remote Desktop Users"
    Description
    -----------
    Get the membership for the the group "Remote Desktop Users" on the computer SERVER01

.Example
    Get-LocalGroupMembership -ComputerName SERVER01,SERVER02 -GroupName "Administrators"
    Description
    -----------
    Get the membership for the the group "Administrators" on the computers SERVER01 and SERVER02

.OUTPUTS
    PSCustomObject
            
.INPUTS
    Array
            
.Link
    N/A
        
.Notes
    NAME:      Get-LocalGroupMembership
    AUTHOR:    Francois-Xavier Cat
    WEBSITE:   www.LazyWinAdmin.com
#>

 
 [Cmdletbinding()]

 PARAM (
        [alias('DnsHostName','__SERVER','Computer','IPAddress')]
  [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
  [string[]]$ComputerName = $env:COMPUTERNAME,
  
  [string]$GroupName = "Administrators"

  )
    BEGIN{
    }#BEGIN BLOCK

    PROCESS{
        foreach ($Computer in $ComputerName){
            TRY{
                $Everything_is_OK = $true

                # Testing the connection
                Write-Verbose -Message "$Computer - Testing connection..."
                Test-Connection -ComputerName $Computer -Count 1 -ErrorAction Stop |Out-Null
                     
                # Get the members for the group and computer specified
                Write-Verbose -Message "$Computer - Querying..."
             $Group = [ADSI]"WinNT://$Computer/$GroupName,group"
             $Members = @($group.psbase.Invoke("Members"))
            }#TRY
            CATCH{
                $Everything_is_OK = $false
                Write-Warning -Message "Something went wrong on $Computer"
                Write-Verbose -Message "Error on $Computer"
                }#Catch
        
            IF($Everything_is_OK){
             # Format the Output
                Write-Verbose -Message "$Computer - Formatting Data"
             $members | ForEach-Object {
              $name = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
              $class = $_.GetType().InvokeMember("Class", 'GetProperty', $null, $_, $null)
              $path = $_.GetType().InvokeMember("ADsPath", 'GetProperty', $null, $_, $null)
  
              # Find out if this is a local or domain object
              if ($path -like "*/$Computer/*"){
               $Type = "Local"
               }
              else {$Type = "Domain"
              }

              $Details = "" | Select-Object ComputerName,Account,Class,Group,Path,Type
              $Details.ComputerName = $Computer
              $Details.Account = $name
              $Details.Class = $class
                    $Details.Group = $GroupName
              $details.Path = $path
              $details.Type = $type
  
              # Show the Output
                    $Details
             }
            }#IF(Everything_is_OK)
        }#Foreach
    }#PROCESS BLOCK

    END{Write-Verbose -Message "Script Done"}#END BLOCK
}#Function Get-LocalGroupMembership


Thanks for Reading! If you have any questions, leave a comment or send me an email at fxcat@lazywinadmin.com. I invite you to follow me on Twitter: @lazywinadm

2012/12/29

Move Computers Object between two organizational units (OU) - What are the permissions required ?

Today I was playing a bit in my lab with PowerShell and AD Computer Objects.
I automate the daily cleanup of Inactive Computer Object and move them to a specific OU.
This script is running with his own service account, the privileges required are specified below.

Move Computer Object INSIDE an OU:
-Create Computer

Move Computer Object OUTSIDE an OU:
-Delete Computer
-Write All Properties

As an example, here I was using the "Delegation of Control Wizard" to allow the "Move out"





2012/12/09

FreeNas 8.3 - Creating a RAID volume and Configure iSCSI

FreeNAS is a tiny Open Source FreeBSD-based operating system which provides free Network-Attached Storage (NAS) services (CIFS, FTP, NFS, ...). It supports sharing across Windows, Apple, and UNIX-like systems.

FreeNAS 8 includes ZFS, which supports high storage capacities and integrates file systems and volume management into a single piece of software.



Overview

In the following post I will cover the following points:
  • Introduction
  • Terminology
  • Raid Volume Configuration
    • Connecting to the FreeNas HTTP Interface
    • Creating the RAID Volume
  • iSCSI Configuration
    • Adding a Portal
    • Adding an Initiator
    • Adding a Target
    • Adding a File Extent
    • Adding a Target / Extent association
    • Enabling the iSCSI Service
  • Configuring the iSCSI Initiator on VMware vSphere 5.1


Introduction

Using FreeNAS 8.3, I need to create a RAID Volume, configure iSCSI and present it to my VMware VSphere 5.1 environment.

Note: If you are not familiar with some of the iSCSI terms used below (target, initiator, extent...) please check the following webpage: http://doc.freenas.org/index.php/ISCSI


Overview of my iSCSI Lab Architecture

2012/12/07

My Home Lab !

I finally ordered my home lab to work on my technical knowledge and to help me work on some certifications. 

My first goal will be to pass my VCP5-DV in February 2013 (It is already booked!) and probably work on some other certifications like Hyper-V, SCCM, W2012...

Here is the configuration I choose

My HomeLab will run on 3 Whiteboxes:
-2 HYPERVISOR  running VMware ESXi VSphere 5.1
-1 STORAGE SERVER running FreeNas 8.3




HYPERVISORS (2 New Whiteboxes)


STORAGE
For this box I took my old HTPC and replaced some components.


More detail on HomeLab page....

2012/11/01

Create a bunch of DNS Entries using PowerShell and DNScmd.exe

Today I needed to create approx. ~50 DNS A entries.
Each of those also need to have a PTR entry.

Lazy as i am... a quick search for PowerShell DNS module did return some interesting things but none who can create both A and PTR DNS entries at the same time.

So I decided to finally use DNSCMD.exe (full syntax on technet) with powershell.

Requirement: DNSCmd.exe is part of the DNS Server Tools and need to be installed prior to use it. On Windows server you can install it using Add-WindowsFeature RSAT-ADDS-Tools


Here is a quick syntax overview of the Dnscmd.exe that we will be using.

dnscmd.exe <DNSServer> /RecordAdd <DNSZone> <NewEntryName> /CreatePTR A <IPAddress>


First Step: Create a CSV with all the information (in Excel or via PowerShell)
here is an example, save it as DNSEntries.csv (in my case at the root of the C: drive)


Second Step: The Script OneLiner:
Import-CSV -Path "c:\DNSEntries.csv" | ForEach-Object { dnscmd.exe $_.dnsserver /RecordAdd $_.zone $_.name /createPTR $_.type $_.IP }


The output should look like this

2012/09/22

PowerShell Resources - From Noob to Ninja

Videos
Windows PowerShell for Beginners
Technet ScriptCenter - Windows PowerShell: Learn It Now Before It's an Emergency

Build2011 - Windows networking with PowerShell: A foundation for data center management
TechEd 2011 - Advanced Automation Using Windows PowerShell 2.0
TechEd 2011 - Windows PowerShell Remoting: Definitely NOT Just for Servers
TechEd 2012 - Windows PowerShell Crash Course
TechEd 2012 - Advanced Automation Using Windows PowerShell 3.0
TechEd 2012 - The Dirty Dozen: Windows PowerShell Scripts for the Busy DBA
TechEd 2012 - Inside Windows Server 2012 Multi-Server Management Capabilities
TechEd 2012 - Group Policy Reporting and Analysis with Windows PowerShell
Technet Radio - The Scripting Guy’s Top 5 PowerShell 3.0 Tips and Tricks
More videos on http://channel9.msdn.com

Guides
Windows PowerShell Survival Guide (en-US) Extensive list of resources on PowerShell
Windows PowerShell 3.0 and Server Manager Quick Reference Guides
Ravikanth Chaganti - WMI Query Language via PowerShell
Don Jones - Secrets of PowerShell Remoting
Windows PowerShell Core About Topics



Code repository
PoshCode
Technet Gallery - Script Repository

Powershell sites
http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx
http://www.powershell.org
http://powershell.com/cs/
http://www.powershellmagazine.com
http://www.powershellpro.com
http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx

2012/09/19

I'm Going to PowerShellSummit !!! @pshsummit

Seattle here I come !!!
I cannot wait to meet all my fellow PowerShell enthousiasts !

The PowerShell Summit will be held at Microsoft in Redmond April 22-24, 2013. Check here for details.





PowerShell Module included in System Center Configuration Manager 2012 SP1 BETA

Source

Microsoft just released the Service Pack 1 for System Center Configuration Manager 2012.
AND!! FINALLY comes with its own PowerShell Module !!! Woot Woot :-) 

Once the SP1 installed, all you need is PowerShell 3.0.
Already included in Windows Server 2012 or can be installed on Windows Server 2008


IMPORT THE MODULE

Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"


CMDLETS

Add-CMBoundaryToGroup
Add-CMDeviceAffinityToUser
Add-CMDeviceCollectionDirectMembershipRule
Add-CMDeviceCollectionExcludeMembershipRule
Add-CMDeviceCollectionIncludeMembershipRule
Add-CMDeviceCollectionQueryMembershipRule
Add-CMDeviceCollectionToDistributionPointGroup
Add-CMDistributionPointToGroup
Add-CMSoftwareUpdateToGroup
Add-CMUserAffinityToDevice
Add-CMUserCollectionDirectMembershipRule
Add-CMUserCollectionExcludeMembershipRule
Add-CMUserCollectionIncludeMembershipRule
Add-CMUserCollectionQueryMembershipRule
Add-CMUserCollectionToDistributionPointGroup
Approve-CMApprovalRequest
Approve-CMDevice
Approve-CMUserDeviceAffinityRequest
Block-CMCertificate

2012/08/24

Introduction to CIM Cmdlets

Great article from the Powershell team blog:

Introduction to CIM Cmdlets

PowerShell 3.0 shipping with Windows server 2012 and Windows 8 brings a new set of Cmdlets to manage any server or device that complies with CIM and WS-Man standards defined by DMTF. In this blog post we will explore these new Cmdlets and how can they help IT Pros in managing a datacenter.
The list of new Cmdlets is given in the table below:
Cmdlet Purpose
Get-CimInstance Gets instances of a class.
New-CimInstance Creates a new instance of a class.
Remove-CimInstance Removes one of more instances of a class.
Set-CimInstance Modifies one or more instances of a class.
Get-CimAssociatedInstance Gets all the associated instances for a particular instance.
Invoke-CimMethod Invokes instance or static method of a class.
Get-CimClass Gets class schema of a CIM class.
Register-CimIndicationEvent Helps subscribe to events.
New-CimSession Creates a CIM Session with local or a remote machine
Get-CimSession Gets a list of CIM Sessions that have been made.
Remove-CimSession Removes CimSessions that are there on a machine.
New-CimSessionOption Creates a set of options that can be used while creating a CIM session.

Basic terminology

If you are already familiar with terms like WMI, CIM, WinRM and WS-Man, you can skip this section.
CIM: Common Information Model (CIM) is the DMTF standard [DSP0004] for describing the structure and behavior of managed resources such as storage, network, or software components.
WMI: Windows Management Instrumentation (WMI) is a CIM server that implements the CIM standard on Windows.
WS-Man: WS-Management (WS-Man) protocol is a SOAP-based, firewall-friendly protocol for management clients to communicate with CIM servers.
WinRM: Windows Remote Management (WinRM) is the Microsoft implementation of the WS-Man protocol on Windows.

Introduction to CIM Cmdlets

2012/06/14

LazyWinAdmin v0.4 released

UPDATE 2016/04/26: Lazywinadmin is now open source, see here: https://github.com/lazywinadmin/LazyWinAdmin_GUI

LazyWinAdmin is a PowerShell Script that generates a GUI/WinForms loaded with a tons of tools

The Form was created using Sapien Powershell Studio 2012.


2012/06/01

LazyWinAdmin v0.4 - Sneak Peek

Sneak peek : LazyWinAdmin v0.4

LazyWinAdmin is a PowerShell Script
This script generate a GUI/WinForm that was created using Sapien Powershell Studio.

I've been working in LWA for a while now.
This project of mine is mostly to help myself in my day to day Windows System Administrator tasks.

The goal of this tool is to centralize a lot of commands I use everyday inside a GUI and waist less time doing some tasks...
It also taking advantage of a couple of other tools Built-in in Windows: Computer Manager, Services.msc,...
And some non-built-in: Psexec, ADExplorer, SYDI-Server.vbs etc...


"General" tab contain my Top Used tools.


The "Check" button allow you to check the following connectivity item:
Ping (test-connection), Permission (test-path \\Computer\c$), RDP (Test of the port 3389), PsRemoting (PowerShell Remoting Enabled), OS (WMI), Uptime (WMI)





Autocomplete of the ComputerName. 
The script run a Get-Content on a Computers.txt when the form is loading.

2012/05/11

Group Policy Health PowerShell Cmdlet Updated

SDM Software just updated their Group Policy Health Powershell Cmdlet to version 1.2

Once Download and Install, all you need to do is:

Import-Module SDM-GPHealth


Here is the only cmdlet available for this module Get-SDMGPHealth, this is the full help.

NAME
    Get-SDMGPHealth
    
SYNOPSIS
    Retrieves Group Policy Processing Health on local or remote Windows systems.
    
SYNTAX
    Get-SDMGPHealth [-ComputerName]  [-Credentials ] [-OutputbyXml] [-NoComputer] [-NoUser] [-NoG
    PO] [-NoCSE] []
    
    Get-SDMGPHealth [-OU]  [-Credentials ] [-OutputbyXml] [-NoComputer] [-NoUser] [-NoGPO] [-NoCS
    E] []
    
    Get-SDMGPHealth [-DomainName]  [-Credentials ] [-OutputbyXml] [-NoComputer] [-NoUser] [-NoGPO
    ] [-NoCSE] []
    
    
DESCRIPTION
    This cmdlet leverages in-depth knowledge of Group Policy processing to return overall health as well as detailed in
    formation on three main areas of Group Policy processing. The first is general information, which provides informat
    ion such as host OS version, whether loopback was detected, fast logon optimization, etc. The second area is a list
     of GPOs currently processed by computer and user. The third is a list of CSEs run by computer and user, and what G
    POs ran for each CSE. An OverallStatus property is also returned which provides a quick "red or green" status of GP
     processing on the target system, based on whether either Core or CSE processing failed for the client
    

PARAMETERS
    -ComputerName 
        This parameter is used for targeting a single system and expects the hostname of the machine in question.
        
        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false
        
    -Credentials 
        This parameter is expecting a PSCredential object containing a username and password that will be used when mak
        ing a connection to the target(s). You can create such an object by call get-credential and assigning it to a v
        ariable, then passing that variable into this parameter. Note that this cmdlet requires the ability to remotely
         query a system via WMI. As such, any credentials passed must have this ability.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       true (ByValue)
        Accept wildcard characters?  false
        
    -OutputbyXml
        If this optional parameter is used, the results of the GPHealth call will be logged to an XMLDocument object. T
        his object contains the more detail than the default output format, and should be used to if more detail is req
        uired or you need a structured data model to import into a database.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -NoComputer
        Use this optional parameter if you want to exclude per-computer status from the health report.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -NoUser
        Use this optional parameter if you want to exclude per-user status from the health report.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -NoGPO
        Use this optional parameter if you want to exclude GPO status from the health report. No GPO details will be pr
        ovided in this case.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -NoCSE
        Use this optional parameter if you want to exclude CSE status from the health report. No CSE details will be pr
        ovided in this case.
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -OU 
        This parameter would be used in place of -ComputerName. If you specify this parameter and supply the DN of an O
        U in AD domain, then that OU is searched for all computer objects and those computer objects are used as target
        s for the health cmdlet. The cmdlet runs against each computer in turn and outputs the results to the console. 
        For example, -OU "OU=Marketing,DC=cpandl,DC=com"
        
        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false
        
    -DomainName 
        This parameter would be used in place of -ComputerName or -OU. If you specify this parameter and supply the DN 
        of an AD domain, then that entired domain is searched for all computer objects and those computer objects are u
        sed as targets for the health cmdlet. The cmdlet runs against each computer in turn and outputs the results to 
        the console. For example, -DomainName "DC=cpandl,DC=com"
        
        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false
        
    
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        "get-help about_commonparameters".
    
INPUTS
    System.String
     
    
OUTPUTS
    Sdmsoftware.SDMGPHealthResult, System.XML
     
    
NOTES
    
    
        
    
    --------------  Example 1 --------------
    
    C:\PS>get-SDMGPHealth -ComputerName xp3
    
    
    Returns GP Health information for a host named XP3
    
    
    OverallStatus            : red
    TimeLogged               : 6/18/2008 1:34:09 AM
    HostName                 : xp3
    Domain                   : cpandl.com
    OSVersion                : Microsoft Windows XP Professional, Service Pack 2
    ComputerCoreStatus       : The operation completed successfully
    UserCoreStatus           : The operation completed successfully
    FastLogonEnabled         : False
    ComputerSlowLinkDetected : False
    Loopback                 : None
    DCUsed                   : \\sdm2.cpandl.com
    ComputerElapsedTime      : 00:00:04
    CurrentLoggedOnUser      : CPANDL\test
    UserSlowLinkDetected     : False
    UserElapsedTime          : 00:00:01
    ComputerGPOsProcessed    : {Local Group Policy, Default Domain Policy, Scripts TEst, Windows Update Test...}
    UserGPOsProcessed        : {Local Group Policy, Default Domain Policy, Scripts TEst, Windows Update Test...}
    ComputerCSEsProcessed    : {Registry, Scripts, Internet Explorer Zonemapping, Security...}
    UserCSEsProcessed        : {Folder Redirection, Registry, Scripts, Internet Explorer Zonemapping...}
    
    
    --------------  Example 2 --------------
    
    C:\PS>get-SDMGPHealth -ComputerName XP3 -NoCSE
    
    
    Returns GP Health information for a host named XP3 without Client Side Extension (CSE) information
    
    
    OverallStatus            : green
    TimeLogged               : 6/18/2008 1:36:58 AM
    HostName                 : xp3
    Domain                   : cpandl.com
    OSVersion                : Microsoft Windows XP Professional, Service Pack 2
    ComputerCoreStatus       : The operation completed successfully
    UserCoreStatus           : The operation completed successfully
    FastLogonEnabled         : False
    ComputerSlowLinkDetected : False
    Loopback                 : None
    DCUsed                   : \\sdm2.cpandl.com
    ComputerElapsedTime      : 00:00:04
    CurrentLoggedOnUser      : CPANDL\test
    UserSlowLinkDetected     : False
    UserElapsedTime          : 00:00:01
    ComputerGPOsProcessed    : {Local Group Policy, Default Domain Policy, Scripts TEst, Windows Update Test...}
    UserGPOsProcessed        : {Local Group Policy, Default Domain Policy, Scripts TEst, Windows Update Test...}
    ComputerCSEsProcessed    :
    UserCSEsProcessed        :
    
    
    --------------  Example 3 --------------
    
    C:\PS>(Import-Csv hosts.csv | Get-SDMGPHealth | ft HostName, OverallStatus) 2>errors.txt
    
    
    This example leverages the import-csv cmdlet to pass a list of hostnames to the GP Health cmdlet. Then, the output 
    is piped into a format-table cmdlet that only returns the hostname and overall status. If any hosts return an error
    , the error is redirected to a file called errors.txt
    
    
    HostName                                                    OverallStatus
    --------                                                    -------------
    xp3                                                         red
    sdm1                                                        red
    sdm2                                                        green
    xp2                                                         green
    member100                                                   green
    
    
    --------------  Example 4 --------------
    
    C:\PS>$creds= Get-Credential ; Get-SDMGPHealth -ComputerName child1 -Credentials $creds
    
    
    These two commands first assign the call to get-Credential to a variable called $creds, and then then use that to p
    ass alternate credentials to the Health cmdlet using the -Credentials parameter
    
    
    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    Credential
    
    
    OverallStatus            : green
    TimeLogged               : 6/18/2008 2:12:50 AM
    HostName                 : child1
    Domain                   : west.cpandl.com
    OSVersion                : Microsoft(R) Windows(R) Server 2003, Standard Edition, Service Pack 1
    ComputerCoreStatus       : The operation completed successfully
    UserCoreStatus           : The operation completed successfully
    FastLogonEnabled         : False
    ComputerSlowLinkDetected : False
    Loopback                 : None
    DCUsed                   : \\child1.west.cpandl.com
    ComputerElapsedTime      : 00:00:00
    CurrentLoggedOnUser      :
    UserSlowLinkDetected     : False
    UserElapsedTime          : 00:00:00
    ComputerGPOsProcessed    : {Local Group Policy, Default Domain Policy, Default Domain Controllers Policy}
    UserGPOsProcessed        : {}
    ComputerCSEsProcessed    : {Registry, Security, EFS recovery}
    UserCSEsProcessed        : {}
    
    
    --------------  Example 5 --------------
    
    C:\PS>(Get-SDMGPHealth -ComputerName xp3 -OutputbyXml).Save(".\output.xml")
    
    
    This example leverages the OutputbyXML parameter to dump the contents of the Health cmdlet to an XML file called ou
    tput.xml. It uses the fact that the output type of the call to this cmdlet with this parameter is an XMLDocument ob
    ject, which contains the Save() method to save the contents to an XML file.
    

RELATED LINKS
    http://www.sdmsoftware.com/group_policy_scripting 




2012/05/02

Video: Powershell V3 Guru Don Jones

Source : http://channel9.msdn.com/posts/PowerShell-V3-Guru-Don-Jones

Rick Claus interviews PowerShell guru Don Jones while at MMS 2012.  They chat about Powershell V3. cool things that are under represented and how everything is underpinned by PowerShell in Windows Server 2012.

2012/04/20

Video: Tobial Weltner – Regular Expressions in 5 Minutes

Video: Tobial Weltner – Regular Expressions in 5 Minutes:
One of my favorite lightning talks at the PowerShell Deep Dive in Frankfurt was the one that Tobias did on regular expressions.
Lightning Talks are super quick sessions at the conference in which anyone gets a chance to show something cool in 5 minutes. We tried doing these in Frankfurt and they had just amazing level of energy and got everyone really excited. I think we will do them again in San Diego in May.
Anyway, here’s the recording of the Regular Expressions talk by Tobias which I made in Frankfurt. Enjoy!

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!

Video: Brandon Shell – Module Design for IT Pro

Video: Brandon Shell – Module Design for IT Pro:
Here’s another great recording from previous PowerShell Deep Dive – Brandon‘s session on module design. Brandon has experience designing PowerShell modules for Splunk and other companies – so there’s a lot to learn from him!
In this session we will deep dive into the thought process behind production module design. The presenter will explain the reason for choices made for the Splunk Module and his own BSonPosh module.

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!

2012/04/13

Video: Aleksandar Nikolic – Delegation with Remoting

Video: Aleksandar Nikolic – Delegation with Remoting:
Here’s recording of @alexandair – PowerShell MVP, constrained runspaces guru and editor of PowerShell Magazine – talking about delegation in PowerShell remoting. I bet not that many of you tried this feature before – so check out this talk that Aleksandar did at the last PowerShell Deep Dive in Frankfurt!
In this session you will learn how to set up a fan-in PowerShell endpoint, and then use it to assign specific administrative tasks to the appropriate users and groups without changing the membership of local Administrators group. By using just the IIS configuration files and PowerShell scripts we will enable dynamic creation of customized automation environments.

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!

2012/04/06

Video: Jeffery Hicks - Turn Command-Line Tools into PowerShell Tools

Video: Jeffery Hicks – Turn Command-Line Tools into PowerShell Tools:
Here’s recording of @jeffhicks – PowerShell MVP, book author and trainer – Jeffery Hicks – talking at the previous PowerShell Deep Dive about how you can turn existing command-line utilities into PowerShell functions so they can become first-class (object emitting ;) ) PowerShell citizens.
You can find Jeff’s slides and demo scripts here.
The abstract and video recording are below:



PowerShell is everywhere but there are still many command line tools in the IT Pro’s toolbox, In this session we’ll look at how to turn just about any command line based tool into a PowerShell tool so that you can incorporate it into your PowerShell scripts and daily management tasks. The power of objects in the pipeline is amazing and there’s no reason not to include tools like NETSTAT.EXE or NBTSTAT.EXE. 

1. The Challenge of CLI Tools 

2. Console Text to PowerShell Objects Techniques 

3. Putting It All Together





This is a live recording from European TEC 2011 PowerShell Deep Dive conference. See more PowerShell Deep Dive recordings here.

2012/04/04

Using PowerShell as a Starting Point for Comparing GPOs

source






Video Transcript

Comparing two Group Policy Objects can be pretty tricky with the native tools. Here in the Group Policy Management console or GPMC I have created two different GPO’s, test 1 and test 2. Now if we open one up each of these only setting a couple of settings. You will find it under Computer Configuration/Polices/Windows Settings/Security Settings/Event Log. What I have done is set the Retain security log in this one to 75 days and the other test GPO to 7 days. Then both of them set the retention method for security log to By days.
Right here in the GPMC there is nothing I can really do to compare these two things. What I have done is hop on Google, I punched in compare GPO and I found this script that was written by Ed Wilson, the scripting guy at Microsoft. He has helpfully posted this in the repository and what I have done is take the scripts default parameters to reflect my environment. I provided the domain name, the name of the controller, my two GPO’s, and then the folder where I want the comparison information to be written.
You do not have to set that information, it is possible to provide all of those perimeters when you run the script. For example, we will hop down here. There is the name of the script. Now because I have set all of those perimeters to what I want them to be by default I do not need to specify the GPO names, or the domain name, or the server names, or any of that. But I do need to specify either -computer or            -user, based on which side of the GPO, the computer settings or the user settings, I want to compare.
Running this, it is actually outputting both GPO’s test 2 and test 1 to an xml file and it is indicating that both of these GPO’s change the same settings. I see AuditLogRetentionPeriod and RetentionDays. Unfortunately because of the way this output is created I cannot really tell that it is the security audit log that was changed. I see both of them changed that setting, but I do not actually see what they changed it to just with that default output.
This is why some people will start looking at third party tools. If you hop into Google or your favorite search engine and type compare GPO tool, you will find plenty of different results. The key and one of the things I discuss in the article, Native Methods for Comparing Group Policy Objects, that accompanies this video is in deciding exactly what you are going to do with that comparison, because different tools provide you with that information in different ways. For example, if you just need a quick check of what settings two GPO’s do, well then this little script can do that for you. If you need to dive deeper and maybe get a color coded change management report that shows what values are different from GPO to GPO well, then you are going to have to either do more work with something like PowerShell or find some tools that implement that for you.

Video Awesomeness - VMware has released 3 hours of free online training

Video Awesomeness - VMware has released 3 hours of free online training:


You definitely have to check out this YouTube video channel I’ve compiled from recent video uploads of VMwareTV. VMware has released 3 hours of online VMware vSphere training material featuring Chris Skinner and Brian Watrous.

2012/04/02

Video: Bartosz Bielawski – Tracing in PowerShell

Video: Bartosz Bielawski – Tracing in PowerShell:
Here’s a recording of the session that @bielawbBartek Bielawski did at the previous PowerShell Deep Dive on PowerShell tracing. He explains why you would want to trace PowerShell, how to find trace sources, and how to enabling tracing for particular trace sources.
Enjoy:

See more PowerShell Deep Dive recordings here.
This is a live recording from European TEC 2011 PowerShell Deep Dive conference.

Video: Dmitry Sotnikov – PowerShell Jobs in v2 and v3

Video: Dmitry Sotnikov – PowerShell Jobs in v2 and v3:
Another day – another recording from PowerShell Deep Dive. For a change, this one is from a session delivered by yours truly. :) And it is on PowerShell jobs (also known as background jobs) and the functionality that they had in PowerShell 2.0 and are getting in PowerShell 3.0.
PowerShell jobs allow you to run your commands and scripts in the background without blocking your PowerShell. You can run multiple jobs, check their status, and collect results. We will also get a sneak peek of the new Jobs functionality coming in Windows 8! 

This is a live recording from European TEC 2011 PowerShell Deep Dive conference. See more PowerShell Deep Dive recordings here.

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