Steve Schofield's Blog

Browse by Tags

All Tags » powershell   (RSS)

  • Powershell Script, WMI to get DNS settings.

    A while ago I wrote my disappointment about Powershell and trying to pick up the syntax. I've scripted for years with WSH / VBS, ASP, ASP.NET, VB.NET and some C#. I was used to Visual Studio and the rich debugging support. Coming from a web developer...(read more)
  • Send email with powershell cmd-let

    I've been reading the Powershell newsgroup, which is pretty much the authoritative source for community help. http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?dg=microsoft.public.windows.powershell For those who want to send email...(read more)
  • Misc Powershell links

    For my own reference. Freenode IRC network: irc.freenode.net Web client at powershelllive.com/irc Newsgroup name microsoft.public.windows.powershell www.PowerScripting.net www.PowerShellCommunity.org...(read more)
  • Send email with Powershell script, schedule script with Windows Task Scheduler

    Here is a set of samples I used to do a common task in my scripting life. This go around I wanted to use Powershell. A) Create a script to send emails in powershell ---------------------------------------------------- 1) Open Powershell type set-executionpolicy...(read more)
  • Free Powershell book and other Powershell info

    I attended TechED USA this year.  One of the key technologies that has a lot of buzz in the ITPro space is about Powershell.  I attended a few sessions on Powershell and the Exchange Management Shell (Powershell for managing Exchange 2007).   I found a free Powershell book online.

    http://blogs.technet.com/mfugatt/archive/2007/06/11/free-windows-powershell-book.aspx

    Other Powershell information.


    Quest Software has free AD powershell stuff

    AD templates for controlling the powershell execution policy.
    www.microsoft.com/downloads/
    Search for Powershell
     
    My favorite Powershell community site
  • IIS7 post #32 - Web Application Stress Tool on Vista

    I was messing around with Powershell and IIS7 trying to list the executing requests.  Since my local environment isn't very busy, I loaded Web Application Stress Tool.   This tool has no problem generating enough requests.  You'll need to load one DLL called msvcp50.DLL not include with Vista.   The installer looks for this DLL.

    I created a Default.asp page that writes the Date / time and hit this with WAST.

    <% response.write Now() %> 

    Here is the Powershell script

    [System.Reflection.Assembly]::LoadFrom( "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" )
    $sm = new-object Microsoft.Web.Administration.ServerManager
    $sm.workerprocesses | foreach-object {$_.GetRequests(0)}

    Here is the WAST Settings

    Here is the output from the powershell script

  • Filter Event logs with Powershell

    This command helps filter SYSTEM event log entries.

    get-eventlog system | where {$_.Message -match "Office" -and $_.Source -match "UmrdpService"} | format-table -wrap -autosize -property Message

  • Intellisense / get-member in Powershell

    One of the neat tricks is write out what Methods, Properties get-member cmdlet.  Here are a couple of replies I recently from my question in the Powershell newsgroup.  

    Example 1
    -------------
    It works well for static methods (note the parenthesis and square brackets
    around the class name):

    PS> get-member -in ([system.math]) -static


    Example 2
    -------------
    You don't need to assign to a variable. You can pipe the new object into the get-member call:

    new-object text.stringBuilder | get-member -memberType methods

    If you don't want to create an instance at all, you can use reflection:

    [text.stringBuilder].getMethods() | % { $_.name } | sort -unique

  • RMT version of Powershell available for Vista

  • Basic Powershell examples, couple useful commands

    I've been bitten by the Powershell bug.  My scripting background tells me I should really learn this tool.  Since I've been writing console applications for a few years, mostly to do WMI and related Web service calls.  This should be fairly easy in Powershell.  As with anything, learning the syntax and how things are done is a bit frustrating at first.  There are tons of examples available, however if you are like me, you need to figure it out the hard way. Once you get the swing of it, things should be pretty straight forward.

    After figuring out a couple of examples, which are posted below, I'm starting to get the swing of it.  There is a lot though I don't understand but this will come in time. I miss intellisense that is built into Visual Studio.   The get-member cmdlet is useful in helping figure out which methods / properties are available to use.  Another command I like is man.  A few years back, I got into FreeBSD and used the 'man' command all the time.  Powershell has this available and it seems natural.  This is a basic blog, but helps me learn Powershell and share some a couple examples for future reference.  Happy Scripting!

    Using MAN to pipe out information on get-member cmdlet

    Type PS c:\>man get-member

    This is what is displayed,  a nice short version of help.

    NAME
        Get-Member
       
    SYNOPSIS
        Gets information about objects or collections of objects.
       
       
    SYNTAX
        Get-Member [[-name] <string[]>] [-inputObject <psobject>] [-memberType {<AliasProperty> | <CodeProperty> | <Propert
        y> | <NoteProperty> | <ScriptProperty> | <Properties> | <PropertySet> | <Method> | <CodeMethod> | <ScriptMethod> |
        <Methods> | <ParameterizedProperty> | <MemberSet> | <All>}] [-static] [<CommonParameters>]
       
       
    DETAILED DESCRIPTION
        Gets information about the members of objects. Get-Member can accept input from the pipeline or as the value of the
         InputObject parameter. You can use the MemberType parameter to specify the type of members you want information ab
        out.
       
        If you pipeline input to Get-Member, it outputs a MemberDefinition object for each distinct type of input object. 
        For example, if you pipe the output of Get-ChildItem to Get-Member in a directory that includes at least one subdir
        ectory and one file, it returns two MemberDefinition objects. One includes information about the FileInfo object an
        d the other includes information about the DirectoryInfo object. Get-Member outputs only two MemberDefinition objec
        ts, regardless of how many files or subdirectories are in the directory.
       
        The output of Get-Member is different if you supply input by using the InputObject parameter. In that case, Get-Mem
        ber returns a single MemberDefinition object that represents either the single input object or the collection class
         that contains the set of input objects.
       
        To retrieve information about static members, you must specify the Static parameter.
       

    RELATED LINKS
        Add-Member
        Get-Help
        Get-Command
        Get-PSDrive

    REMARKS
        For more information, type: "get-help Get-Member -detailed".
        For technical information, type: "get-help Get-Member -full".

    Create a new object at the command line
    $sw = new-object System.IO.StreamWriter("c:\temp\ss.txt")

    Type this to find out all methods available
    $sw | get-member -memberType methods

    PS C:\temp> $sw | get-member -membertype methods


       TypeName: System.IO.StreamWriter

    Name                      MemberType Definition
    ----                      ---------- ----------
    Close                     Method     System.Void Close()
    CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
    Dispose                   Method     System.Void Dispose()
    Equals                    Method     System.Boolean Equals(Object obj)
    Flush                     Method     System.Void Flush()
    GetHashCode               Method     System.Int32 GetHashCode()
    GetLifetimeService        Method     System.Object GetLifetimeService()
    GetType                   Method     System.Type GetType()
    get_AutoFlush             Method     System.Boolean get_AutoFlush()
    get_BaseStream            Method     System.IO.Stream get_BaseStream()
    get_Encoding              Method     System.Text.Encoding get_Encoding()
    get_FormatProvider        Method     System.IFormatProvider get_FormatProvider()
    get_NewLine               Method     System.String get_NewLine()
    InitializeLifetimeService Method     System.Object InitializeLifetimeService()
    set_AutoFlush             Method     System.Void set_AutoFlush(Boolean value)
    set_NewLine               Method     System.Void set_NewLine(String value)
    ToString                  Method     System.String ToString()
    Write                     Method     System.Void Write(Char value), System.Void Write(Char[] buffer), System.Void Wr..
    WriteLine                 Method     System.Void WriteLine(), System.Void WriteLine(Char value), System.Void WriteLi..

    'Create a web request
    $request = [System.Net.WebRequest]::Create("http://www.iislogs.com/testlink.aspx")
    $response = $request.GetResponse()
    $requestStream = $response.GetResponseStream()
    $readStream = new-object System.IO.StreamReader $requestStream
    new-variable db
    $db = $readStream.ReadToEnd()
    $readStream.Close()
    $response.Close()

    'Create a new file and write the contents of that to a file
    $sw = new-object system.IO.StreamWriter("c:\temp\ss2.txt")
    $sw.writeline($db)
    $sw.close()
    get-content "c:\temp\ss.txt"

    Take care,

    Steve Schofield
    Microsoft MVP - IIS

  • Searching logfiles with Powershell, Log parser, Findstr, QGrep

    I'm on a mission!  I have to search log files that are between 150 MB and larger.  These are syslogd files generated.  Here is sample output.

    2007-01-15 00:00:10 Mail.Debug 111.111.111.111 join[00000]: server.steve.net[1.1.1.1] 1168837209-0ff301650000-3Bdfku 1168837209 1168837210 SCAN - info@mydomain.com info@mydomain.com - 2 39 *abcdef.xyz.com SUBJ:Blah this is replaced

    I don't confess to be an expert but this has got to be easier than I'm making it.  I want to share my experiences, so far and I love adventures like this, because I learn a lot. What am I after?  I want the 'server.steve.net[1.1.1.1]' or just [1.1.1.1].  

    Example #1 - For small files this works good

    $sb =  new-object System.Text.StringBuilder
    $re = new-object regex('\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]')
    $m = $re.match((get-content mySysLogfile.txt))
    while ($m.Success)
    {
    $sb.Append($m.value)
    $sb.AppendLine()
    $m = $m.NextMatch()
    }
    $sb.ToString() > st1.txt

    Example #2 - Works for large files extracting the data, performance takes a couple hours.

    $sb =  new-object System.Text.StringBuilder
    $re = new-object regex('\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]')
    $m = [System.IO.File]::OpenText("d:\temp\syslogcatchall16.txt")
    while($line = $m.ReadLine())
    {
    $line = $re.Match($line)
    $sb.Append($line)
    $sb.AppendLine()
    }
    $m.Close()
    $sb.ToString() > st1.txt

    Log Parser example

    'Example 1
    logparser -i:tsv "select top 50 Count(extract_token(field6,1, '[')) as CountOfIt,extract_token(Field6,1,'[') as IPAddress into Steve.csv from  '\\ServerName\ShareName\syslogd11.txt' Group By IPA
    ddress order by CountOfIt DESC" -headerRow:off -iSeparator:'spaces'

    'Example 2
    logparser -i:tsv "select Top 10 Count(field6),Field6 from\\ServerName\ShareName\syslogd11.txt Group By Field6" -headerRow:off -iSeparator:'spaces'

    'Findstr
    http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/findstr.mspx?mfr=true

    'QGrep
    http://www.ss64.com/nt/qgrep.html

    In conclusion, the clear winner was Log parser, speed and accuracy were great.  Powershell was 'cool' but took too long.  Maybe as I get better at Powershell, that will change.  Findstr & QGrep appear to be more for parsing out entire lines of text.  That was my experience, it could be my lack of advanced knowledge with these tools.  I use FINDSTR a lot for doing quick searches, it is faster than FIND.  I was hoping to use regular expressions, but found Powershell was easier to use for regex.  I didn't try a grep utility found on sourceforge, because Log Parser did the trick.  If you have other experiences using FINDSTR, QGrep or some other tool, please pass them along.  Hope this helps!

  • IIS7 - post #27 - Powershell & Microsoft IIS Web.administration blog

  • IIS7 - post #22 - IIS7 and Powershell info

    I've been reading up on Powershell and found a few articles on IIS7 related material.  Using Powershell will be handy with IIS7 because of the new WMI provider.  Also, check out my blog post on Powershell reference links..

    An Introduction to Windows PowerShell and IIS 7.0
    http://www.iis.net/default.aspx?tabid=2&subtabid=23&i=1212

    Writing PowerShell Command-lets for IIS7
    http://channel9.msdn.com/Showpost.aspx?postid=256994

    Managing IIS 7 with Windows PowerShell
    http://www.iis.net/default.aspx?tabid=2&subtabid=25&i=1211

    Enjoy,

    Steve Schofield
    Microsoft MVP - IIS

  • Powershell references

    For the last few years, every holiday season I 'geek' on a particular technology.  This year, Powershell has been generating a lot of buzz in the admin community.  I decided to jump on the bandwagon and check out what this Powershell thing is about.   This posting has some misc links, commands and resources for Powershell.  It is not meant to be an complete list but some places I've visited.  When you install Powershell, there are 2 documents that are a must read before using Powershell.  You can get the documentation here.  I recommend reading GettingStarted.rtf and Userguide.rtf.  This is a nice primer and in-depth documentation provided by Microsoft.  The Userguide.rtf is a 116 page 'readme' type file, I am about 1/2 through reading it.  There is a lot of examples.  I also listed below some links to community resources for help.

    Since 2002, I've used console apps to do an array of administrative functions.  Console apps made it easy to combine .NET and WMI to perform a lot of powerful 'scripting like' activities.  The one drawback applications required Visual Studio to update a 'script'.  I can use Powershell as a way to combine the ease of 'scripting' and power of console apps with .NET.  I've not exposed WMI information yet but I can see this will be one of my favorite methods.  In conclusion, Powershell is a huge leap forward for Administrators.  It introduces a new 'shell' to perform things UNIX admin's have had for years.  Heck, you can even type 'man' to view help.  If you perform administrative functions, I encourage you to check out Powershell.

    0) Few basic cmdlets: Get-Help, Get-Command, Get-Process, Get-Service, and Get-Eventlog.

    1) Get help
    powershell -?

    2) Get help, pipe to a file
    powershell -? | Out-file 2.txt | Notepad 2.txt

    3) Get help, piple to a file, open file in notepad
    powershell -? | Out-file 2.txt | Notepad 2.txt

    4) get-help about_*

    5) get-process | taskkill -pid dw20.exe -f

    6) get-alias is cool!

    7) get-wmiobject win32_bios -computername server01 

    8) Windows PowerShell 1.0 Documentation Pack
    http://www.microsoft.com/downloads/details.aspx?FamilyID=B4720B00-9A66-430F-BD56-EC48BFCA154F&displaylang=en

    9) Windows Newsgroup
    msnews.microsoft.public.powershell

    10) Windows Powershell Blog.
    http://blogs.msdn.com/PowerShell/

    11) Powershell newsgroup
    http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?dg=microsoft.public.windows.powershell

    12) http://msdn2.microsoft.com/en-us/library/aa830112.aspx 

    13) http://mow001.blogspot.com/  (Marc Powershell MVP)

    14) http://sapien.eponym.com/  (MVP book and blog)

    15) http://www.sapienpress.com/WindowsPowerShellTFM_Sample.pdf (Sample chapter on powershell)


Powered by Community Server 2.1