Skip to main content

Posts

Showing posts from November, 2012

Removing duplicate objects from an set of objects

The question that I took this evening involved a user who has some functional PowerShell code.  The needed a way to filter out any duplicate objects.  They were looking at using several loops.  In my college days, that would have been the answer.  As my favorite professor, Dan Matthews, put it, “Never Reinvent the Wheel” PowerShell has built in functionality to remove duplicate items by using the Sort-Object cmdlet.  You need to use the – Property parameter to tell PowerShell which proper of the object you are looking for duplicates on and also you need to use the – Unique parameter to tell PowerShell to only leave unique objects (remove duplicates). Below is some sample code to generate a set of 11 objects.  Two of those objects will have a duplicate value in Prop1 . # Create a dynamic array to hold the test objects. $Array = @()   # Create 10 objects in the dynamic array. For ( $X = 0 ; $X -lt 10 ; $X ++ ) {     $Obj = New-Object PSObject     $Obj | Add-Membe

Executing a lot of code on multiple clients

I took a question today about how to execute a bunch of code on remote clients.  The users code worked for them on their local client, but they needed it to execute remotely.  This is a job for Invoke-Command!!! Invoke command will let you take your existing code and run it on multiple clients.  Here is a basic example. invoke-command -ScriptBlock {    #<< Your code here >>    } -ComputerName #<<Name of remote computer>>   Now for the part about executing this code against multiple clients.   $Servers = “SVR1” , “SVR2” , “SVR3” ForEach ( $Server in $Servers ) { invoke-command -ScriptBlock {    #<< Your code here >>    } -ComputerName $Servers }   In this example, we nest our invoke command  inside of a ForEach statement.  We provide a list of server names to $Servers and use this to cycle through each client.  You may want to add some error handling to this code.

Get the Name of a Server Returned with Data Using Get-Process

Here is a question that I had about using Get-Process.  The user needed the same basic information that Get-Process normally gives you, but they also needed the name of the computer that the data came from.  Their intent was to run this one command against multiple servers at the same time, but needed to separate the data by its source. When you use the Get-WMIObject cmdlet, you get a few extra properties added in.  The on of interest in this case is __SERVER .  This will hold the name of the client that the data came from.  I could have just told the user to execute Get-WMIObject Win32_Process –ComputerName <List of names> .  But that would return a lot more data.  Also, I am on a very long flight back from Microsoft so I needed something to keep me from being bored.  Below is the result. Since the user wanted to use this in a script or as a stand alone, I created a function that could be either dot sourced into memory or added as a http://mctexpert.blogspot.com/2011/04/crea

Use the difference between event log time stamps to decide if you need to take action

Today I am on a long flight back to Indianapolis after a week of training at Microsoft. Being the geek that I am I decided to take a quick look at PowerShell.org to see if anybody in the community was having issues that I could help with before we took off. One community member needed to be able to tell if two events were being recorded more than 2 hours apart. If so, she wanted an action to take place. I used the Subtract Method of the System.DateTime object that is given to you in the TimeCreated property of an individual event log to resolve this. In the below function, I have it extract the first two events that match the criteria in $EventHash. I then take the first returned event and subtract the second events time from the first and then look for the TotalHours property. If it is greater than the number of hours specified when the function was called, it returns True. If not, it returns False.  It also has a built in safety.  If 1 or less events are returned, the function de

Use PowerShell to Download HTML code from a website

Here is a little code to help you download the HTML code of a website to a file on your client. Function Download-HTML { [CmdletBinding(HelpUri = " http://get-help-jason-yoder.blogspot.com/2012/10/download-html.html " )] Param ( [Parameter(Mandatory = $True )] $Source = " www.MCTExpert.com " , [Parameter(Mandatory = $True )] $SaveFile = " C:\Users\Jason\Documents\Temp\Download1.HTML " , [ Switch ] $Quiet ) # Create an object to hold the web content. $DataObj = New-Object System.Net.WebClient Try { # Use the System.Net.WebClient method: Download to attempt to # download the data. If it dows not exists, then error out. $DataObj .DownloadFile( " Http://$source " , $SaveFile ) # Once the file is found, notify the user if $Quite is $False. If ( $Quiet -eq $False ) { Write-Host " Website text downloaded to $SaveFile " -foregro

Placing data into a CSV from multiple objects with PowerShell

I recently answered a question on PowerShell.org in which a user was sending data to a CSV file.  This data contain objects with multiple properties.  The problem with sending an object that contains objects to a CSV file with the Export-CSV is that a CSV file cannot store hieratical data.  This is what you get.  Take note of the data in the property “LogicalDisks”. #TYPE System.Management.Automation.PSCustomObject "Server_Name","MFG","LogicalDisks" "LocalHost","JASON-PC","System.Object[]"   If you need to save and object that contains an object, send it to an XML file using Export-Clixml.  Here is the same data set as an XML file.   Notice the hierarchy is preserved.  When you use Import-Clixml, you can import this data into a variable and all the objects properties are restored.   In case this is not an option, below is the code that I sent to the individual who posted the question.  This is a combination of the code

Backup event logs on multiple servers with PowerShell

This PowerShell cmdlet was developed for my PowerShell class in Miami.  This is very specific to their needs.  The requirement was to be able to backup event logs from multiple servers to a single location.  The logs needed to be saved in a folder structure of Year/Month.  They also needed an option to clear the log.  This was a fun one, but complex so I took it on. It is designed as a function so you can add it to a custom library. Function Backup-EventLog { [ CmdletBinding (HelpUri = 'http://get-help-jason-yoder.blogspot.com/2012/10/backup-eventlog.html' ) ] Param (     [ Parameter (Mandatory = $True ) ][ String []] $ComputerName ,     [ Parameter (Mandatory = $True ) ] $LogFiles ,     [ Parameter (Mandatory = $True ) ][ String ] $Path ,     [ Switch ] $ClearLog ,     [ Switch ] $Quiet )     # Support Function: Write-Info --------------------------------------------     # Provides pre-defined color formatting for text output.     Function Wri