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

Hey PowerShell Guy !, How Can I Retrieve All the Values in a Registry Key?

Today's Hey Scripting Guy ! column , How Can I Retrieve All the Values in a Registry Key? , Shows a 38 line VbScript to get the Values in a registry key.

In a PowerShell console it just takes this simple line to do the same :

 get-ItemProperty 'hkcu:\Software\Microsoft\Internet Explorer\Main'

The big difference in this case is that in the VbScript version the script has to handle all the parsing itself, as with the PowerShell command shown above , the parser does all the hard work for us, you can see below as we look at some array Properties in more detail, that the Parser did "understand" them and converted them to for us on-the-fly :

PoSH> (get-ItemProperty 'hkcu:\Software\Microsoft\Internet Explorer\Main').Do404Search
1
0
0
0
PoSH > (get-ItemProperty 'hkcu:\Software\Microsoft\Internet Explorer\Main').Window_Placement | get-member


   TypeName: System.Byte

Name        MemberType Definition
----        ---------- ----------
CompareTo   Method     System.Int32 CompareTo(Object value), System.Int32 CompareTo(Byte value)
Equals      Method     System.Boolean Equals(Object obj), System.Boolean Equals(Byte obj)
GetHashCode Method     System.Int32 GetHashCode()
GetType     Method     System.Type GetType()
GetTypeCode Method     System.TypeCode GetTypeCode()
ToString    Method     System.String ToString(), System.String ToString(String format), System.String ToString(IForm...
    

 And when you are in the right location you can replace the complete Vbscript by 3 Characters in the PowerShell console ;-)

PS HKCU:\Software\Microsoft\Internet Explorer\Main> gp .


Disable Script Debugger            : no
Anchor Underline                   : yes
Cache_Update_Frequency             : Once_Per_Session
Display Inline Images              : yes
Do404Search                        : {1, 0, 0, 0}
Local Page                         : C:\Windows\system32\blank.htm
 

... ...

 

So also when you don't want no stinkin' scripts, PowerShell is the Shell for you ;-)   

Enjoy,

Greetings /\/\o\/\/

 

Posted by MoW | 3 Comments
Filed under: ,

Hey PowerShellGuy!,How Can I Check to See if Two Lines of Text are in a File and, If They Are Not, Append Those Lines to the File?

How Can I Check to See if Two Lines of Text are in a File and, If They Are Not, Append Those Lines to the File?

Translation to PowerShell of a  Hey, Scripting Guy! column that shows you how to check a text file for specific lines containing double quote marks and add those lines if it they don't exist.

$l = 'pref("general.config.obscure_value", 0);',
     'pref("general.config.filename", "mozilla.cfg");'

$f = @(get-content all.js)
$l |% {if (-not($f -contains $_)) {$f += $_}}
set-content all.js $f

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: ,

Hey PowerShell Guy !,How Can I Separate The Month From the Year in a Date String Like 122007?

How Can I Separate The Month From the Year in a Date String Like 122007?

[datetime]::ParseExact(122007,'Myyyy',$null) | ft Month,Year

You can see you can use ParseExact to convert a custom format to d dateTime OBject from there it is simple of course

PS> [datetime]::ParseExact(122007,'Myyyy',$null)

zaterdag 1 december 2007 0:00:00


PS l> [datetime]::ParseExact(122007,'Myyyy',$null) | fl Month,Year


Month : 12
Year  : 2007
 

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments
Filed under: , ,

Hey PowerShellGuy !, How Can I Determine the Currency Symbol in Use on a Computer?

From the Scripting Son article  : How Can I Determine the Currency Symbol in Use on a Computer? 

3 ways to do the same in PowerShell : 

(gp 'hkcu:\Control panel\International').sCurrency

(get-culture).NumberFormat.CurrencySymbol

 '{0:c}' -f 1

And yes we can do it remote also :

$Computer = 'Mow2008' 

[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser',$computer).OpenSubKey('Control panel\International').GetValue('sCurrency')

Or of course use the registry provider as I show below, only problem in all cases, when you are in the Euro region, as I am,  in Asci there is no euro symbol so you get only a question mark instead (as in the original ;-) )  :

PS HKCU:\Control panel\International> gp . sCurrency

sCurrency
---------
?

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 1 Comments
Filed under: , ,

PowerShell WMI explorer update for PowerShell V2 CTP

I got a question from Dee about using alternate credentials with my PowerShell .

This is not possible in version 1.0 of PowerShell because of a bug in the WMI adapter, hence I removed this from my PowerShell WMI explorer also at that time, but if you are using the PowerShell V2 CTP this will be possible again .

When you doubleClick the Server field in the status you can set the connection options, if you fill in the username in the options (there will be no password field ), when you click the connect button you will get asked for credentials and can connect with different credentials.

Doubleclicking the server field works also in former version and all other connections options can also be set, but you will not get the credential box, you can use this new version (only 2 lines added) also in V1 but connection using alternate credentials will fail anyway.

 As Dee did upgrade to the PowerShell V2CTP for this I posted this quick fix, I will make it more discoverable in a later update.

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 17 Comments
Filed under: ,

Attachment(s): WmiExplorer.ps1

IT HerOlympics update

Tomorrow is the Microsoft IT herolympics event in the Netherlands,

I already mentioned that here that I would do a PowerShell instructor led Lab on this event, but next to this ILL, I will also provide a "PowerShell Unplugged" session, this is a Chalk and Talk session,  meaning a interactive, total free format session where basicly the content will be up to you, In Dutch "Vraag maar raak" 

So if you have a specific Question, are looking for general PowerShell information or are interested in a demo, everything goes in this session (PowerShell related that is, please no politics  ;-) ).

Hope to see you there.

Greetings /\/\o\/\/

 

Posted by MoW | 2 Comments
Filed under: ,

Russian PowerShell livemeeting recording with Xaegr

I was watching the livemeeting from Vasily Gusev (Xaegr) , the download can be found here ( take the left button after your profile information, as google translate did not work on this site it took me a while to find out how to get to the download )

 As Xeagr is one of the most avid Powertab users I know, you can find some PowerTab coverage in this recording, also for example ISA management from PowerShell is shown. I do not understand Russian still this was a nice watch as PowerShell does what esperanto was designed to do ;-) . 

I could not help a grin when I did see this poll  ;-)  

Enjoy, 

Greetings /\/\o\/\/

Posted by MoW | 4 Comments
Attachment(s): poll.PNG

PowerScripting Podcast - Episode 20

Pfff, scripting games 2008 over and all solutions posted , let's rest back and listen to the new PowerScripting Podcast - Episode 20

 

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments
Filed under: ,

Scripting Games 2008 Beginners Windows PowerShell Event 10

And to end the series with solutions, Beginners event 10,

this was a nice one, I started out with a straight loop but to handle 2 or 3 strikes in a row I considered that it might be easier to look back and forwards in the array.

a Pro was that this would make scores per frame / round possible, a Con was that I needed to check for Strikes or spares ( "X" or "\" ) in the lookups also.

 

$arrFrames = 2,5,7,"/",8,1,"X",9,"/",5,3,7,0,4,5,"X",2,0

$score = $i = 0 
$arrFrames |% { 
  if ($_ -is [int]) { 
    $score += $_ 
  } Else { 
    switch ($_) { 
    '/' { 
           $score += (10 - $arrFrames[$i-1]) + (($arrFrames[$i+1]) -replace 'X','10') 
        } 
    'X' { 
           $o1 = ($arrFrames[$i+1]) -replace 'X','10' 
           $o2 = (($arrFrames[$i+2]) -replace 'X','10') -replace '/' , (10 - $o1) 
           $score += 10 + $o1 + $o2 
        } 
    } 
  } 
  $i++ 
};$score 

From IRC chats I think that Jaykul did workout the "loop" for this so it might be nice to compare the solutions when he has his one posted.

b.t.w. you will find "only" 26 solutions in this series as the Sudden death included 2 Quizzes, and the beginner a debug question, and one where I had nothing to add to the given solution.

I hope you enjoyed the games and comparing all different solutions posted, till next year @ the 2009 Games !

 

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 0 Comments

Scripting Games 2008 Beginners Windows PowerShell Event 9

My solution for Event 9 in the beginners competition, as Jaykul already noted here : 2008 Scripting Games - Solution for Advanced Event 2 , when working with ADO in PowerShell it's much better to use .NET to connect to a database as the COM objects shown in the Windows PowerShell, solution from the Scripting guy's.

I used the same code as in last years Scripting Games 2007 Event 8 to connect to the database : Winter Scripting games Part 8 (Last Day) , but use a Select statement with custom columns to generate the new list with water volumes.

PoSH> .\Event9B.ps1                                                                                                     
                                                                                                                        
Customer Volume of Water                                                                                                
-------- ---------------                                                                                                
Jones            2500000                                                                                                
Myer             1500000                                                                                                
Smith            1500000                                                                                                
Kumar            1200000                                                                                                
Chen             1500000                                                                                                
Garcia           1058000                                                                                                
                                                                                                                        
                                                                                                                        
PoSH>                                                                                     

As this is a beginner event I worked it out a bit more verbose this time, and show in this example that you can create the hashtable's for the "Custom Columns" in advance, to make the select command more clear :

# Connect to database 
 
$mdb = "c:\scripts\Pool.mdb" 
$ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$mdb" 
$Conn = new-object Data.OleDb.OleDbConnection($connString) 
$conn.open() 
 
# Open Table 
 
$cmd = new-object Data.OleDb.OleDbCommand("select * from SwimmingPool",$Conn) 
$da = new-object Data.OleDb.OleDbDataAdapter($cmd) 
$dt = new-object Data.dataTable  
[void]$da.fill($dt) 
 
# Create a custom column for volume calculations 
 
$Volume = @{ 
    label='Volume of Water' 
    expression = { 
        if ($_.Slope -eq $false) { 
            $_.Length * $_.Width * $_.Depth * 1000 
        } else { 
            $_.Length * $_.Width * (($_.SEnd + $_.SStart) / 2) * 1000 
        } 
    } 
} 
 
# use custom Volume column in the select command : 
 
$dt | ft -a Customer,$volume 

You can see that we can just use the variable $volume containing our pre-created HashTable with the formulas in the Format-Table (FT) command.

Enjoy,

Greetings /\/\o\/\/ 

Posted by MoW | 2 Comments

Scripting Games 2008 Advanced Windows PowerShell Event 9

My solution for event 9 :

 (gc c:\scripts\alice.txt |% {$_.split()}|% {$_[-1..(-$_.length)]-join ''})-join ' '

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 2 Comments

Scripting Games 2008 Advanced Windows PowerShell Event 10

My Windows PowerShell solution for event 10 is posted on the scriptcenter.

By accident ( I did send a "preview" version to confuse the scripting guys check if format was right),  it was not the latest version that got posted, I made some small changes after :

*update* the article on the scriptcenter is now also updated to include the changes mentioned below,   

* BugFix * only the first ace was checked for 1 or 11

Function get-Value ($cards){

   $aces = $val = 0
   $cards |% {
       if ($_.card[1] -match '[0JQK]') {$val += 10}
       if ($_.card[1] -match '\d') {$val += [int]$_.card[1].toString()}
       if ($_.card[1] -match '[A]') {$val += 11;$aces += 1}
   }

   while ($aces -gt 0 ) {if ( $val -gt 21) {$val -= 10};$aces--}
   $val  
}

* Addition * and I added the drawing of a facedown card :

Function PaintFaceDownCard ($x,$y){
  ($y)..($y + 6) |% {ColorLine $x $_ 6 'Blue'}
  WriteLine $x ($y + 2) " /\/\ " 'white' 'Blue'
  WriteLine $x ($y + 3) "  ()  " 'white' 'Blue'
  WriteLine $x ($y + 4) " \/\/ " 'white' 'Blue'
}

As you could see in the teaser here : The Scripting Games have started and some teasers

The complete version of the blackJack function, including these changes,  I will attach to this post.

Enjoy,

Greetings /\/\o\/\/

Posted by MoW | 2 Comments
Attachment(s): event10.ps1

MTC Technology Briefing for February 29, 2008: What's Up With PowerShell

3 videos of a "roundtable" podcast,featuring PowerShell

MTC Technology Briefing for February 29, 2008: What's Up With PowerShell

Enjoy,

Greetings /\/\o\/\/

 

Posted by MoW | 0 Comments
Filed under: ,

Scripting Games 2008 Sudden Death Challenge Event 9

As the Scripting Guys note here Event 9 Solution , this was a simple event, biggest part of the code is the filename.

(gc c:\scripts\Symbols.txt) -replace '[^\w\s]|_',''
Only issue I had is as I use \w (word characters) and this also included the underscores I had to remove them also with an OR in the regex.
 
*Update*  I did think just after posting, that it could even be shorter, as we replace by an empty string we can just leave it out completly another 3 chars less :
(gc c:\scripts\Symbols.txt) -replace '[^\w\s]|_'

The 2008 Winter Scripting Games
        without spaces back to 46 chars :
 
"(gc c:\scripts\Symbols.txt)-replace'[^\w\s]|_'".length
46
 
Enjoy,
Greetings /\/\o\/\/  
Posted by MoW | 0 Comments

Hey, PowerShell Guy, how to translate a Unix timestamp to a local time ?

This time not a translation from a Hey scriptingguy article, but a question that just came up in the #powerShell IRC channel,

how to convert a Unix timestamp to a local datetime ?

 A Unix Timestamp is expressed in seconds since 1 January 1970 in UTC time, this function will convert the unix timestamp to a UTC time first, and then convert it to a Local time for the current timezone. 

Function get-Unixdate ($UnixDate) {
    [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($UnixDate))
}

And now you can easy translate Unix timestamps like this :


PS C:\scripts> get-Unixdate 1204062874

Tuesday, February 26, 2008 10:54:34 PM

I did not make a -UTC parameter but if you want you can get back to UTC time like this ;-)

PS C:\scripts> (get-Unixdate 1204062874).ToUniversalTime()

Tuesday, February 26, 2008 9:54:34 PM

Enjoy,

Greetings /\/\o\/\/

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