Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

PowerShell V2 Interview: Universal Code Execution Model

Jeffrey Snover did a very interesting V2 Interview: Universal Code Execution Model at TechEd, that now is posted online.

The direct link given on the PowerShell Team blog is not working, but you can access the entire library of interviews HERE.

it's the second from the bottom in this list, and it is available as audio or video (including 491 MB hiRes ;-) )

A very interesting interview about the remoting possibilities for PowerShell V2 , and as always with JPS, don't forget to listen between the lines ;-)

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: , ,

PowerTab V2 Examples

Did not find much time for improvements to the Alpha Build this week, but some examples working in last update

An example of usage in my last post UpToDateness Vector (UTDV) PowerShell exercise  :

image

method overloads on types :

image

on Objects (Note you can use space before invoking TAB again for methods if you tabcompleted the Method (as you need to change one character for Tabexpansion to be invoked)

image

Note that the overload completion only works on the first level for now,

* testers call, please note me of parsing errors thrown back at completion, thx.

For the rest I only changed the download format to .ZIP at (special) request

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: , ,

UpToDateness Vector (UTDV) PowerShell exercise

I did see this post at joeware.com : UpToDateness Vector (UTDV) that was a follow up, at the PowerShell examples Brandon posted . As needed a break from my activities at that moment, To get my head clear, I translated it to PowerShell.

Note that this was just meant as a PowerShell exercise for me, I did not look into the original Problem that much For a detailed background see Brandon and joe's posts and/or the discussion thread.

I started with translating the first part of joe's command :

adfind -default

This I did translate to :

$ds = new-object DirectoryServices.DirectorySearcher

Note : I did not pick the type adapter ... :

[AdsiSearcher]''

... here, as this defaults to the Filter parameter, hence overwriting the default filter, an effect I did not want here.

As in this case as we pick "my default domain on my default domain controller…" this covers the -default switch also.

next this was to cover the -Base switch in the Adfind command As this parameter does set the SearchScope to Base, we do the same in PowerShell by setting the SearchScope property on our DirectorySearcher object :

$ds.SearchScope = 'base'

Note : this is not strictly needed in our case, as the first object returned from our query is the object itself anyway, so we could leave it away but in this case it is good to be clear about it

So we go on to complete the first ADfind command :

adfind -default -s base msDS-NCReplCursors

the last argument here does specify the property to look for, let's do this in PowerShell also :

$ds.PropertiesToLoad.add('msDS-NCReplCursors')

Note here that this step is mandatory, as this attribute is "Lazy" and not retrieved by default by the searcher.

so new we have prepared our DirectorySeacher object, let's invoke it :

$r = $ds.findone().properties.'msds-ncreplcursors'

Note that, I select the property directly on the result of the method here from the resulting properties collection here (adspath is always returned).

As joe mentioned : "That will work from any LDAP query tool you want to use…", but this is not really friendly to work with.

Now did Adfind  have a nice ;Binary option joe shows in his post :

adfind -default -s base msDS-NCReplCursors;binary

I'm not sure how this works exactly bust this gives a much cleaner output, that I also wanted to get from PowerShell.

As you might have see the output returned looks a lot like XML, so I first tried to directly cast it into a XML object by using [XML]

this did complain that there was no root node, hence I added one by embedding the variable into a string like this :

$xml = [xml]"<root>$r</root>"

And yes, this did the trick ! the result looks like this :

image

So far so good, and as we have an XML object now the result is not text but properties.

for in this case the given date is not in a handy format, hence I wanted to translate the Date into a Datetime object, so I used select and calculated properties to convert this also :

$xml.root.DS_REPL_CURSOR | select usnAttributeFilter,@{n='Date';e={get-date $_.ftimeLastSyncSuccess}},pszSourceDsaDN

and now I can do things like this with the data :

image

I sort the result's sorted on the Date and select the first 3 with the following command.

$xml.root.DS_REPL_CURSOR | select usnAttributeFilter,@{n='Date';e={get-date $_.ftimeLastSyncSuccess}},pszSourceDsaDN | sort date -des | select -first 3

this is as far as my 10 minute PowerShell exercise did go, I was loaded up again enough to get to my real work again ;-) but you can see that having created structured data from the returned "XML blob", can be very useful , and it is easy to improve this console exercise, by doing a bit more processing and building it into a function.

For reference the complete code used :

# Get info

$ds = new-object DirectoryServices.DirectorySearcher
$ds.SearchScope = 'base'
$ds.PropertiesToLoad.add('msDS-NCReplCursors')

# Convert to XML

$r = $ds.findone().properties.'msds-ncreplcursors'
$xml = [xml]"<root>$r</root>"

# Usage
$xml.root.DS_REPL_CURSOR

# selecting and converting properties, sorting and filtering

$xml.root.DS_REPL_CURSOR | select usnAttributeFilter,@{n='Date';e={get-date $_.ftimeLastSyncSuccess}},pszSourceDsaDN | sort date -des | select -first 3

Ok a bit more as :

adfind -default -s base msDS-NCReplCursors;binary

but we did create structured data in the PowerShell example, that we can easy work with the data in PowerShell, as I showed selecting, sorting, filtering the data is a trivial task from here.

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments

Keeping up with the Community

It's hard to keep up with all PowerShell info that comes up lately.here a list of video and audio sources, that I did view/listen to recently :

As I mentioned in Powershell tips and tricks from the field ...  (links to demos there )

Now the Complete session Windows, PowerShell, and Windows Management Instrumentation: Unveiling Microsoft's Best Kept SecretBen Pearce

And also from Teched :

Advances Microsoft SQL Server PowerShell Tips and Tricks, Dan Jones

And even more from Teched

Using Powershell to managed Hyper-V (edge interview) and the Spotlight video about the complete session :

http://www.microsoft.com/emea/spotlight/sessionh.aspx?videoid=996

a new podcast :

Get-Scripting podcast by Jonathan Medd with in the first pilot episode James one  http://www.codeplex.com/PSHyperv

Also the teched series from Don Jones features small videos now to support the articles :

Don Jones V2 Sneak peek

Also of course the powerscripting podcast (keep also a good look at the Shownotes on the blog for good resource links.) I'm now listening to episode 36 about /N Cmdlets.

And some  I forgot (sorry).

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments
Filed under: , ,

PowerShell, CdAudioDoor Module

I got nifty Add-Type trick from Tao Ma to open and close the CD door that he also posted on his blog here : http://blog.csdn.net/PowerShell/archive/2008/08/03/2761960.aspx

He is using Add-Type to do a P/Invoke call, Cool stuff ! right ?,

but as Jeffrey Snover mentioned here V2: Custom Enums using add-type is final, and we can only add the type once, hence you can not add it to the function

As the example already needs PowerShell CTP2 as it uses Add-Type, I did see it fit to translate into a module to solve this problem, also I made it a Script Cmdlet to show the use of ValidateSet to define the allowed options (Open,Closed) and it will enforce them :

$winnm = Add-Type -memberDefinition @"
  [DllImport("winmm.dll", CharSet = CharSet.Ansi)]
  public static extern int mciSendStringA(
  string lpstrCommand,
  string lpstrReturnString,
  int uReturnLength,
  IntPtr hwndCallback);
"@  -ErrorAction 'SilentlyContinue' -passthru -name mciSendString

cmdlet Set-CDAudioDoor {

  Param(
    [ValidateSet("open", "closed")][String[]]$Mode = 'open'
  )

  $winnm::mciSendStringA("set cdaudio door $mode", $null, 0,0)

}

As you save this code as CdAudioDoor.psm1 you can add it with add-module

Adding the Module will add the Cmdlet, also PowerShell takes care that the initialization code is being executed only once.

image

This is only a simple example of what Script Cmdlets and Modules can do, export specific script cmdlets only etc. but I think this is a nice example to peek at the great possibilities modules in PowerShell V2 can offer, for more info about Modules see also Jaykul's great post PowerShell Modules .

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: , ,

just silly

go to a place that does not exist in PowerShell

c:;(get-psdrive c).CurrentLocation = '\I do Not exist'

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 8 Comments
Filed under: ,

PowerTab for PowerShell V2 Update

I posted, 8 updates since PowerTab for PowerShell V2 Alpha testers wanted (link to download in former post) mostly working with Xaegr 

I did some hard work on the Member completion (3 rewrites) , but it is almost there,

For the other Alpha Testers, I added another eager missed feature FileSystem completion that I would like you to take a look at

relative filesystem, and UNC path completion (shares broken in latest build, but will be fixed ;-) )

image

Registry :

image

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 4 Comments
Filed under: , ,

The Show goes on

See: Translating Literature Into PowerShell ,

Hmm, would you only be able to translate books to PowerShell this way ? :

while {$Question.IsAnswered -eq $false) {if ($TheOne){switch $pill {'Red'{exit};"Blue {$memory.reset()}}}

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments
Filed under: ,

PowerTab for PowerShell V2 Alpha testers wanted

As I did mention in last post ( PowerTab for PowerShell V2  ), I started working on PowerTab for PowerShell V2, and I posted the current version some day's ago and made 5 updates to it in that time.

I'm looking for some Alpha testers that have a bit experience with PowerTab and want to give detailed input.

This is only an alpha version and not as functional as the current PowerTab so no need to install this Alpha build looking for more functionality yet, so first some warnings.

  • CTP2 needed 
  • No Custom completion
  • No configuration
  • No powertab file completion
  • No install
  • Not everything works as expected yet
  • irregular updates

OK, if you still feel up to it after those warnings, You can find the latest version here :

http://thepowershellguy.com/blogs/posh/pages/powertab-v2-alpha-1.aspx

Status :

I did implement a lot of bugs and tips from Xaegr (See also his  Screencast about Powertab )

Current Focus :

Installation

Simple but run update-Tabexpansion and Export-Tabexpasion by hand after first install (to overwrite my database)

creating of new database still needs to be done.

for the rest as it is a Module now  the installation is very simple, follow Jaykul's excellent intro here : PowerShell Modules

Parameter completion

I'm implementing Parameter completion on Script Cmdlets, for example help is now a script cmdlet :

 image

Completion on Arguments that are enums :

image

Completion on scripts :

image

Member completion

I'm implementing Member completion on $_. ( Note, that members from File and directory objects are mixed in the completion)

image

Other Things to try :

image

Also try the examples in the NewTest.txt you will find in the PowerTab directory.

You can leave a comment with your bugs, tips, requests etc. or you can mail me at the mail address on the About page, (with pictures etc)

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 2 Comments
Filed under: , ,

PowerTab for PowerShell V2

I got a lot of questions about the future of PowerTab lately, so a teaser of what is coming in a new version of PowerTab for the CTP2 version of PowerShell:

- No Installer

PowerTab is now a Module, so installation will be as easy as copying the directory to the Packet location and running Add-Module PowerTab

- Using the Tokenizer

- $_ support

- ArgumentType support

and more to come ...

-

image

A first Alpha version can be expected later this week.  found here : http://thepowershellguy.com/blogs/posh/pages/powertab-v2-alpha-1.aspx

Note that this is an Alpha version, with still less functionality as current PowerTab, targeted at readers that want to help testing.

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 6 Comments
Filed under: , ,

PowerShell Get-Ipconfig function

 

In a comment on this post PowerShell on joeware.net , I translated a Perl example that used ipconfig information, I used the same regex techniques as in the Perl example, but this made me think of a more PoSHy  general wrapper that exposes the ipconfig information as an object in PowerShell.

for convenience I also added text output to the console by default (you can suppress this with the -Silent Switch) so you can use it as a quick lookup as Ipconfig, but it also returns a dynamically build Object that you can use to access all information hierarchal by digging into the properties.

You can use the properties (and tab completion) to access the property of interest from the output for interactive or script usage.

See examples below :

image

The Get-IpConfig function shown above looks like this :

Function get-Ipconfig ([switch]$silent){
  $ipc = ipconfig /all
  $ipcObject = New-Object object
  $ipc |% {

    if (.{$m = [regex]::Matches($_,'^(\w.*?):*$');$m[0]}) {
        $script:o = New-Object object
        Add-Member -InputObject $o -MemberType ScriptMethod -Name ToString -Value {$this.psobject.properties |% {$_.name + " = " + $_.value + "`n"}} -force
        Add-Member -InputObject $ipcObject -MemberType NoteProperty -Name $m[0].groups[1].value.replace(' ','') -Value $o
    } elseIf (.{$m = [regex]::Matches($_,'(.*?)[ \.]*: (.*)');$m[0]}){
        $script:p = $m[0].groups[1].value.replace(' ','')
        Add-Member -InputObject $script:o -MemberType NoteProperty -Name $m[0].groups[1].value.replace(' ','') -Value $m[0].groups[2].value
    } elseIf (.{$m = [regex]::Matches($_,'\w+.*');$m[0]}){
        $script:o."$p" += ";" + $m[0].groups[0] 
    }
  }
  if (!$silent) {$ipcobject | fl | out-string | write-host -fore 'Yellow'}
  $ipcobject
}

Note that this is only a simple example and as I build the property list dynamic I do keep all properties text, and not translate them but the use of nested Noteproperties might be interesting to look at, as it might come of use sometime, note also the overload of the ToString() Method for custom formatting with Format-List ;-)

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 13 Comments

Hey PowerShell Guy !, How Can I Copy Files Based on Multiple Criteria?

A Translation of the Scripting Guys post : How Can I Copy Files Based on Multiple Criteria? VbScript example,

As mostly in this series I point to the original Article for more information.

dir c:\Scripts |? {$_ -match "^FS|^CG|^GPS." -and $_.CreationTime -gt (get-date).AddDays(-1)} | copy -dest C:\Test

And on the Scripting Guy's remark in the article :

2) with Windows PowerShell 1.0 we wouldn’t be able to run this script against a remote computer. 

not really as we can just as easy use UNC paths in the command ;-p 

dir \\server\c$\scripts .....

or of course by using WMI  as in the Vbscript example

* Update * OK, I could not resist here is the WMI oneliner, doing exactly the same as the Scripting Guy's VbSCript version :

([WmiSearcher]"ASSOCIATORS OF {\\.\root\cimv2:Win32_Directory.Name='C:\Scripts'} Where ResultClass = CIM_DataFile").Get() |? {$_.ConvertToDateTime($_.CreationDate) -gt (get-date).AddDays(-1) -and $_.FileName -match "^FS|^CG|^GPS." } |% {$_.copy(("c:\test\{0}.{1}" -f $_.filename,$_.Extension))}

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments
Filed under: ,

Little PoSH prank

I came up with this little prank while on IRC,

give this command on a colleague's workstation (he did not lock) in a PowerShell console and minimize it  , and you might have some fun watching him when he gets back ;-)

do {[Windows.Forms.Cursor]::Position = "1,1";sleep 5}until (0)

enjoy,

Greetings /\/\o\/\/

Posted by MoW | 3 Comments
Filed under: ,

PowerShell projects on Codeplex, 37 and Growing

I often recommend peaple to keep an eye on , these articles might tell you why :

PowerTools Script that Generates a Table in an Open XML Document

Hyper-V PowerShell library - now on Codeplex

Windows Mobile PowerShell Provider released (MS Mobiles)

This brings the count of current  PowerShell Projects on CodePlex to 37 !

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: ,
More Posts Next page »