Updates from January, 2008 Toggle Comment Threads | Keyboard Shortcuts

  • Chris 8:18 pm on January 30, 2008 Permalink | Reply
    Tags: , tee-object   


    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 12:06 pm on January 23, 2008 Permalink | Reply
    Tags: , , windows services   

    Using Powershell to restart Services 

    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 use it in our code .Its basically like the using statement in 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.WaitForStatus("Stopped") # here we are waiting for the service ...very cool

    Stop the WMI service

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

    Start the SMS service

    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 !

    • Khaja Pasha 11:04 am on November 22, 2008 Permalink

      Good help! thanks Chris..

    • Marc 5:15 am on March 31, 2011 Permalink

      your where-object syntax is incorrect:
      $wmiservice = [System.ServiceProcess.ServiceController]::GetServices(“$server”) | where-object ($_.Name -eq “WinMgmt”)

      should be:
      $wmiservice = [System.ServiceProcess.ServiceController]::GetServices(“$server”) | where-object {$_.Name -eq “WinMgmt”}

      braces define a script block, not parentheses

    • Chris 10:02 pm on March 31, 2011 Permalink

      Thanks Marc my bad . Fixed .

    • guillaume 3:09 am on August 4, 2011 Permalink

    • Kym 6:58 am on January 26, 2013 Permalink

      I have found in testing on Server 2008 R2 that if the operating system encounters difficulties stopping a service (for whatever reason) then PowerShell does not proceed past smsservice.stop(). As a consequence the next line $smsservice.waitforstatus(“stopped”) is never reached. The script will wait for eternity until it is manually terminated.

      To get around this circumstance, I have had to issue the $smsservice.stop() as a background task per:
      Start-Job -ScriptBlock { param($svc) $svc.stop() } -Arg $smsservice
      Script execution can then proceed to the next line immediately where subsequent commands can take some sort of action (eg kill the recalcitrant service process).

  • Chris 1:36 pm on January 20, 2008 Permalink | Reply
    Tags: Football,   

    Playoff Sunday with PowerShell … Huh? 

    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:


    SD Cahrgers:


    NE Patriots:


    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 .


    #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++)


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



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

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

  • Chris 2:44 pm on January 18, 2008 Permalink | Reply
    Tags: ,   

    Thank God its Friday ! 

    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 9:26 am on January 15, 2008 Permalink | Reply  

    How to Reboot a Server with Powershell 

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

    $server = gwmi Win32_operatingsystem -computer Your_Servername

    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 11:53 pm on January 12, 2008 Permalink | Reply
    Tags: , , DirectoryServices, System   


    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 !


    • Dave 1:22 pm on January 28, 2008 Permalink

      You make it sound easy but your example doesn’t work. Try it in IIS.

    • Chris Federico 10:58 am on January 29, 2008 Permalink

      Hi Dave ,

      I would be happy to help you . Please explain your comment .


    • Dave 9:25 am on January 31, 2008 Permalink

      I figured out that in IIS unless you are using basic authentication while impersonating it causes issues. If you use windows authentication you have to set the SPN and delegation. Kind of a pain. I’m new to the programming stuff and spent about a week trying to figure that out.

    • Nick 10:02 am on March 24, 2008 Permalink

      Why do you have this: UserPrincipal u = new UserPrincipal(ctx);// Create an in-memory user object to use as the query example.

      When simply this will do?
      UserPrincipal u = UserPrincipal.FindByIdentity(ctx, UserName);

    • Chris 11:00 am on March 24, 2008 Permalink

      Hi Nick ,

      I did istantiate a UserPrinciple object because I beleive I was going by an MSDN example thats why . Plus the formating didn’t work out so well as you notice I do call that line next in the code.


    • Vicky 3:32 am on March 5, 2009 Permalink


      I have a problem with connecting to an Active Directory on a different server than my application.
      For the moment I’m working on my local computer an trying to acces the AD on a test server.
      I specify PrincipalContext ctx = new PrincipalContext(ContextType.Domain, “dcname”);
      but receive an “The server could not be contacted” error.

      I think this has something to do with security, but I don’t now with which user/password he’s trying to access the AD.

      Could you help me with this?


    • Jill 12:00 pm on March 9, 2012 Permalink

      Yes vicky

  • Chris 11:25 am on January 11, 2008 Permalink | Reply
    Tags: , , Output   

    Binding to Active Directory in C# 

    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 1:58 pm on January 7, 2008 Permalink | Reply
    Tags: cmdlets, , powershell extensions   

    Good Blog on how to write your own cmdlet for powershell 

    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 !

  • Chris 7:11 pm on January 6, 2008 Permalink | Reply  

    Short Blog 

    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 .

  • Chris 4:55 pm on January 3, 2008 Permalink | Reply

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

     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 .

    • karlagius 6:09 pm on January 3, 2008 Permalink

      Hi Chris,

      What you need in the second class (MyOtherClass) is a reference to form1. When you create an instance of form1, you are creating a new instance every time.

      To keep a reference to the original form, you could pass the form as a parameter to GetNames, like so:

      public static void GetNames(Form1 form)

      do stuff


      Definitely *not* the cleanest way in the world, but should work.

      Regarding WIA, Scott Hanselman has a fantastic article at http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx

      The article describes how to connect to a camera, but a scanner that supports WIA should work the same way.


    • Chris Federico 11:01 am on January 4, 2008 Permalink

      Thanks Karl . WIA actually stands for Windows Image Acquisition . I stated it wrong in my blog . 😦

    • alin 8:05 am on July 24, 2009 Permalink

      hey man…did you had success with the scanner?
      if you did please send me the project to see how can I work with a scanner


    • Chris 12:21 am on August 2, 2009 Permalink

      Hi Alin ,

      I don’t have a working project of this yet . I kinda left it alone . I was able to connect to a scanner using the WIALIB com object I believe.

      Hope that helps.


    • alin 1:13 am on August 3, 2009 Permalink

      Hi Chris,

      10x a million.


    • Shashi 5:02 am on February 16, 2010 Permalink

      can u explain me about the coding of scanner (how to add it)

    • alin 4:10 am on February 19, 2010 Permalink

      The link from karlagius is awesome!!
      Thanks a lot!!

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc