/\/\o\/\/ PowerShelled

This blog has moved to http://ThePowerShellGuy.com Greetings /\/\o\/\/
$AtomFeed = ("Atom.xml")
$PreviousItems = (" Moving to ThePowerShellGuy.com "," PowerShell Code formatting test for my new Blog "," PowerShell Code formatting test for my new Blog "," PowerShell Community Extensions V1.0 "," PowerShell : Access remote eventlogs "," Windows PowerShell Scripting Sweepstakes! "," PowerShell : making Custum Enums "," TechNet Webcast: An Overview of Windows PowerShell "," "Windows PowerShell: TFM" goes "Gold" "," PowerShell : Advanced renaming of files "," ")

Friday, October 20, 2006

 


Windows PowerShell Week on ScriptCenter



On the scriptcenter on Technet, you can find information about the Windows PowerShell Week

by the Scripting Guy , a series of webcasts about PowerShell, to be held November 6-10.

 

Don't miss it !

 

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




 0 comments

Thursday, October 19, 2006

 


PowerShell : How Can I Split a String Only on Specific Instances of a Character?



Hey PowerShell Guy : How Can I Split a String Only on Specific Instances of a Character?

 

PoSH>[regex]::Split("aaa&bbb&ccc&aamp;ddd","&(?!amp)")
aaa
bbb&ccc
aamp;ddd

 

 

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 0 comments
 


PowerShell : How Can I Tell Whether a Number is Even or Odd?



Hey PowerShell Guy : How Can I Tell Whether a Number is Even or Odd?

Function check-even ($num) {[bool]!($num%2)}

 

PoSH>check-even 12
True
PoSH>check-even 13
False

 

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 0 comments
 


PowerShell : 99-bottles-of-beer



I came at this page : 99-bottles-of-beer.net ,

I could not resist making and submitting a PowerShell example to it.
I came to this example :

# 99-bottles-of-beer

99..1 |% {("{0} bottle{1} of beer on the wall, {0} bottle{1} of beer.
Take one down and pass it around, {2} bottle{3} of beer on the wall.`n" -f 
$_,$(if ($_ -ne 1){"s"}),($_ -1),$(if ($_ -ne 2){"s"})).replace(' 0',' No more')}


Note, this sample does handle the bottle(s) and 0 = No More, to keep it at least a bit of a chalenge in PowerShell ;-).

Enjoy,

Greetings, /\/\o\/\/
Tags : Monad PowerShell


posted by /\/\o\/\/
 4 comments

Wednesday, October 18, 2006

 


PowerShell : Tabcompletion Part 5



I realy added a lot on my TabCompletion :


this function realy makes PowerShell fly for me :

***

*Edit* I made beter version of this script on my new
blog :
The PowerShell Guy ( http://ThePowerShellGuy.com )

As it comes with an installer its much more easy to
setup,
and it uses one database for all data, it works mostly the
same as this one

Just download the PowerTab.ZIP file from the overview page here :

http://thepowershellguy.com/blogs/posh/pages/powertab.aspx

run PowetTabSetup.Ps1 and you are ready to go

***

I will Post my current TabCompletion below, I contains a lot of additions I realy like and the GUI selecting of items in a list I think is handy also as





Some of the additions in this version might be to specific, could be constructed better or are not consistent, but this version is my own current version as it has grown I and might need some cleaning up, but I posted this version for trying out and to tweak it to your need or to get some ideas and to get you started on Custom tab completion, or just use it as is .


As I think*Note* this script is also on Codeplex in : PowerShell Utility scipts as my last version this works as is.


For this version to work you need some preparement as it needs some utility scripts and a XML file to work, the code to make the XML file is needed only once, the loading of it needs to be done every time a new shell is started, so it is best placed in your profile: (for testing if you past in all of the codeblocks your also ready to go),


Utility Functions (to be called in profile)


# Custom Tab Completion Helper Functions

Function add-tabCompletion ([string]$filter,[string]$Text,[string]$type){
$global:dsTabCompletion.Tables['CustomTabExpansion'].Rows.Add($filter,$text,$type)
}

Function Save-tabCompletion {
$global:dsTabCompletion.WriteXml("$PSHome\TabCompletion.xml")
}

Function Load-tabCompletion {
$global:dsTabCompletion = new-object data.dataset
$global:dsTabCompletion.ReadXml("$PSHome\TabCompletion.xml")
}

Function Get-tabCompletion {
$global:dsTabCompletion.tables['CustomTabExpansion']
}

Function New-tabCompletion {
$global:dsTabCompletion = new-object data.dataset

$global:dtCustomTabExpansion = new-Object data.datatable
[VOID]($global:dtCustomTabExpansion.Columns.add('Filter',[string]))
[VOID]($global:dtCustomTabExpansion.Columns.add('Text',[string]))
[VOID]($global:dtCustomTabExpansion.Columns.add('Type',[string]))
$global:dtCustomTabExpansion.tablename = 'CustomTabExpansion'
$global:dsTabCompletion.Tables.Add($global:dtCustomTabExpansion)
}

Function find-tabCompletion ([string]$filter) {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("filter like '$filter'") % {$_}
}

Function Refresh-TabCompletionAlias {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("Type = 'Alias'") % {$global:dsTabCompletion.Tables['CustomTabExpansion'].rows.remove($_)}
Get-Alias % {add-tabCompletion $_.name $_.Definition 'Alias'}
}

Function Refresh-TabCompletionFunction {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("Type = 'Function'") % {$global:dsTabCompletion.Tables['CustomTabExpansion'].rows.remove($_)}
Get-Command -commandType "Function"% {add-tabCompletion $_.name $_.name $_.CommandType}
}


Then you need to build the Tab Completion DataBase for first use.


Build XML file (one time only needed)


# Create Initial Tab-Completion DataBase

New-tabCompletion

Get-Alias % {add-tabCompletion $_.name $_.Definition 'Alias'}

Get-Command -commandType "Function, Filter, Cmdlet"% {add-tabCompletion $_.name $_.name $_.CommandType}

add-tabCompletion '%' ' foreach-object {}' 'Custom'
add-tabCompletion '?' ' Where-object {}' 'Custom'

Save-tabCompletion

Load-tabCompletion


as you can see here, after we did initial fill it we can use the functions to customize it and then save it again,.I also added 2 functions to update the Alias and Function list.


Also as te Tabcompletion function uses a GUI you need to load this help function also :


Out-DataGridView needed loaded for tabcompletion (profile)

*edit* needed formas library :

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")


# Function out-datagridView
#
# shows piplineinput in a GUI using a datagridView
# and returns the given field on double-Click or Enter
#
# /\/\o\/\/ 2006
# http:mow001.blogspot.com

Function out-dataGridView ([String]$ReturnField){

# Make DataTable from Input

$dt = new Data.datatable
$First = $true
foreach ($item in $input){
$DR = $DT.NewRow()
$Item.PsObject.get_properties() foreach {
If ($first) {
$Col = new-object Data.DataColumn
$Col.ColumnName = $_.Name.ToString()
$DT.Columns.Add($Col) }
if ($_.value -eq $null) {
$DR.Item($_.Name) = "[empty]"
}
ElseIf ($_.IsArray) {
$DR.Item($_.Name) =[string]::Join($_.value ,";")
}
Else {
$DR.Item($_.Name) = $_.value
}
}
$DT.Rows.Add($DR)
$First = $false
}

# show Datatable in Form

$form = new-object Windows.Forms.form
$form.Size = new-object System.Drawing.Size @(1000,600)
$DG = new-object windows.forms.DataGridView
$DG.DataSource = $DT.psObject.baseobject
$DG.Dock = [System.Windows.Forms.DockStyle]::Fill
$dg.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize
$dg.SelectionMode = 'FullRowSelect'
$dg.add_DoubleClick({
$script:ret = $this.SelectedRows % {$_.DataboundItem["$ReturnField"]}
$form.Close()
})

$form.text = "$($myinvocation.line)"
$form.KeyPreview = $true
$form.Add_KeyDown({
if ($_.KeyCode -eq 'Enter') {
$script:ret = $DG.SelectedRows % {$_.DataboundItem["$ReturnField"]}
$form.Close()
}
ElseIf ($_.KeyCode -eq 'Escape'){
$form.Close()
}
})

$form.Controls.Add($DG)
$Form.Add_Shown({$form.Activate();$dg.AutoResizeColumns()})
$script:ret = $null
[void]$form.showdialog()
$script:ret
}

And after that ofcourse load the TabCompletion replacement : TabCompletion Function (load in profile)


# TabExpansion.ps1
# RC2 Version 0.5
# Replacement of default TabExpansion function
# /\/\o\/\/ 2006
# www.ThePowerShellGuy.com


#$global:dtAssemblies = $null
#$global:dtWmiClasses = $null

function TabExpansion {

# This is the default function that gets called for tab expansion.
# Edited by /\/\o\/\/ from the original to handle :
# - Cached tab completion on types (janel / mow).
# - Methods and properties of types
# - shows get_ methods
# - MultiLevel variable Tab Completion
# - Bracet Removal
# Edited by DBMwS: Added Progressbar and Scoped variable name expansion
# /\/\o\/\/ added WMI Tab completion win32_[tab]/cim_[tab]/msft_[tab]
# expansion on aliases / custom aliases
# simple () expansion
# history expansion
# GUI Expansion

param($line, $lastWord)

$_Method = [Management.Automation.PSMemberTypes] 'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
$_ScopeNames = @("global", "local", "script", "private")

switch -regex ($line) {
# Handle property and method expansion on simple () blocks( added /\/\o\/\/)...
'^\((.+)\)\.(.*)' {
$val = "($($matches[1]))"
invoke-expression "Get-Member -inputobject $val" ? {$_.name -like "$($matches[2])*"} foreach {
if ($_.MemberType -band $_method)
{

# Return a method...
$lastword.Substring(0,$lastword.LastIndexOf('.')) + '.' + $_.name + '('
}
else {
# Return a property...
$lastword.Substring(0,$lastword.LastIndexOf('.')) + '.' + $_.name
}
}
break;
}
}

switch -regex ($lastWord) {

# GUI Shortcuts

'w_(.*)' {$global:dtWmiClasses.Select("name like 'win32_$($matches[1])%'","name") out-dataGridView name}
'A_(.*)' {$global:dtAssemblies.Select("name like '%$($matches[1])%'","name") out-dataGridView name}
'f_' {ls function: select name out-dataGridView name}
'd_' {ls select Mode,LastWriteTime,Length,Name,fullname out-dataGridView fullname}
'e_' {"@{e={};Name=}"}
'h_(.*)' {Get-History -count 900 ? {$_.CommandLine -like "$($matches[1])*"} foreach-object {$_.CommandLine}}
'g_' {Get-History -Count 100 out-dataGridView Commandline}
'c_(.*)' {$global:dsTabCompletion.Tables['CustomTabExpansion'].select("filter like '$($matches[1])%'","text") out-dataGridView text}

# WMI completion

'(win32_.*cim_.*MSFT_.*)' {
# First time fill list

if (!($global:dtWmiClasses)) {

$global:dtWmiClasses = new data.datatable
[VOID]($global:dtWmiClasses.Columns.add('name',[string]))
[VOID]($global:dtWmiClasses.Columns.add('Description',[string]))

$WmiClass = [WmiClass]''

# Set Enumeration Options

$opt = new-object system.management.EnumerationOptions
$opt.EnumerateDeep = $True
$opt.UseAmendedQualifiers = $true

$i = 0 ; write-progress "Adding WMI Classes" "$i"
$WmiClass.psBase.GetSubclasses($opt) foreach {
$i++ ; if ($i%10 -eq 0) {write-progress "Adding WMI Classes" "$i"}
[void]$global:dtWmiClasses.rows.add($_.name,($_.psbase.Qualifiers ? {$_.Name -eq 'description'} % {$_.Value}))
}
write-progress "Adding WMI Classes" "$i" -Completed
}


$global:dtWmiClasses.select("name like '$($matches[1])%'") % {$_.name}
break;
}

# Handle property and method expansion on simple () blocks( added /\/\o\/\/)...
'^\((.+)\)\.(.*)' {
$val = "($($matches[1]))"
invoke-expression "Get-Member -inputobject $val" ? {$_.name -like "$($matches[2])*"} foreach {
if ($_.MemberType -band $_method)
{

# Return a method...
$val + '.' + $_.name + '('
}
else {
# Return a property...
$val + '.' + $_.name
}
}
break;
}
# Handle property and method expansion (MultiLevel added /\/\o\/\/)...
'\$(.+)\.(.*)' {
$variableName = $matches[1]
$val = '$' + $matches[1]
$level = $matches[2].split('.').count
if ($level -gt 1) {
$ofs = '.';$val = '$' + $variableName + ".$($matches[2].split('.')[0..($level -2)])"
}
$pat = $matches[2].split('.')[($level -1)] + '*'
# /\/\o\/\/ removed : -and $n -notmatch '^[ge]et_'
# to get get_ methods on WMI and AD objects
invoke-expression "Get-Member -inputobject $val" where {$n = $_.name; $n -like $pat } foreach {
if ($_.MemberType -band $_method)
{
# Return a method...
$val + '.' + $_.name + '('
}
else {
# Return a property...
$val + '.' + $_.name
}
}
break;
}

# Remove Brackets from typename (/\/\o\/\/)
'(\[.*\])=(\w*)' {
"new-Object $($matches[1].replace('[','').replace(']',''))"
break;
}

# Handle Static methods of Types (/\/\o\/\/)..
'(\[.*\])::(\w*)' {
invoke-expression "$($matches[1]) gm -static" where {$_.name -like "$($matches[2])*"} % {
if ($_.MemberType -band $_Method) {
"$($matches[1])::$($_.name)" + '('
} Else {
"$($matches[1])::$($_.name)"
}
}
break;
}

# Handle methods of Types (/\/\o\/\/)..
'^(\[.*\]).(\w*)' {
invoke-expression "$($matches[1]) gm" where {$_.name -like "$($matches[2])*"} % {
if ($_.MemberType -band $_Method) {
"$($matches[1]).$($_.name)" + '('
} Else {
"$($matches[1]).$($_.name)"
}
}
break;
}



# Cache and Handle namespace and TypeNames (/\/\o\/\/) ..
'^\[(.*)' {
$matched = $matches[1]
# only the first time Fill a DataTable with Typenames,namespaces and dotCount (level)
if (!($global:dtAssemblies)) {
$global:dtAssemblies = New-Object System.Data.Datatable
[VOID]($global:dtAssemblies.Columns.add('name',[string]))
[VOID]($global:dtAssemblies.Columns.add('DC',[int]))
[VOID]($global:dtAssemblies.Columns.add('NS',[string]))
$assemblies = [appdomain]::CurrentDomain.getassemblies()
[void] ($assemblies % {$i = 0} {
$i++;
[int]$assemblyProgress = ($i * 100) / $assemblies.Length
write-progress "Adding Assembly $($_.getName().name):" "$assemblyProgress" -perc $assemblyProgress
$types = $_.GetTypes() ? {$_.IsPublic -eq $true}
$types % {$j = 0} {
$j++;
if (($j % 200) -eq 0) {
[int]$typeProgress = ($j * 100) / $types.Length
write-progress "Adding types percent complete :" "$typeProgress" -perc $typeProgress -id 1
}

$dc = $_.fullName.split(".").count - 1
$ns = $_.namespace
$global:dtAssemblies.rows.add("$_",$dc,$ns)
}

# Stubs added
$dtAssemblies.rows.add('windows stub',2,'System.Windows')
write-progress "Adding types percent complete :" "100" -perc 100 -id 1
})
}

# actual tab completion
$dots = $matches[1].split(".").count - 1
switch ($dots) {
0 {"[System","[Microsoft","[IronPython"}
Default {
$res = @()
$res += $global:dtAssemblies.select("ns like '$($matched)%' and dc = $($dots + 1)")
select -uni ns % {"[$($_.ns)"};
$res += $global:dtAssemblies.select("name like '$($matched)%' and dc = $dots") % {"[$($_.name)]"}
$res
}
}
break;
}








# Handle expansions for both "Scope Variable Name" and "Type Variable Names" (DbmwS)
'(.*^\$)(\w+):(\w*)$' {
$type = $matches[2]; # function, variable, etc.. that are not scopes
$prefix = $matches[1] + $type; # $ + function
$typeName = $matches[3]; # e.g. in '$function:C', value will be 'C'

if ($_ScopeNames -contains $type) {
# Scope Variable Name Expansion
foreach ($scopeVariable in
(Get-Variable "$($typeName)*" -Scope $type Sort-Object name)) {
$prefix + ":" + $scopeVariable.Name
}
} else {
# Type name expansion($function:, $variable, $env: ,etc)
foreach ($t in (Get-ChildItem ($type + ":" + $typeName + '*') Sort-Object name)) {
$prefix + ":" + $t.Name
}
}
break;
}

# Handle variable name expansion (original)...
'(.*^\$)(\w+)$' {
$prefix = $matches[1]
$varName = $matches[2]
foreach ($v in Get-Childitem ('variable:' + $varName + '*')) {
$prefix + $v.name
}
break;
}

# Do completion on parameters (original) ...
'^-([\w0-9]*)' {
$pat = $matches[1] + '*'

# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesnt handle strings however.
$cmdlet = [regex]::Split($line, '[;]')[-1]

# Extract the trailing unclosed block
if ($cmdlet -match '\{([^\{\}]*)$') {
$cmdlet = $matches[1]
}

# Extract the longest unclosed parenthetical expression...
if ($cmdlet -match '\(([^()]*)$') {
$cmdlet = $matches[1]
}

# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you dont get leading empty elements.
$cmdlet = $cmdlet.Trim().Split()[0]

# now get the info object for it...
$cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet)[0]

# loop resolving aliases...
while ($cmdlet.CommandType -eq 'alias') {
$cmdlet = @(Get-Command -type 'cmdlet,alias' $cmdlet.Definition)[0]
}

# expand the parameter sets and emit the matching elements
foreach ($n in $cmdlet.ParameterSets Select-Object -expand parameters) {
$n = $n.name
if ($n -like $pat) { '-' + $n }
}
break;
}

# Custom additions

'(.*)' {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("filter like '$($matches[1])'") % {$_.text} # AND type = 'Alias'"
}
'(.*)%' {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("filter like '$($matches[1])%'","text") % {$_.text}
}
'(.*-.*)' {
$global:dsTabCompletion.Tables['CustomTabExpansion'].select("filter like '$($matches[1])%'","text") % {$_.text}
}

} # EO switch
}



now you are free to edit your tabcompletion
try this now



# Alias

PoSH> gwmi[tab]
PoSH> Get-WmiObject win32_sh[tab]
Posh> Get-WmiObject Win32_Share

# Function + CmdLet (on -)

PoSH> get-t[tab]
PoSH>Get-tabCompletion

# Function + CmdLet (on %)

PoSH>ref%[tab]
PoSH>Refresh-TabCompletionAlias

# GUI tabcompletion :

PoSH>w_sh[tab]
PoSH>f_[tab]
PoSH>w_ [tab]

# Custom

PoSH>ls %[tab]
PoSH>ls foreach-object {}

# () resolving

PoSH>(LS).[tab]

PoSH>(gwmi win32_share).[tab]



Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 2 comments

Thursday, October 12, 2006

 


PowerShell : Calendar Function (GUI)



I often have a need for a quick Calendar  to look up some dates or Week numbers ,

you can double click the clock in the systray to do a quick lookup (I often used it for that) but you need to be an Admin to do so, so it is not available on my own workstation using my normal account , also it shows no week numbers and I often need those  also

So this trick did help me out on several occasions, but still this is not a really ideal solution.

Hence I made this small PowerShell function that does show a Calendar with WeekNumbers in a Form that closes again on hitting [Enter],  that I load in my profile and alias to Cal to keep it ready for a quick lookup of some dates, as you will be surprised how often it comes handy.

(note the dot-space to load in global scope, and the loading forms library in profile (needed for function) 

to test you can also just past the code into the PowerShell console to load the function, and start using the function:

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

. c:\PowerShell\Functions\GetCalendar.ps1 

and here is the script  : (formatted by the html export function from PowerShell Analyzer a great PowerShell editor, if you not know it yet be sure to try it out)

# Function Get-Calendar
#
Shows a calendar with WeekNumbers in a Form
#
/\/\o\/\/ 2006
#
www.ThePowerShellGuy.com

Function
get-Calendar {

$form = new-object Windows.Forms.Form
$form.text = "Calendar"
$form.Size = new-object Drawing.Size @(656,639)

# Make "Hidden" SelectButton to handle Enter Key

$btnSelect = new-object System.Windows.Forms.Button
$btnSelect.Size = "1,1"
$btnSelect.add_Click({
$form.close()
})
$form.Controls.Add($btnSelect )
$form.AcceptButton = $btnSelect

# Add Calendar

$cal = new-object System.Windows.Forms.MonthCalendar
$cal.ShowWeekNumbers = $true
$cal.MaxSelectionCount = 356
$cal.Dock = 'Fill'
$form.Controls.Add($cal)

# Show Form

$Form.Add_Shown({$form.Activate()})
[void]
$form.showdialog()

# Return Start and end date

return $cal.SelectionRange
}

set-alias cal get-Calendar

 



* Update *As the PSA formatting if the Script gives formatting and pasting problems, I'm looking into this, I also will place the script here in the "old" formatting

# Function Get-Calendar
# Shows a calendar with WeekNumbers in a Form
# /\/\o\/\/ 2006
# www.ThePowerShellGuy.com

Function get-Calendar { 

  $form = new-object Windows.Forms.Form 
  $form.text = "Calendar" 
  $form.Size = new-object Drawing.Size @(656,639

  # Make "Hidden" SelectButton to handle Enter Key

  $btnSelect = new-object System.Windows.Forms.Button
  $btnSelect.Size = "1,1"
  $btnSelect.add_Click({ 
    $form.close() 
  }) 
  $form.Controls.Add($btnSelect ) 
  $form.AcceptButton =  $btnSelect

  # Add Calendar 

  $cal = new-object System.Windows.Forms.MonthCalendar 
  $cal.ShowWeekNumbers = $true 
  $cal.MaxSelectionCount = 356
  $cal.Dock = 'Fill' 
  $form.Controls.Add($cal) 

  # Show Form

  $Form.Add_Shown({$form.Activate()})  
  [void]$form.showdialog() 

  # Return Start and end date 

  return $cal.SelectionRange


set-alias cal get-Calendar


So if you are need a quick calendar, you just need ro do a quick cal[enter], in the PowerShell console ..and there you go :


 



PoSH>cal

End Start
--- -----
10/12/2006 12:00:00 AM 10/12/2006 12:00:00 AM


 


 and you can select a timeframe in the calendar to return.


I added a "hidden" button (size 1 by 1) , to handle the [enter] key to close the Form and return the start and end date, to make the calendar more handy to use, as a quick enter will close the form after use and you do not need to use  X to close the form, and I still can use fill on the Calendar control. also you can select a range of days in the Calendar and the function will return the Start and the End date of that period to the PowerShell console when it is closed.


 



PoSH>$vacation = cal
PoSH>$vacation.end

Sunday, November 05, 2006 12:00:00 AM

PoSH>$vacation.start

Saturday, October 14, 2006 12:00:00 AM

PoSH>$vacation.end - $vacation.start

Days : 22
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 19008000000000
TotalDays : 22
TotalHours : 528
TotalMinutes : 31680
TotalSeconds : 1900800
TotalMilliseconds : 1900800000



Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell







posted by /\/\o\/\/
 8 comments

Wednesday, October 11, 2006

 


PowerShell : WMI Support in RC2 : Privileges and connection settings (Series part 3)



  For some actions in WMI you need to enable privileges , for example for the SetDateTime method of win32_operatingsystem,

and how you can use the GUI again to edit settings, and change Classes , and also see posible values of properties also with the searcher you can do the same as we did see in (" PowerShell : WMI Support in RC2 (Series part 2) "," PowerShell : WMI Support in RC2 (Series part 1) ","

[WmiSearcher]$roq | opg

as I did get a question by G/\/\E  on the second part of this series, I did this quick post about this *Remark* I did not see the blog item he did make about this, about this when I started this

to see about that strange timeformat see second example, More information about calling methods in next post

PoSH>$win32_Operatingsystem = gwmi win32_Operatingsystem
PoSH>$win32_Operatingsystem.SetDateTime("20061010234615.000000+120")
Exception calling "SetDateTime" : "Access denied "
At line:1 char:35
+ $win32_Operatingsystem.SetDateTime( <<<< "20061010234615.000000+120")
PoSH>
$win32_Operatingsystem.psbase.Scope

IsConnected Options Path
----------- ------- ----
True System.Management.ConnectionOptions \\localhost\root\cimv2

PoSH>$win32_Operatingsystem.psbase.Scope.options

Locale :
Username :
Password :
Authority :
Impersonation : Impersonate
Authentication : Unchanged
EnablePrivileges : False
Context : {}
Timeout : 10675199.02:48:05.4775807

 

 

PoSH>$win32_Operatingsystem.psbase.Scope.options.EnablePrivileges = $true
PoSH>$win32_Operatingsystem.SetDateTime("20061010234615.000000+120")

__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0

Here you can see that you can also use the out-PropertyGrid to Edit and test those Settings as I showed in former posts about queries (Change properties and query will be automatically changed), *Note* you need to change to WmiClass eg to win32_share and back Note the changing of paths in the GUI, to reconnect and enable the privileges, note that you have a complete WMI browsel like this,

also I show the use of a added utility property added to a WMI class in RC2  to get a WMI dateTime, a bit more about methods in next post

PoSH>$win32_Operatingsystem = gwmi win32_Operatingsystem

PoSH>$win32_Operatingsystem.ConvertfromDateTime("10/10/2006 23:26:15")
20061010232615.000000+120

 

PoSH>$win32_Operatingsystem.SetDateTime("20061010232615.000000+120")
Exception calling "SetDateTime" : "Access denied "
At line:1 char:35
+ $win32_Operatingsystem.SetDateTime( <<<< "20061010232615.000000+120")

PoSH>$win32_Operatingsystem | opg
Cancel

PoSH>$win32_Operatingsystem | opg
Cancel

 



PoSH>$win32_Operatingsystem.SetDateTime("20061010232615.000000+120")

__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 1 comments

Monday, October 02, 2006

 


PowerShell : WMI Support in RC2 (Series part 2)



In last post PowerShell : WMI Support in RC2 (Series part 1) , I started out translating the first WMI post, about more advanced WMI queries, and the helperObjects ( RelatedObjectQuery and RelationshipQuery ) you could use as helpers for creating this kind of Queries .

Also I did show that you could use out-PropertyGrid to Edit and test those queries (Change properties and query will be automatically changed)

This is a great help in doing that advanced queries, but might be a step to much if you are just starting out with PowerShell and/or WMI

In this post I take a step back, and will first  cover the different ways to get to just one WMI object / Class, and go on from the Lanman example in last post.

After that I will cover Next post I did on my blog also in October last year the WMI viewer script WMI viewer script for MSH (GUI) .

As I already made a out-DataGrid function here : PowerShell out-DataGrid update and more Dataset utilities that can take all sorts of input and show it in a GUI Form with a DataGrid that is a more generic solution, and can also combine datasources , (See Screendumps here : MSH GUI Viewer for Dataset Example ,) , Hence we do not really need it anymore, and also I could replace the whole first Part with "gwmi $WmiClass | " 

PS C:\PowerShell> gwmi win32_service | out-DataGrid
Cancel
PS C:\PowerShell> gwmi win32_service | select [a-z] | out-DataGrid
Cancel

but I did still update the script and did put it at the end of this post as it uses the next change in RC2 getting to a static Class, and can take it as input, getting to static classes is much easier in RC2 but more about that in next post.

(we going to use that also in next post about using methods in RC2)

take a note about how I changed the input Parameter to [WmiClass] so it gets more flexible, it will not only take a string but anything it can translate to an WmiClass, so you can also pass it an (Variable with) WMI Class as input, also see I use a Class to get Instances from them not needed in this example but in next post I will show some more examples about using this  :

PS C:\PowerShell> get-WMIDatagrid win32_share
Cancel
PS C:\PowerShell> [WmiClass]'win32_share'

Win32_Share

PS C:\PowerShell> $WmiClass = [WmiClass]'win32_share'
PS C:\PowerShell> get-WMIDatagrid $WmiClass
Cancel
PS C:\PowerShell>

For More information about working with DataSets and Tables see my CSV series :

working with CSV files in MSH (part one) 

/\/\o\/\/ PowerShelled: working with CSV files in MSH (part two)

/\/\o\/\/ PowerShelled: more Monad scripts, and a bit more CSV

 

And for using datasets with other datasources see these posts :

Access :
scripting games Last Day MSH answers for event 7 and 8
Excel :
Using ADO to get data from Excel to Dataset in Monad.
SQL (SQL Provider)
Getting and Working With SQL Server data in Monad

 

But to go on with WMI here are some way's to to get to an instance of a WMI class, I will show how to use get-WmiObject and also the new ways in PowerShell RC2 using [WMI] (name or Path) or [WmiSearcher] use a WQL query.

As last example I show using [WmiClass] like in the script, as I can only filter client site this is not a good way to do this, but I added it as an first example of the [WmiClass] (see also how it is used in the Updated script, to make the input more flexible and note other ways to do it)more in next post.  

 

# Use get-WmiObject

PS C:\PowerShell> get-wmiObject win32_service -filter "Name = 'lanmanserver'"

ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK

# a More Short way

PS C:\PowerShell> gwmi win32_service -f "Name = 'lanmanserver'"

ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK

# Using [WMI] and a Path

PS C:\PowerShell> [WMI]'\\.\root\cimv2:Win32_Service.Name="lanmanserver"'

ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK

# only the Name of the Class

PS C:\PowerShell> [WMI]'Win32_Service.Name="lanmanserver"'

ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK

# Using a [WMISearcher] for using a WQL query to get to the Object

PS C:\PowerShell> [wmiSearcher]"Select * from Win32_Service where Name='lanmanserver'"

Scope : System.Management.ManagementScope
Query : System.Management.ObjectQuery
Options : System.Management.EnumerationOptions
Site :
Container :

PS C:\PowerShell> ([wmiSearcher]"Select * from Win32_Service where Name='lanmanserver'").get()

ExitCode : 0
Name : lanmanserver
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

# Note that you can use get-Services in PowerShell but this uses .NET not WMI

PS C:\PowerShell> get-service lanmanserver

Status Name DisplayName
------ ---- -----------
Running lanmanserver Server

PS C:\PowerShell> get-service lanmanserver | gm

TypeName: System.ServiceProcess.ServiceController

Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = ServiceName

PS C:\PowerShell> [wmiClass]'win32_service'

Win32_Service

# Using WmiClass (filter client site not efficient)

PS C:\PowerShell> $win32_service = [wmiClass]'win32_service'
PS C:\PowerShell> $win32_service.psbase.GetInstances() |? {$_.name -eq 'lanmanserver'}

ExitCode : 0
Name : lanmanserver
ProcessId : 1580
StartMode : Auto
State : Running
Status : OK

You can see that RC2 makes you very flexible, Here the updated script using [wmiClass] directlyin the Parameter set.

for the Rest I only added a couple of PsBases and changed the topmost hack .

 

# WmiDatagrid.PS1
# Shows Instances of WMIClass in Datagrid 
# PowerShell RC2 Update
#
# /\/\o\/\/ 2006 
# http://www.ThePowerShellGuy.com

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms"

function get-WMIDatagrid { 
  Param ([wmiCLass] $WmiClass = {Throw "No WMIClass given"}) 

  $MOC = $WmiClass.PSBase.GetInstances() 

  trap{"Class Not found";break

  $DT =  new-object  System.Data.DataTable 
  $DT.TableName = $wmiClass 

  $i = 0 
  $MOC | foreach { 
    $MO = $_ 

    # Make a DataRow 
    $DR = $DT.NewRow() 

    $MO.PSBase.properties | foreach { 

      $prop = $_ 

      If ($i -eq 0)  { 
        # Only On First Row make The Headers 

        $Col =  new-object System.Data.DataColumn 
        $Col.ColumnName = $prop.Name.ToString() 
        $prop.PSBase.get_Qualifiers() | foreach { 
          If ($_.Name.ToLower() -eq "key") { 
            $Col.ColumnName = $Col.ColumnName + "*" 
          } 
        } 
        $DT.Columns.Add($Col)  
      } 

      #fill dataRow  

      if ($prop.value -eq $null) { 
        $DR.Item($prop.Name) = "[empty]" 
      } 
      ElseIf ($prop.IsArray) { 
        $DR.Item($prop.Name) =[string]::Join($prop.value ,";"
      } 
      Else { 
        $DR.Item($prop.Name) = $prop.value 
        #Item is Key try again with * 
        trap{$DR.Item("$($prop.Name)*") = $prop.Value.tostring();continue
      } 
    } 
    # Add the row to the DataTable 
    $DT.Rows.Add($DR) 
    $i += 1 
  } 
    
  $form = new-object "System.Windows.Forms.Form" 
  $form.Size = new-object System.Drawing.Size @(800,400
  $DG = new-object "System.windows.forms.DataGrid" 
  $DG.CaptionText = "$wmiClass $($DT.Count)" 
  $DG.AllowSorting = $True 
  $DG.DataSource = $DT 
  $DG.Dock = [System.Windows.Forms.DockStyle]::Fill 

  #show the Form 

  $form.text = "$wmiCLass" 
  $form.Controls.Add($DG) 
  $Form.Add_Shown({$form.Activate()}) 
  $form.showdialog() 


set-alias gwd get-WMIDatagrid 

More very cool RC2 WMI stuff in next part of this series about calling WMI Methods !!, there the real power of the changes made in WMI will show ! 

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 2 comments

Sunday, October 01, 2006

 


PowerShell : WMI Support in RC2 (Series part 1)



 

As the WMI Support in PowerShell as also changed in RC2,

I will start a new WMI series by translating former WMI posts on my blog to PowerShell RC2, and I will show what has changed,

Opposed to what I think about the new Active Directory Support See :  PowerShell RC2 and Active Directory Part 2 ,

In this Case I think the wrapper does add value, here also a bit more PSBase is needed, but the added functional in this case I think is much more as what the ADSI wrapper does and I has much less impact on working interactively  ,

So for now I decided I like it, or working with it and the translating of older WMI post in this series, does bring up some hidden problems,

I will start with the First WMI example I did on my blog (Lets Query WMI from MSH) in the first Month October 2005 about  RelatedObjectQuery 's  in WMI,

as I was just starting then with Monad (Codename for PowerShell at that time), and did go on from a VbScript Example, I did copy the old post and will follow it in RC2  in this re-post and I will translate the scripts inbetween the old text adding comments and changes to it (Italic)., also I will show the use of out-PropertyGrid  PowerShell : out-PropertyGrid  that is very handy for editing the WMI Queries in a GUI Form (load windows forms library first see example).

here is the edited post :

Lets Query WMI from MSH

*Original text*

ls, as I was answering a post in the NG, about a vbscript to get dependent services the (corrected) script looks like this :

Dim UnArgs
Set UnArgs = WScript.Arguments.Unnamed
WScript.Echo UnArgs(0)

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='" & UnArgs(0) & "'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Antecedent" )

for each s in colServiceList
WScript.Echo s.name
next
this is a bit more as the standard WMI get propery, and involves more than 1 WMI-class. I decided to make it in MSH also :. at first I came with this :
Function GetDep {
$mos = (new-object system.management.ManagementObjectSearcher)
$mos.Query = "Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=Antecedent"
$mos.get()
}

 


* Update *


As you can see, if you past this script into the PowerShell RC2 Console it still works  :


 



PS C:\PowerShell> Function GetDep {
>> $mos = (new-object system.management.ManagementObjectSearcher)
>> $mos.Query = "Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=A
ntecedent"
>> $mos.get()
>> }
>>
PS C:\PowerShell> getdep 'lanmanserver'

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK



But in PowerShell RC2 we can use the  [WmiSearcher]  "intrinsic type" (From Release notes) ,  so I did started out testing interacive in the PowerShell Conole 


 



PS C:\PowerShell> [wmiSearcher]("Associators of {Win32_Service.Name='" + $Args[0] + "'} Where AssocClass=Win32_DependentService Role=Antecedent")

Scope : System.Management.ManagementScope
Query : System.Management.ObjectQuery
Options : System.Management.EnumerationOptions
Site :
Container :

PS C:\PowerShell> ([wmiSearcher]"Associators of {Win32_Service.Name='lanmanserver'} Where AssocClass=Win32_DependentService Role=Antecedent").get()

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK


also I would do some things a bit different now, here is the translated script for PowerShell RC2 :


 



# PowerShell RC2 Function to get Services that depent on the given ServiceName

Function Get-DependentService ([String]$ServiceName) {

  $WmiSearcher = [wmiSearcher]"Associators of {Win32_Service.Name='$ServiceName'} Where AssocClass=Win32_DependentService Role=Antecedent"
  $WmiSearcher.get()

}

You can See I changed to a Named Parameter for the service Name to make things more clear, opposed the $Args[0] I did use in the Monad examples , and I did a make use of the Variable handling of PowerShell that will expand in double quoted strings but both where possible at that time also (You can see that I was using a more VbScript way as I was just starting out with PowerShell at that time and still did "think VbScript"  as I was less used to PowerShell) ,


The Difference in RC2 is the [WmiSearcher]  "intrinsic type" , so it is not needed anymore to use new-object system.management.ManagementObjectSearcher to get the .NET object , also the next remark in the Original is Covered in RC2 :


 



PS C:\PowerShell> [WMI]'\\MOWDC001\root\cimv2:Win32_Service.Name="lanmanserver"'

ExitCode : 0
Name : lanmanserver
ProcessId : 876
StartMode : Auto
State : Running
Status : OK


the rest is all still working only you need to use PSBase as with the [adsi] wrapper, but this time the wrapper shows the Methods of the Win32_Share class and we can invoke them directly, we  see  the methods of the WMIclass in the Get-Member and have Tab Completion for them and this is very handy


As we needed to Invoke them in PowerShell before RC2 , and could not see them, so in this case the wrapper has much more added value.


 



PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'") | gm

TypeName: System.Management.ManagementObject#root\cimv2\Win32_Service

Name MemberType Definition
---- ---------- ----------
Change Method System.Management.ManagementBaseObject Change(System.String DisplayName, System...
ChangeStartMode Method System.Management.ManagementBaseObject ChangeStartMode(System.String StartMode)
InterrogateService Method System.Management.ManagementBaseObject InterrogateService()
PauseService Method System.Management.ManagementBaseObject PauseService()
ResumeService Method System.Management.ManagementBaseObject ResumeService()
StartService Method System.Management.ManagementBaseObject StartService()
StopService Method System.Management.ManagementBaseObject StopService()
UserControlService Method System.Management.ManagementBaseObject UserControlService(System.Byte ControlCode)

...

 

PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").PsBase | gm

TypeName: System.Management.Automation.PSMemberSet

Name MemberType Definition
---- ---------- ----------
add_Disposed Method System.Void add_Disposed(EventHandler value)
Clone Method System.Object Clone()
CompareTo Method System.Boolean CompareTo(ManagementBaseObject otherObject, Compariso...
CopyTo Method System.Management.ManagementPath CopyTo(ManagementPath path), System...
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
Delete Method System.Void Delete(), System.Void Delete(DeleteOptions options), Sys...
Dispose Method System.Void Dispose()
Equals Method System.Boolean Equals(Object obj)
Get Method System.Void Get(), System.Void Get(ManagementOperationObserver watcher)
GetHashCode Method System.Int32 GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetMethodParameters Method System.Management.ManagementBaseObject GetMethodParameters(String me...
GetPropertyQualifierValue Method System.Object GetPropertyQualifierValue(String propertyName, String ...
GetPropertyValue Method System.Object GetPropertyValue(String propertyName)
GetQualifierValue Method System.Object GetQualifierValue(String qualifierName)
GetRelated Method System.Management.ManagementObjectCollection GetRelated(), System.Ma...
GetRelationships Method System.Management.ManagementObjectCollection GetRelationships(), Sys...
GetText Method System.String GetText(TextFormat format)
GetType Method System.Type GetType()

...


I will cover the Methods in  more detail in later posts in this Series, for the following examples we need to add  PSBase at some places, for the rest it works the same only we can start the Query we constucted much easier , see next update below following the original text how the use the Query in RC2 , here is how it looks in RC2 with PSbase before the method, but first the example on how the change the original code  :.

 


PS C:\PowerShell> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").PSBase.GetRelated($null,"Win32_DependentService",$null,$null,$null,"Antecedent",$false,$null)

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK


 

*Original text*


(you can not use a Moniker to connect to WMI as in VBscript) But after that I thought .. this may be correct but not realy MSH. Hence, I did look at the get-WMIObject function. first how to get only the wanted Class. the get-WMIObject uses - filter for this :



then how to get the related class


a Get-Method on the Object revealed the GetRelated Property


hence ,


Function GetServiceDeps {($s = get-wmiObject win32_service -filter "Name = '$($args[0])'").GetRelated("win32_service")}



And Ready ..


Much more Clean, shorter and more MSH



but then again .....maybe NOT..... (c) LSL


I did forget the Role-part this does not matter for "lanmanserver" so I did not see it at first but this will give also the relations the service is dependend on.



OK, lets look again at that Method :




MSH G:\Monad> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelated.OverloadDefinitions
System.Management.ManagementObjectCollection GetRelated()
System.Management.ManagementObjectCollection GetRelated(String relatedClass)
System.Management.ManagementObjectCollection GetRelated(String relatedClass, String relationshipClass, String relationshipQualifier, String relatedQualifier,String relatedRole, String thisRole, Boolean classDefinitionsOnly, EnumerationOptions options)
(I left out the ASync Methods)
Oops, IMNSHO that is not a nice Overload !!!
(Quiz Question : You know them All  well enough to fill the 3th overload ?)
I do now ;-) (see later in post) and it seems that you can keep the ones you don't need empty.
it is : 
MSH G:\Monad> (get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelated($null,"Win32_DependentService",$null,$null,$null,"Antecedent",$false,$null)
But then I did not know what to fill in, but I saw another Method called

after playing a bit I stopped at :

 ((($s = get-wmiObject win32_service -filter "Name = 'lanmanserver'").GetRelationships("win32_Dependentservice"))  foreach {$_.dependent}).split("=")[1]

What do you think ? , In this case I would more like the ".NET" solution ;-) But.. help was on the way ;-) while searching SDK's etc for the WQL language specs, I stumbled upon System.Management.RelationshipQuery after playing with it (more about how later) I could only make a

So I needed his brother-class : System.Management.RelatedObjectQuery(System.Management.RelatedObjectQuery is related to GetRelated and RelationshipQuery to GetRelationships)


.So ... and what can we do with thos 2 classes ?


Translate WQL Query's to Properties and Back !!!


MSH G:\Monad> $roq = new-object System.Management.RelatedObjectQuery
MSH G:\Monad> $roq.QueryString = "associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent"
MSH G:\Monad> $roq


IsSchemaQuery : False
SourceObject : Win32_Service.name='lanmanserver'
RelatedClass : win32_service
RelationshipClass :
RelatedQualifier :
RelationshipQualifier :
RelatedRole :
ThisRole : Antecedent
ClassDefinitionsOnly : False
QueryLanguage : WQL
QueryString : associators of {Win32_Service.name='lanmanserver'} wher
e resultclass = win32_service role = Antecedent
So, Now you know How I filled in that 3th Overload of GetRelated ;-) but at the End, I don't know if i want to, because you can get put the RelatedObjectQuery into a ManagementObjectSearcher directly. (see last "bonus"-script.) so until you need more as only the relatedClass (1st/2nd Overload of GetRelated) get-wmiObject is nice but after that I prefer the "system.management"-Way And .. as final "Bonus" - script to learn the WMI Queries, I coupled to on my Objectviewer-script, to get a GUI WQL-Querytool :
$roq = new-object System.Management.RelatedObjectQuery
ov($roq)
$mos = new-object system.management.ManagementObjectSearcher($roq)

In the MSHObjectviewer you can change the Properties (or the Query), and you will see the effect in the Query(or the properties). You have to change to another field to see the reaction. I think now you have enough tools to get some more heavy work done in WMI Doe er iets leuks mee (have Fun) gr /\/\o\/\/ PS IF you do not have OV(MSHObject-Viewer), go here : MSH Object Viewer for more info about WQL queries go to : http://msdn.microsoft.com/library/en-us/wmisdk/wmi/wql_sql_for_wmi.asp?frame=true


 


* Update *


Also for the .NET Query helper classes I did show how to use in the original post above, you can use them with [WmiSearcher]  in RC2 so you do not need to make the object yourself,


Also I show that you can also use a GUI using the function out-datagrid to get a kind of Query Generator,


You can find that function here :


  powershell-out-propertygrid-msh-view.html 


that is an updated version of the MSH object viewer mentioned. that can be used to configure the WMI queries in A GUI


 



PS C:\PowerShell> # make the Query
PS C:\PowerShell>
PS C:\PowerShell> $roq = new-object System.Management.RelatedObjectQuery
PS C:\PowerShell> $roq.QueryString = "associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent"
PS C:\PowerShell> $roq

IsSchemaQuery : False
SourceObject : Win32_Service.name='lanmanserver'
RelatedClass : win32_service
RelationshipClass :
RelatedQualifier :
RelationshipQualifier :
RelatedRole :
ThisRole : Antecedent
ClassDefinitionsOnly : False
QueryLanguage : WQL
QueryString : associators of {Win32_Service.name='lanmanserver'} where resultclass = win32_service role = Antecedent

PS C:\PowerShell>
PS C:\PowerShell> # Execute the Query in RC2 :
PS C:\PowerShell>
PS C:\PowerShell> ([WmiSearcher]$roq).get()

ExitCode : 0
Name : Browser
ProcessId : 876
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Dfs
ProcessId : 1264
StartMode : Auto
State : Running
Status : OK

ExitCode : 0
Name : Netlogon
ProcessId : 432
StartMode : Auto
State : Running
Status : OK

 


 


 


PS C:\PowerShell>
PS C:\PowerShell> # Example Of using a PropertyGrid to make the Query
PS C:\PowerShell>
PS C:\PowerShell> [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")


GAC Version Location
--- ------- --------
True v2.0.50727 C:\WINDOWS\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.For...

PS C:\PowerShell>
PS C:\PowerShell> . .\Out-PropertyGrid.ps1
PS C:\PowerShell>
PS C:\PowerShell> $roq | opg
Cancel
PS C:\PowerShell> # And you can also use it for the whole Searcher Object
PS C:\PowerShell> [WmiSearcher]$roq | opg
Cancel
PS C:\PowerShell>


 

 

the [WMI] and [WMIClass] in PoSH RC2 make working with a WMI Path or Query much Easier,also that you can see the Class methods on the WMI Object and use the directly, make that it is much Easier to work with and explore WMI in PowerShell RC2,

So in this examples the RC2 changes do really help, and Queries are more used, and more handy to work with as using the methods as you see in this post, 

Hence in Case of WMI till now I'm still very happy with the change, as you can see in original entry I missed that at the time, and can live with PSBase for this.

So I don't mind I need to update my scripts for this, more later in this series.

Enjoy,

Greetings, /\/\o\/\/

Tags : Monad PowerShell




posted by /\/\o\/\/
 0 comments

Archives

October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006  

$Links = ("PowerShell RC1 Docs"," PowerShell RC1 X86"," PowerShell RC1 X64"," Monad GettingStarted guide"," Monad Progamming Guide"," Monad SDK"," Monad videos on Channel 9"," MSH Community Workspace"," scripts.readify.net "," MonadSource"," www.reskit.net"," PowerShell Blog"," Under The Stairs"," computerperformance powershell Home"," proudlyserving"," MSH on wikipedia"," MSHWiki Channel 9"," Keith Hill's Blog"," Precision Computing"," PowerShell for fun"," MSH Memo (Japanese)"," monadblog")

find-blog -about "PowerShell","Monad" | out-Technorati.
find-blog -contains "","" | out-Technorati.
Google
 
Web mow001.blogspot.com

This page is powered by Blogger. Isn't yours?