Search PowerShellers and other PowerShell-related sites

Friday, October 14, 2011

The PowerShell Deep Dive USA 2011

While waiting for the PowerShell Deep Dive Europe, look at some of never-seen-before photos from the PowerShell Deep Dive USA, held in Las Vegas in April.



It’s not too late to sign up for the October 17 & 18 PowerShell Deep Dive:

Go to the TEC registration page
Create an account. You need to do this again for TEC Europe, even if you attended TEC USA earlier this year.
Enter registration code: ATGNJR6E
Select “PowerShell Deep Dive” for the “Which conference do you plan to attend” question.

Monday, November 22, 2010

PowerShell Dinner at TechEd Europe 2010

Another conference, another PowerShell Dinner... Here are the pictures from PowerShell Dinner we had at Teched Europe 2010. The dinner was a great event thanks to our hosts Dmitry Sotnikov and Kenneth Hansen, the iconic Jeffrey Snover and other members of PowerShell team, and a great group of old, new and future MVP guys.



Dmitry has chosen the same restaurant (Meineke X) as last year and we again enjoyed delicious traditional German food and beer. We've missed Apfelstrudel, but Rote Grütze has saved the day. :) It is not an overstatement to say it was really one of the highlights of the year! You can see the whole PowerShell Dinner at TechEd Europe 2010 album.

Monday, November 23, 2009

PowerShell Dinner at TechEd Europe 2009

Here are the pictures from PowerShell Dinner we had at Teched Europe 2009. The dinner was a great event thanks to our host Dmitry Sotnikov, the one and only Jeffrey Snover, amazing MVP guys, and a bunch of European PowerShellers.

From PowerShell Dinner at TechEd Europe 2009

It was a great privilege to talk about PowerShell with fellow PowerShell addicts. And, let's not forget to mention delicous food and German beers. One of the highlights of the year! You can see the whole PowerShell Dinner at TechEd Europe 2009 album.

Thursday, October 15, 2009

PowerShell V2: Meet New-Object's Property parameter

I've stumbled upon blog post that talks about accessing remote registry, collecting "Automatic Update" configuration info and creating custom object to hold that data for further processing/formatting.

The author has used Add-Member cmdlet to add quite a bunch of NoteProperties to the custom object. In PowerShell V2 we can do it in much cleaner way, with less typing, using new New-Object's Property parameter that expects a hash table as a value, a hash table in which the keys are the names of properties or methods and the values are property values or method arguments.


Let's rewrite a function.
function Get-WSUSRegKey {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true)]
[String[]]$ComputerName = $env:computername
)

PROCESS {
$ComputerName | ForEach-Object {
# open remote registry key
$rootKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$_)
# open subkey WindowsUpdate and its subkey AU
$regKey0 = $rootKey.OpenSubKey("Software\policies\Microsoft\Windows\WindowsUpdate\")
$regKey1 = $rootKey.OpenSubKey("Software\policies\Microsoft\Windows\WindowsUpdate\" + $($regKey0.GetSubKeyNames()))

# create an empty hash table
$ht = @{}
# enumerate value names in both subkeys and populate hash table with name/value pairs
$regKey0.GetValueNames() | ForEach-Object {$ht.$_ = $regKey0.GetValue($_)}
$regKey1.GetValueNames() | ForEach-Object {$ht.$_ = $regKey1.GetValue($_)}
# this will add ComputerName NoteProperty to our object
$ht.ComputerName = $_
# and finally, create an object using the data stored in a hash table
New-Object PSObject -Property $ht
}
}
}

Two usage examples:

PS C:\> $servers = 'server1','server2','server3'
PS C:\> Get-WSUSRegKey -ComputerName $servers
PS C:\> $servers | Get-WSUSRegKey | Format-Table ComputerName,WUServer

Thursday, June 11, 2009

How to get computer SID using PowerShell

Let's start with the theory. ;)

The computer SID is stored in the HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account Registry subkey. This key has a value named F and a value named V. The V value is a binary value that has the computer SID embedded within it at the end of its data. This SID is in a standard format (3 32-bit subauthorities preceded by three 32-bit authority fields).

Because you can't see the SECURITY hive's contents by default (even as an administrator), you need a little trick. Use at command to schedule the startup of PowerShell. Make sure that you schedule the task as Interactive and that the Scheduler service runs in the security context of the System (aka LocalSystem) account because this account—unlike a regular user account—has privileges to view the SAM and SECURITY hives.

c:\> at TIME /interactive powershell.exe


PS> $key = Get-Item HKLM:\security\sam\domains\account
PS> $values = Get-ItemProperty $key.pspath
PS> $bytearray = $values.V
PS> New-Object System.Security.Principal.SecurityIdentifier($bytearray[272..295],0) | Format-List *

BinaryLength : 24
AccountDomainSid : S-1-5-21-796845957-602608370-839522115
Value : S-1-5-21-796845957-602608370-839522115


You can check your result with Sysinternals' PsGetSid:

PS> .\psgetsid.exe 

SID for \\COMPUTER:
S-1-5-21-796845957-602608370-839522115

Sunday, May 3, 2009

What happened to a CustomMenu property?

If you'd like to customize your Windows PowerShell ISE be prepared for some breaking changes in Windows PowerShell ISE that comes with Windows 7 RC (May I call it Windows PowerShell ISE RC?). In Windows PowerShell ISE CTP3 $psISE, custom host variable, has following properties:

PS C:\> $psISE | gm -MemberType property


TypeName: System.Management.Automation.Host.PSGHost

Name MemberType Definition
---- ---------- ----------
CurrentOpenedFile Property System.Management.Automation.Host.OpenedFile CurrentOpenedFile {get;}
CurrentOpenedRunspace Property System.Management.Automation.Host.OpenedRunspace CurrentOpenedRunspace {get;}
CustomMenu Property System.Management.Automation.Host.PSMenuItem CustomMenu {get;}
OpenedRunspaces Property System.Management.Automation.Host.OpenedRunspaceCollection OpenedRunspaces {get;}
Options Property System.Management.Automation.Host.Options Options {get;}


Same command in Windows PowerShell ISE RC will give renamed type and properties:

TypeName: Microsoft.PowerShell.Host.ISE.ObjectModelRoot

Name MemberType Definition
---- ---------- ----------
CurrentFile Property Microsoft.PowerShell.Host.ISE.ISEFile CurrentFile {get;}
CurrentPowerShellTab Property Microsoft.PowerShell.Host.ISE.PowerShellTab CurrentPowerShellTab {get;}
Options Property Microsoft.PowerShell.Host.ISE.ISEOptions Options {get;}
PowerShellTabs Property Microsoft.PowerShell.Host.ISE.PowerShellTabCollection PowerShellTabs {get;}


Runspace is PowerShell Tab now, and Opened was unnecessary, but what happened to a CustomMenu property?

Let's see what CurrentPowerShellTab can offer:

PS C:\> $psISE.CurrentPowerShellTab | gm


TypeName: Microsoft.PowerShell.Host.ISE.PowerShellTab

Name MemberType Definition
---- ---------- ----------
... ... ...

AddOnsMenu Property Microsoft.PowerShell.Host.ISE.ISEMenuItem AddOnsMenu {get;}
... ... ...


It looks that we are on a right track. We used to run a command such as the following one to add customized menu item:

$psISE.CustomMenu.Submenus.Add("Run single line", {Invoke-CaretLine} , 'F7')


So, what we are looking for is a Submenus property. Let's hope that an AddOnsMenu has one. :)


PS C:\> $psise.CurrentPowerShellTab.AddOnsMenu | gm -MemberType property


TypeName: Microsoft.PowerShell.Host.ISE.ISEMenuItem

Name MemberType Definition
---- ---------- ----------

Action Property System.Management.Automation.ScriptBlock Action {get;}
DisplayName Property System.String DisplayName {get;}
Shortcut Property System.Windows.Input.KeyGesture Shortcut {get;}
Submenus Property System.Collections.Generic.IList`1[[Microsoft.PowerShell.Host.ISE.ISEMenuItem...


Bingo!

PS C:\> $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | gm


TypeName: Microsoft.PowerShell.Host.ISE.ISEMenuItem

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Action Property System.Management.Automation.ScriptBlock Action {get;}
DisplayName Property System.String DisplayName {get;}
Shortcut Property System.Windows.Input.KeyGesture Shortcut {get;}
Submenus Property System.Collections.Generic.IList`1[[Microsoft.PowerShell.Host.ISE.ISEMenuItem...


What the fluff?! Where is an Add method?
As we have learnt in V1, when you miss some member use a psbase property:

PS C:\> $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.psbase | gm


TypeName: System.Management.Automation.PSMemberSet

Name MemberType Definition
---- ---------- ----------
CollectionChanged Event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged(System....
Add Method Microsoft.PowerShell.Host.ISE.ISEMenuItem Add(string displayName, scriptblock action,...
Clear Method System.Void Clear()
Contains Method bool Contains(Microsoft.PowerShell.Host.ISE.ISEMenuItem item)
CopyTo Method System.Void CopyTo(Microsoft.PowerShell.Host.ISE.ISEMenuItem[] array, int arrayIndex)
Equals Method bool Equals(System.Object obj)
GetEnumerator Method System.Collections.Generic.IEnumerator[Microsoft.PowerShell.Host.ISE.ISEMenuItem]
GetHashCode Method int GetHashCode()
GetType Method type GetType()
IndexOf Method int IndexOf(Microsoft.PowerShell.Host.ISE.ISEMenuItem item)
Insert Method System.Void Insert(int index, Microsoft.PowerShell.Host.ISE.ISEMenuItem item)
Remove Method bool Remove(Microsoft.PowerShell.Host.ISE.ISEMenuItem item)
RemoveAt Method System.Void RemoveAt(int index)
ToString Method string ToString()
Item ParameterizedProperty Microsoft.PowerShell.Host.ISE.ISEMenuItem Item(int index) {get;set;}
Count Property System.Int32 Count {get;}
IsReadOnly Property System.Boolean IsReadOnly {get;}


That's much better. :)

Now it's easy to add our first customized menu item:

$action = {$p = Read-Host "Enter parameter name";Get-Help * -parameter $p}
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Find parameter",$action,'Ctrl+Shift+F3')


If we want to create a submenu, we need to omit an action:

$m = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Execution Policy",$null,$null)


And then we can add the menu items:

$m.Submenus.Add("Get policy",{Get-ExecutionPolicy},'CTRL+Shift+J')
$m.Submenus.Add("Set policy",{Set-ExecutionPolicy RemoteSigned},'CTRL+Shift+K')


These changes are not persistent, and we will loose them when we close Windows PowerShell ISE. We can really extend our environment by putting the code into our Windows PowerShell ISE profile.

To summarize, Windows PowerShell ISE can have up to 8 PowerShell Tabs, and every tab can have its own set of customized menu items and submenus.

While we talk about changes in a new Windows PowerShell ISE, let's not forget that some shorcuts are changed as well (Run Selection is F8 now) and new toolbar is common for all three panes. The best new built-in menu item is the New Remote PowerShell Tab... which will start an interactive session with a remote computer.

Saturday, May 2, 2009

Upgrade Virtual PC 2007 before you virtualize Windows 7 RC

If you plan to install Windows 7 RC using Microsoft Virtual PC 2007, upgrade it to Virtual PC 2007 SP1 (6.0.192.0). Old version (6.0.156.0) will give you BSOD after you install Virtual Machine Additions (Error: Fs_Rec.sys - The driver mistakenly marked a part of its image pagable instead of nonpagable.)
Happily, System Restore works great. :)

Tuesday, February 17, 2009

Get-Alias ?

If you want to find the cmdlet "behind" the alias ?, command Get-Alias ? won't help you, because ? will be treated as a wildcard for a single character, and you will get all single-character aliases:

PS>get-alias ?

CommandType  Name    Definition
-----------  ----    ----------
Alias        %       ForEach-Object
Alias        ?       Where-Object
Alias        h       Get-History
Alias        r       Invoke-History

To use ? as the literal value, you have to escape it with a backtick and put it in single quotes:

PS>get-alias '`?' 

CommandType  Name    Definition
-----------  ----    ----------
Alias        ?       Where-Object

Double quotes don't work in both V1 and V2 CTP3. Does somebody know why?

Friday, February 6, 2009

Do you know the aliases for the New-Item cmdlet?

I was playing with Doug Finke's extensions for PowerShell ISE (Integrated Scripting Environment), Expand-Alias and Expand-CurrentAlias, when I've noticed that mkdir doesn't expand and md expands to mkdir. Up until now I thought that mkdir and md are aliases for the New-Item cmdlet as rmdir and rd are the aliases for the Remove-Item cmdlet.

In both PowerShell V1 and V2 CTP3:

PS> get-alias | ? {$_.definition -eq 'remove-item'}

CommandType Name  Definition
----------- ----  ----------
Alias       ri    Remove-Item
Alias       rm    Remove-Item
Alias       rmdir Remove-Item
Alias       del   Remove-Item
Alias       erase Remove-Item
Alias       rd    Remove-Item



PS> get-alias | ? {$_.definition -eq 'new-item'}

CommandType Name Definition
----------- ---- ----------
Alias       ni   New-Item


Where are the mkdir and md?

The mkdir and md are built-in functions in PowerShell V1 with the same definition:

PS> gci function: | ? {$_.name -like 'm*d*'} | ft -auto

CommandType Name  Definition
----------- ----  ----------
Function    mkdir param([string[]]$paths); New-Item -type directory -path $paths
Function    md    param([string[]]$paths); New-Item -type directory -path $paths


The things are different in PowerShell V2 CTP3. The mkdir command is still a function, but with much more complex definition, and md is an alias for mkdir.


PS> gci function: | ? {$_.name -like 'm*d*'}

CommandType Name  Definition
----------- ----  ----------
Function    mkdir ...

PS> get-alias md

CommandType Name Definition
----------- ---- ----------
Alias       md   mkdir


To see the code behind mkdir command type:

PS> gc function:\mkdir



Very nice example of an advanced function.

Monday, November 10, 2008

-include and -exclude go together

While reading James Brundage's blog post Microcode: Exploring More of .NET with Get-Assembly, I have spotted a rather unnecessary complicated part of a code:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -filter "*.dll" |
Where-Object {
! $_.Name.Substring(0,$_.Name.IndexOf($_.Extension)).EndsWith(".ni")
}


The goal was to remove from the list of the DLLs those files named something like AssemblyName.Ni.Dll, because they cannot be loaded. At first I thought this is the right job for a -notlike operator:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -filter "*.dll" |
Where-Object {$_.name -notlike "*.ni.*"}


It'll do the job and it's much cleaner (and simpler).

On the other hand, Get-ChildItem has an -exclude parameter. It must be faster than piping to Where-Object. Why not use that instead? To my surprise the combination of -filter and -exclude parameters produced totally wrong result.

Fortunately, Get-ChildItem has an -include parameter too, which can be used instead of a -filter in this case (hat tip to Joel 'Jaykul' Bennett). So, the final command is:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -include "*.dll" -exclude "*.ni.*"


Isn't that easier to write (and probably faster to execute)?

Monday, October 6, 2008

An interview with Tobias Weltner

For those of you who have missed it when it was broadcasted live, new episode of famous PowerScripting Podcast is online and ready for listening. In this episode Tobias Weltner gives an inside look at PowerShellPlus Professional Edition. Hal Rottenberg and Jonathan Walz had a bag full of great questions (with a nice contribution from the guys in the ustream.tv chat room) and it seems that Tobias was more than willing to give them in-depth coverage of the PowerShellPlus history and new features in version 2.0.

Tuesday, August 12, 2008

"LDAP query" versus "WHERE"

Here is the good example for Jeffrey Snover's post "When NOT To Use "WHERE"". This is original Andrey Moiseev's one-liner to get a list of all computed attributes in AD, mentioned in Dmitry Sotnikov's post "List all Constructed Attributes"

Get-QADObject -SearchRoot "CN=Schema,CN=Configuration,dc=MyDomain,dc=COM" -Type attributeSchema -IncludedProperties systemFlags -SizeLimit 0 | where {$_.SystemFlags -band 4}


This one-liner needs 120 seconds to complete on my system.

Let's try the same thing, but this time with LDAP query:

Get-QADObject -SearchRoot "CN=Schema,CN=Configuration,dc=MyDomain,dc=COM" -ldapfilter '(systemFlags:1.2.840.113556.1.4.803:=4)' -Type attributeSchema -IncludedProperties systemFlags -SizeLimit 0


I can see a list of all computed attributes in AD in just 3 seconds.

Tuesday, June 10, 2008

The "#requires" statement

Most of us are familiar with #requires -version 2. Jeffrey Snover had written about versioning just before the release of a Community Technology Preview (CTP) of Windows PowerShell v2.0. You start your script with
#requires -version 2
and PowerShell will check version #'s and produce a precise error message.

The "#requires" statement is not a new feature of PowerShell v2. It's with us from the PowerShell v1, but no one cared outside the PowerShell team. ;-)

Do you know that you can check for the presence of the other things too?

The "#requires" statement must be in one of the following formats:
"#requires -shellid <shellid>"
"#requires -version <major.minor>"
"#requires -pssnapin <pssnapinname>[-version <major.minor>]"


For example, you can check if quest.activeroles.admanagement snap-in is added to the current console. Put #requires -pssnapin quest.activeroles.admanagement in your script, and if the snap-in isn't added, you will get nice error message.

The script 'test.ps1' cannot be run because the following Windows PowerShell snap-ins that are specified
by its "#requires" statements are missing: quest.activeroles.admanagement.


By the way, is there any other reserved "comment" statement?

Thursday, May 29, 2008

Search PowerShellCentral Script Repository

This is simple function that will help you search PowerShellCentral Script Repository right from the command line.

function Search-PSCentral {
param([string]$keyword)
(New-Object –com Shell.Application).Open("http://powershellcentral.com/scripts/?lang=&q=*$keyword*")
}


Usage: Search-PSCentral ini

If you leave out a keyword or there are no results, the page will open ready for you to paste in some code and fill the gap. :-)

Friday, November 9, 2007

SDM GPMC PowerShell Cmdlets 1.0

From now on SDM Software is offering SDM GPMC PowerShell Cmdlets 1.0 for free. This version comes with 9 cmdlets for performing GPO management tasks from creating and deleting GPOs, to linking and unlinking them, to modifying GPO security, to backing up and restoring GPOs. After installation you can run them from Start menu or you can add snap-in to your profile file.

Add-PSSnapin SDMGPOSnapIn

After the snap-in is added, you can use 9 new cmdlets.

PS>get-command *sdm* -commandtype cmdlet
Name
----
Add-SDMgplink
Add-SDMgpoSecurity
Export-SDMgpo
Get-SDMgpo
Get-SDMgpoSecurity
Import-SDMgpo
New-SDMgpo
Remove-SDMgpo
Remove-SDMgpoSecurity

Monday, July 2, 2007

Translate with Google Dictionary Translation and PowerShell

Google Translate has added a nifty new feature: dictionary translation. Dictionary translation is currently available between English and French, Italian, German, Spanish, and Korean. You can get it right from the command line with a little help from PowerShell.



# Usage:
# Get-Translation -word power -dictionary ef
# Get-Translation shell ei
# gt "ab und zu" de

Function Get-Translation {
param([string]$word="",[string]$dictionary="")

switch($dictionary) {
ef {$langpair = "en%7Cfr"} # English-French
fe {$langpair = "fr%7Cen"} # French-English
ed {$langpair = "en%7Cde"} # English-German BETA
de {$langpair = "de%7Cen"} # German-English BETA
ei {$langpair = "en%7Cit"} # English-Italian
ie {$langpair = "it%7Cen"} # Italian-English
ek {$langpair = "en%7Cko"} # English-Korean
ke {$langpair = "ko%7Cen"} # Korean-English
es {$langpair = "en%7Ces"} # English-Spanish
se {$langpair = "es%7Cen"} # Spanish-English
}

$objIE = New-Object -Com Internetexplorer.Application
$url = "http://translate.google.com/translate_dict?q=" + $word + "&sa=N&hl=en&langpair=" + $langpair
$objIE.Navigate($url)
$objIE.Visible=$true
}

Set-Alias gt Get-Translation




A dictionary translation of your word or short phrase will be displayed in Internet Explorer.

Monday, May 21, 2007

How to easy format date/time

One of the easiest ways to format date and time is the command

get-date -format <string>


<string> represents the format specifier. For a list of available format specifiers, see the System.Globalization.DateTimeFormatInfo Class topic in MSDN or look at these examples:


PS> get-date -format d
5/21/2007
PS> get-date -format D
Monday, May 21, 2007
PS> get-date -format f
Monday, May 21, 2007 9:24 PM
PS> get-date -format F
Monday, May 21, 2007 9:24:41 PM
PS> get-date -format g
5/21/2007 9:24 PM
PS> get-date -format G
5/21/2007 9:24:50 PM
PS> get-date -format m
May 21
PS> get-date -format M
May 21
PS> get-date -format o
2007-05-21T21:25:03.4218750+02:00
PS> get-date -format r
Mon, 21 May 2007 21:25:09 GMT
PS> get-date -format R
Mon, 21 May 2007 21:25:12 GMT
PS> get-date -format s
2007-05-21T21:25:17
PS> get-date -format t
9:25 PM
PS> get-date -format T
9:25:23 PM
PS> get-date -format u
2007-05-21 21:25:28Z
PS> get-date -format U
Monday, May 21, 2007 7:25:34 PM
PS> get-date -format y
May, 2007
PS> get-date -format Y
May, 2007



This blog entry has been inspired by Per Ostergaard and Jeffrey Snover.

Monday, March 26, 2007

Spring-cleaning of a PowerShell profile

After I read James Manning's post why share-able functions shouldn't be in your PowerShell profile, I have looked in my $profile. It was far from small file focused on prompt function, transcript function, one-liners and aliases. So, I created a few subfolders (AD, ISA, Exchange, Misc, Test...) for my scripts in WindowsPowerShell folder. Also, the functions found their place in dedicated folder Functions. The only thing that left is to put all folders with scripts in my path and to dot-source functions from Functions folder.


$profilehome = ([System.IO.FileInfo]$PROFILE).DirectoryName

dir $profilehome | where {$_.PsIsContainer -and ($_.name -ne "functions")} | %{$env:path += ";" + $profilehome + "\" + $_.name}

dir ($profilehome + "\functions") | where {!$_.PsIsContainer} |
%{. ($profilehome + "\functions\" + $_.name)}



$profile is now clean and tidy, and in James Manning's words - it's a far more robust, maintainable, shareable, and supportable situation than before.

Wednesday, March 14, 2007

Daily notes with PowerShell

The post at Holistic Detection blog gave me an idea how to keep my daily notes organized and just a few keystrokes away.


function New-DailyNotes {

# store files in subfolder notes in WindowsPowerShell folder
$path = (join-path ([System.IO.FileInfo]$profile).DirectoryName \notes\)
# files will be named like 2007-03-14_notes.txt
$notesfile = (get-date).ToString("yyyy-MM-dd") + "_notes.txt"

if( !(test-path $path ) )
{
# create the notes directory if it doesn't exist
new-item -path $path -type directory
}

$notespath = (join-path $path $notesfile)
if( !(test-path $notespath ) )
{
# create the notes file if it doesn't exist
new-item -path $path -name $notesfile -type "file"
notepad $notespath
}
else
{
notepad $notespath
}

}

set-alias dn New-DailyNotes



I've added this function to the profile file and I only have to type dn to get access to my daily notes file.

Sunday, November 12, 2006

Osnove - Uvod u objektni model

Ključna stvar u čemu se Windows PowerShell razlikuje od sličnih shell okruženja jeste osobina da radi isključivo sa objektima. Rezultat komande koju kucate u shell-u na Linux-u je tekst. Na primer

#ps -e
PID TTY TIME CMD
1 ? 00:08:00 init
12021 ? 00:00:00 kdm



Ukoliko sada želimo da prekinemo proces kdm moramo da izdvojimo deo teksta koji se odnosi na broj procesa (PID kolona) i da ga prosledimo kao parametar komandi za prekid procesa (kill).

# ps -e | grep " kdm" | awk '{ print $1 }' | xargs kill



Problem ovog pristupa je da veci deo vremena provodimo formatirajući tekst, što može da bude složeno i zamorno, ali se zato sve komanda se izvršavaju gotovo trenutno.

Windows PowerShall sa druge strane radi sa objektima. Pogledajmo šta se dešava ako otkucamo komandu dir

PS> dir

Directory: Microsoft.PowerShell.Core\FileSystem::C:\

Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 9/23/2006 2:23 PM ATI
d---- 9/21/2006 10:41 PM Documents and Settings
...



Iako reuzultat izgleda kao par redova teksta, u stari u pitanju je niz objekata koji su tipa System.IO.FileInfo. Ukoliko vas ovo podseća na .NET, u pravu ste, osnova Windows PowerShell-a jeste .NET.

Komande su u stvari funkcije čiji su ulazi i izlazi objekti. Ako se vratimo našem primeru koji prekida proces kdm, ekvivalentan primer bi u PS bi bio:

PS> get-process kdm | stop-process



Vidi se da je zapis mnogo čitljiviji, jedina mana je što se malo gubino na brzini. Meni se iskreno ovo mnogo više sviđa, jer se kod lakše i brže piše.

Ovo se može mnogo bolje videti na malo složenijem primeru, sledeće komande prekidaju sve procese koji troše više od 10MB memorije.

bash

# ps -el | awk '{ if ( $6 > (1024*10)) { print $3 } }' | grep -v PID | xargs kill



Windows PowerShell

PS> get-process | where { $_.VS -gt 10M } | stop-process



Čak i ako nikada niste videli PowerShell, velika je verovatnoća da će te samo na osnovu koda razumeti o čemu se radi. Što se bash-a tiče tu ne bih bio tako siguran.

Ovo je tek početak, u sledećem tekstu videćemo da su i promenljive objekti. Takođe videćemo kako lako možemo da saznamo koji svi properties i methods postoje za neki objekat.

Friday, October 20, 2006

Code Test 2

1: $a = ipconfig /all | findstr "172.16.1." | %{$_.remove(0,44)}
2: route add 192.168.0.0 mask 255.255.0.0 $a

Thursday, October 19, 2006

Da li ste već čuli za Windows PowerShell?

Windows PowerShell. Najvrelija stvar koja ovih dana stiže iz Redmonda. Šta je Windows PowerShell? Da se ne bih pravio pametniji od samih tvoraca, pravo je vreme da ubacim mali citat, direktno sa MS sajta - "Microsoft Windows PowerShell command line shell and scripting language helps IT Professionals achieve greater productivity. Using a new admin-focused scripting language, more than 130 standard command line tools, and consistent syntax and utilities, Windows PowerShell allows IT Professionals to more easily control system administration and accelerate automation." Ključne reči su: command line shell, scripting language i admin-focused.

Kao da se svakog dana pojavljuju novi blogovi koji se njime bave (a još se nije ni pojavila finalna verzija). Jedna od udarnih tema na Tech·Ed 2007 u Barseloni biće upravo PowerShell. Informacija ima toliko da čovek ne zna šta pre da pročita, koji skript pre da proba. Odabrane izvore informacija naći ćete u okviru sidebar-a. U vrlo skoroj budućnosti nećete moći administirati Windows sisteme bez znanja PowerShell-a. Ne čekajte finalnu verziju. Preuzmite trenutno aktuelan Windows Powershell 1.0 RC2 (potreban vam je i .NET Framework 2.0, ako ga već nemate instaliran) i zaronite u najbolji shell na svetu. The shell must flow.