Technically Speaking

January 30, 2008

Tee-object

Filed under: PowerShell — Chris @ 8:18 pm
Tags: ,

I haven’t written a blog lately cause I have been busy but I wanted to just point out a cool cmdlet in powershell called Tee-object . You can use this cmdlet to send output to a file and also to the screen as well . So if you want to keep track of your output and also be able to see what is going on then this is cool cmdlet to use . Hope this has been helpful . I know I have been doing a lot of powershell stuff basically cause its a very powerful shell . I will go back to doing some c# stuff soon .

 Example of tee-object :

$servername = ” MyServer” | tee-object c:\serverlist.txt

Chris

January 23, 2008

Using Powershell to restart Services

Filed under: PowerShell — Chris @ 12:06 pm
Tags: , ,

As Administrators one of the most frequent things we do is restart Services . I have created a script to do just that . So the next time it will be a piece of cake . I have done this with vbscript and regular batch files but that is no fun anymore . Plus we are living in a .net world and I’m a .net person ummm hmm :) So lets get to it .

In this example we will be restarting two services  . The SMS client service and the WMI service .

First we start off with this line of code :

[void] ([Reflection.Assembly]::LoadWithPartialName("System.ServiceProcess"))

What this does is tells powershell to go out and load the System.ServiceProcess namespace from our assembly dir in %winnt%. So we can user it in our code .Its basically like the using statement is C#

Now if you have a ton of servers you want to run this against you probably want to read them from a text file . That is what I normally do . So the next line we will be reading a text file that contains a bunch of servers and storing it in a variable .

$serverlist = Get-Content “.\serverlist.txt”

Simple huh ? Our variable $serverlist basically becomes an array . So now we can step thru the array like this :

foreach ($server in $serverlist) {

Our next step is to connect to our first server in the serverlist . We do that with the .net class ServiceController like this and create our smsservice variable which holds the connection .

$smsservice = [System.ServiceProcess.ServiceController]::GetServices("$server") | where-object ($_.Name -eq "CcmExec")

There is a lot of stuff in the above line of code . I’m using the Getservices method to get all the services and piping that into the where-object to pull the service with the Name equal to CcmExec .(Notice the Serivice Name its using . Its not its displayname .)

Once we have this we can also do the same for our WMI service:

$wmiservice = [System.ServiceProcess.ServiceController]::GetServices("$server") | where-object ($_.Name -eq "WinMgmt")

next its all gravy :)

Stop the smsservice:
$smsservice.Stop()
$smsservice.WaitForStatus("Stopped") # here we are waiting for the service ...very cool

Stop the WMI service
$wmiservice.Stop()
$wmiservice.WaitForStatus("Stopped")

Start the WMI Service:
$wmiservice.Start()
$wmiservice.WaitForStatus("Running") # Notice its not started .. but Running is what we are looking for

Start the SMS service
$smsservice.Start()

We stopped and started the 2 services in this order because of dependencies . You cannot stop the wmi service w/o stopping the sms service .

and finally at the end of the script remember the }… :)

Hope this example helps you . You can also put error trapping in place to help with error messages .

Thanks !
Chris

January 20, 2008

Playoff Sunday with PowerShell … Huh?

Filed under: PowerShell, Random — Chris @ 1:36 pm
Tags: ,

Since today is play of Sunday I wanted to make my a random generating score program . Use this to tell what is going to happen today :)

Sample output :

 NY Giants:10GB Packers:

20

SD Cahrgers:

13

NE Patriots:

19

Have Fun Today !

If you would like me to explain any line let me know . I didn’t comment like I should have but I could fix that. Also if you want to change or add anything to make it better let me know .

Chris



#####################################################
#Scriptname: Get-FootballScore.ps1
#Created Date: 1/20/2008
#####################################################


Function Get-FootballScore

{

#create new instance of random object
$intNumofScores = New-Object system.Random

#create random max number of scores from 1-7
$intMaxNumofScores = $intNumofScores.Next(1,7)



#create a random Touchdown or fieldgoal
$score = New-Object system.Random




for ($s = 1;$s -le $intMaxNumofScores;$s++)
{

$intTypeofScore=$score.Next(1,3)

switch -c ($intTypeofScore)
{
{$_ -eq 1} {$intTypeofScore = 7} #Touchdown
{$_ -eq 2} {$intTypeofScore = 3} #FieldGoal
{$_ -eq 3} {$intTypeofScore = 2} #Safety
}
$FinalScore = $FinalScore + $intTypeofScore

}
$FinalScore

}


Write-Host "NY Giants:"
Get-FootballScore
Write-Host "GB Packers:"
Get-FootballScore
""
""



Write-Host "SD Cahrgers:"
Get-FootballScore
Write-Host "NE Patriots:"
Get-FootballScore

January 18, 2008

Thank God its Friday !

Filed under: Random — Chris @ 2:44 pm
Tags: ,

Sorry I haven’t written in awhile . I am busy at work putting together a script for Server Maintenance Windows that we have . You know those times when hot fixes need to be implemented . I am writing it in vbscript . Less and Less I am liking vbscript. More and more I’m liking powershell as a scripting language . Also the scripting games are coming soon . This will be the first time I am going to enter . I want to enter the powershell games . I will write some more blogs on the script I’m making very soon .

Chris

January 15, 2008

How to Reboot a Server with Powershell

Filed under: PowerShell — Chris @ 9:26 am

This is done simply by using WMI and the operatingsystem Class. At the powershell command prompt type:

$server = gwmi Win32_operatingsystem -computer Your_Servername
$server.reboot()

Its that simple !

If your interested in knowing what other propteries and methods are available you can see them with this command .

$server | get-member

Hope this tip helps !

Chris

January 12, 2008

System.DirectoryServices.Accountmanagement

Filed under: C# — Chris @ 11:53 pm
Tags: , , ,

Like I promised to give you a guick example of this 3.5 .net namespace . I will do so now :) .

First make sure you have .net framwork 3.5 installed . Next fire up your 2005 or 2008 c# edition . Create a new project. Add a reference to System.DirectoryServices.Accountmanagement .

At this point on your form you can place a couple of controls on you form . A button , a listbox, textbox that you can enter a user or group name .

    references.jpg     controls.jpg

Make sure your controls are labled correctly (i.e txtUserName). And place this code in the click event of your button .


// Connect to Active directory with principlecontext
  PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "dcname");

This is just like doing a directory entry bind using directryentry(“LDAP:// ….. “)

So with this line your connected to your active directory .

The next bit of code is this :


//Create an instance of UserPriciple

UserPrincipal u = new UserPrincipal(ctx);

What we did here is create a new UserPrinciple instance and referenced ctx (our AD Domain )

The next code is kind of like a directorySearcher Class .


// Create an in-memory user object to use as the query example.

u = UserPrincipal.FindByIdentity(ctx, UserName);

We are taking the userprincipal variable and using the findbyIdentity method to find this usersname is AD . That is it you know have a full binding path to the User in AD . From here you can return the groups the user is a member of (Yes it will report back the primary Group as well )

Here is the complete code snippet :


// Connect to Active directory with principlecontext
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DCName");
//Create an instance of UserPriciple

UserPrincipal u = new UserPrincipal(ctx);// Create an in-memory user object to use as the query example.

u = UserPrincipal.FindByIdentity(ctx, UserName);

//Return a binding to the user
return u;

The reason why your seeing Return U is because I have this is an external Class and All I need to do is to call this and I’m connected to the user . Cool Huh ?

To get the groups a user is a member of you would do this .


PrincipalSearchResult Groups = u.GetGroups();

Use the PrincipalSearchResult to hold the results of the Groups .

There is also a GroupPrinciple Class to connect to a group the same way .

I hope this helps . A very nice Namespace !

Chris

January 11, 2008

Binding to Active Directory in C#

Filed under: C# — Chris @ 11:25 am
Tags: , ,

Geez I haven’t had a lot of time to blog in awhile .  I wanted to quickly put something down about how to connect to active directory using C# . If you do a search Google you will see a Ton of posts,blogs about the subject . As you can find out that there is an issue with returning a users groups . That being that you will not get the primary group (usually Domain users ) . This also affects Group membership too . The reason is because the ‘memberof’ attribute doesn’t contain primary group . So what you must use is Token groups . For me this is very confusing . Since the token groups attribute is not present by default you have to use the user.refreshcache() method .

I found another way to do this . By using this assembly from the 3.5 framework called System.DirectoryServices.Accountmanagement .

I will give an example this weekend but do a search in google . This solves the issue of missing users in groups and lists all groups a user is a member of .

Bye for now .

Chris

January 7, 2008

Good Blog on how to write your own cmdlet for powershell

Filed under: PowerShell — Chris @ 1:58 pm
Tags: , ,

Look hereto checkout a some good info on writing a cmdlet for powershell . Also in the blog it mentions powershell extensions from codeplex which I just installed here. This contains allot of new cmdlets . I like the get-adobject because of active directory .

Great Stuff !

January 6, 2008

Short Blog

Filed under: Random — Chris @ 7:11 pm

Well the first weekend of 08′ has passed . Can you believe it ? Today here in ST Louis it was 65 degrees . This week I’m going to post a blog on how to connect to Active directory with C# . In a previous post I showed how easy it is to do it in Power Shell . Keep in mind that these languages both use .net framework .

Since I love house music I am also going to try and post a  link to the latest music mix I create . I have been doing it for awhile now . So if you like house music then I hope you like the mix . That’s it for now .

January 3, 2008

Connecting to a Scanner with C# and other things C#

Filed under: C# — Chris @ 4:55 pm
Tags:

 I am still learning C# and wanted to write some code to connect to a scanner . I thought this should be simple . Man was I wrong . I first started searching the net on some really good tutorials to do this but couldn’t find any so I came across something on Codeproject.com which looked great but I’m really new to this stuff . Some of the stuff looked pretty self explanatory and others didn’t . I am going to try to expand on this in a different blog by showing the code . I had to use WIA (for the life of me right now I am not sure what it means Windows Integration Automation I think . ) Can anyone send me to a cool looking tutorial for newbies ?

What I basically wanted to do was write and app that took  a scanned document and put it into a SQL database . The reason was because you know how you get a lot of bills in the mail and other stuff . That stuff piles up on you after awhile . Not every company offers paperless bills lets say . So after awhile you get a ton of papers and if your like me than you probably don’t file things away as soon as you get it . I thought it would be nice to take that piece of paper and put it in the scanner hit a button to scan it in to your app . Then set some properties of the image . Then save it in a database . Which you can then sort your data and be able to print out what you want if you need it in the future .  Sounds pretty cool . I am learning allot this way about the language which is very power sitting atop .NET :) .  I think of powershell the same way and that is extremely deadly with .net tied to it .

Also in C# I am having a tough time controlling the controls on my form from a class outside . For example :

on My main form there would be the Form Class

 Namespace WindowsApplication1

Public partial Class Form 1  

{

Lets say I have a button here

private button1_click()

{

}

}

Now I have a separate class with a method . How do I control that button from this separate Class ?

My other class is this for example :

Namespace MyotherClass{

Class MyotherClass 

{

Public static void GetNames()

{

….

From inside here I want to control the controls on form 1

}

}

}

Hope someone can help . I tried creating another instance of form1 but which seemed to work but couldn’t get the result I was looking for .

Next Page »

Blog at WordPress.com.