Monthly Archives: November 2011

Get indexed collection out of LinqDataSource

I wanted to convert this SQLdatasource

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:PaclikJConnectionString %>”
SelectCommand=”SELECT Row_number() OVER (ORDER BY Vlozeno DESC) as Poradi, ObrazID, Nazev, NazevAj, datepart(yy,DatumVyroby) as ‘RokVyroby’, Popis, PopisAj, cast(RozmerX as varchar(3)) + ‘x’ + cast(RozmerY as varchar(3)) + ‘ cm’ as Rozmer, Cena, NaProdej, Vlozeno, Nazev + ‘, rok: ‘ + cast(datepart(yy,DatumVyroby) as varchar(4)) + ‘, ‘ + Popis + ‘, ‘ + cast(RozmerX as varchar(3)) + ‘x’ + cast(RozmerY as varchar(3)) + ‘ cm’ as AltText, Nazev + ‘, rok: ‘ + cast(datepart(yy,DatumVyroby) as varchar(4)) + ‘, ‘ + PopisAj + ‘, ‘ + cast(RozmerX as varchar(3)) + ‘x’ + cast(RozmerY as varchar(3)) + ‘ cm’ as AltTextAj FROM Obrazy inner join Techniky on Obrazy.Technika = Techniky.TechnikaID ORDER BY Vlozeno DESC”>
</asp:SqlDataSource>

to LinqDataSource. The importnat part on the SQLDatasource is of cource the SQL query which indexes the rows. Lower is the solution I came up with to get the same behaviour with LInqToSQL Linqdatasource

Protected Sub LinqDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles LinqDataSource1.Selecting
        'handle selecting event if you want to return custom objects ie. dont need all props or need to create custom props

        Dim ctx As New PaclikDataContext

	    'ObjectTrackingEnabled = False 'cos I'm not going to update object, just show them
        ctx.ObjectTrackingEnabled = False
        Dim Obrazy = (ctx.Obrazs _
                     .OrderByDescending(Function(o) o.Vlozeno) _
                     .Select(Function(o) New With { _
                                 .ObrazId = o.ObrazID, _
                                 .Nazev = o.Nazev, _
                                 .NazevAj = o.NazevAj, _
                                 .RokVyroby = o.DatumVyroby.Year, _
                                 .Popis = o.Technika1.Popis, _
                                 .PopisAj = o.Technika1.PopisAj, _
                                 .Rozmer = o.RozmerX.ToString & " x " & o.RozmerY.ToString & " cm"})).ToList

        'I used .ToList 'cos I need the query to return something that implements IEnumerable(Of T)
        ' as AFaIK the overload of Select with the second index param can be used only on IEnumerable(Of T) not on IQueryable

			'notice the creation of Index property .Index = i
			e.Result = Obrazy.Select(Function(o, i) New With {.Index = i, _
                                                          .ObrazId = o.ObrazId, _
                                                          .Nazev = o.Nazev, _
                                                          .NazevAj = o.NazevAj, _
                                                          .RokVyroby = o.RokVyroby, _
                                                          .Popis = o.Popis, _
                                                          .PopisAj = o.PopisAj, _
                                                          .Rozmer = o.Rozmer _
                                                          })

    End Sub
End Class
Advertisements

Text to speech in Powershell using .NET

<br>function Out-TextToSpeech {  <p>param (<br>[Parameter(Mandatory=$true, ValueFromPipeline=$true)]<br>[string] $Text,<br>[switch] $Async=$false<br>)</p> <p>[Reflection.Assembly]::LoadWithPartialName('System.Speech') | Out-Null<br>$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer<br>if ($Async) {<br>$synth.SpeakAsync($Text)<br>} else {<br>$synth.Speak($Text)<br>}<br>}</p> <p>Out-TextToSpeech "i lost my socks" -async<br>

If you use the –Async switch then the func won’t block the console while the text is spoken

Text to speech in Powershell using com object

function Out-Voice {
param([Parameter(Mandatory=$true)]$Text, [switch]$Drunk)
$object = New-Object -ComObject SAPI.SpVoice
if ($drunk) { $object.Rate = -10 }
$object.Speak($text) | Out-Null}
Out-Voice -Text "hello, Unipex is great"
Out-Voice -Text "hello, Unipex is great" -Drunk
if you are not familiar with functions just do
$object = New-Object -ComObject SAPI.SpVoice
$object.Speak("hello, Unipex is superb") | Out-Null
to get all avalable/installed voices
 $object = New-Object -ComObject SAPI.SpVoice
 $object.GetVoices() | foreach {$_.getdescription()}

Blanka602
bob
igor
machac
machac-lpp
Microsoft Anna – English (United States)
violka
violka-lpp

to set a voice
$voicetouse=$object.GetVoices("Name=bob")
$object.voice = $voicetouse.item(0)
$object.Speak("kolo")

http://www.ehow.com/how_10073764_speak-different-voices-powershell.html

http://community.spiceworks.com/scripts/show/938-making-remote-computers-speak-what-you-type?page=2

3 ways of object creation in Powershell

1. Using Select-Object

$myobject = "" | select name, number, description
$myobject.Name = "Object1"
$myobject.Number = 100
$myobject.Description = "Using Select-Object"

ADMIN PS> $myobject | fl
name        : Object1
number      : 100
description : Using Select-Object

ADMIN PS> $myobject | gm

   TypeName: Selected.System.String

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
description NoteProperty System.String description=Using Select-Object
name        NoteProperty System.String name=Object1
number      NoteProperty System.Int32 number=100

ADMIN PS> $myobject.gettype().fullname
System.Management.Automation.PSCustomObject

 

2.Using New-Object and Add-Member

$myobject = New-Object System.Management.Automation.PSObject |
Add-Member -MemberType NoteProperty -Name "Name" `
-Value "Object2" -PassThru |
Add-Member -MemberType NoteProperty -Name "Number" `
-Value 100 -PassThru |
Add-Member -MemberType NoteProperty -Name "Description" `
-Value "Using New-Object and Add-Member" -PassThru

 

ADMIN PS> $myobject | fl
Name        : Object2
Number      : 100
Description : Using New-Object and Add-Member

ADMIN PS> $myobject | gm
  TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Description NoteProperty System.String Description=Using New-Object and Add-Member
Name        NoteProperty System.String Name=Object2
Number      NoteProperty System.Int32 Number=100

ADMIN PS> $myobject.gettype().fullname
System.Management.Automation.PSCustomObject

3. Using New-Object and a hashtable

$myobject = New-Object System.Management.Automation.PSObject `
-Property @{
Name = "Object3"
Number= 100
Description = "Using New-Object and a hashtable"
}

ADMIN PS> $myobject | fl
Name        : Object3
Number      : 100
Description : Using New-Object and a hashtable

ADMIN PS> $myobject | gm
TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Description NoteProperty System.String Description=Using New-Object and a hashtable
Name        NoteProperty System.String Name=Object3
Number      NoteProperty System.Int32 Number=100

ADMIN PS> $myobject.gettype().fullname
System.Management.Automation.PSCustomObject

Test WMI event query using wbemtest

Run wbemtest (menu Start – Run – wbemtest). Note that wbemtest.exe is part of Windows XP, Vista, 7.

wbemtest1

click Connect

wbemtest2

click Connect again

wbemtest3

select Asynchronous

wbemtest4

click Query Notification

wbemtest5

Insert Wmi event query, click Commit

wbemtest6

When you run calc you’ll see event pop up in the window

Power Events

http://powerevents.codeplex.com/
What is PowerEvents?

PowerEvents is a Windows PowerShell v2.0 module designed to facilitate the ease of creating, updating, and deleting WMI (Windows Management Instrumentation) permanent event registrations. PowerEvents makes it easy to create WMI event filters (define the events you want to capture) and event consumers (responders to events), and then bind them together to initiate the flow of events. By leveraging permanent event registrations, you can perform advanced monitoring functions on a workstation or server, that would otherwise require implementation of an enterprise monitoring product. Because WMI is incredibly vast in the information it provides, very detailed monitoring can be performed using almost any of the WMI objects that exist on a computer.

What are WMI Permanent Event Registrations?

A little-known capability of the WMI service, is its capability to create a permanent registration (listener) for events, and then automatically respond to those events. At a very basic level, it’s “if X happens, do Y” but in this case, it’s all built into WMI, without the need for any additional software.

What Can I Monitor with PowerEvents?

WMI contains a vast amount of information about the Windows operating system, the hardware underneath it, and applications that extend WMI.
Here are a very fewexamples of events that you can monitor in WMI:

  • Microsoft Active Directory
    • Changes in group policy configuration on GP clients
    • Users created or deleted
    • Computer accounts moved
  • Microsoft System Center Configuration Manager
    • Package created, deleted, or modified
    • Advertisement created, deleted, or modified
    • Collection created, deleted, or modified
  • Monitor Disk Events
    • USB flash (UFD) or eSATA drive plugged in or removed
    • Detect shrink or expansion of partitions
  • Monitor Processes
    • Start/stop events
    • Change in process priority
    • Working set (memory utilization) increase/decrease or exceeds “X” value
    • I/O operations increase or exceed a certain value
  • Windows Services
    • Start / stop events
    • New service installed or removed
    • Service start type changed
  • Device changes
    • Detect addition or removal of devices
  • Print jobs
    • Detect new job or finished job
    • Changes in job status
  • Software & Patches
    • Software installed or removed
    • New patches installed
  • Operating System
    • New reliability records created
    • New game registered with Windows 7 Games Explorer
  • User Events
    • User logon / logoff
    • User attributes
  • Network
    • IP address changed
    • Default gateway changed
    • Network adapter added or removed
    • Server Message Block (SMB) session created or ended
  • ODBC Data Sources
    • Created or removed
    • Driver installed
    • Configuration changed
  • Threads
    • Creation or termination
    • Thread state changes
  • Microsoft Distributed File System (DFS)
    • Last replication time changes
    • Errors during replication
    • Volume serial # changes
Why Should I use PowerEvents?

Because it’s awesome! In all reality, the capabilities of this module are quite vast, only limited by the information available in WMI. Because many applications extend WMI through WMI providers, these can be not just managed, but also extensively monitored. Additionally, the Windows operating system itself makes extensive use of WMI to provide system information to applications. Through this, you can discover and monitor almost anything you’d want to know about your workstation or server!

  • Microsoft Active Directory (AD)
  • SQL Server
  • Distributed FileSystem (DFS)
  • Microsoft DNS
  • System Center Configuration Manager (SCCM or ConfigMgr)
  • Internet Information Services (IIS) 6 / 7
  • Windows XP / Vista / 7
  • Windows Server 2003 / 2008 / 2008 R2
About the Author

Trevor Sullivan has 7 years of experience in the Information Technology field, and has worked primarily with Microsoft products such as Active Directory, Group Policy, System Center Configuration Manager 2007, Microsoft Deployment Toolkit (MDT) 2010, VBscript, Windows PowerShell, and C#/.NET. Trevor is passionate about sharing with community, and is an active community participant in a variety of mailing lists, forums, blogging, Twitter (@pcgeek86), and other social media outlets.
Follow Trevor on Twitter: http://twitter.com/pcgeek86
Trevor’s Blog (Art of Shell): http://powershell.artofshell.com
Trevor’s Blog (WordPress): http://trevorsullivan.net

Using Power Events

Example: log every creation of process into a file

I will log every creation of process calc.exe into a file c:\temp\Calc.log. I will be using PowerEvents.

First create filter using wql query

$f=New-WmiEventFilter -Name ProcessStarted -Query “select * from __InstanceCreationEvent within 2 where TargetInstance ISA ‘Win32_Process’ and TargetInstance.Name=’calc.exe'”

Notice the condition in the WQL query – TargetInstance.Name =’calc.exe’ (not TargetInstance.ProcessName because ProcessName is a Powershell alias to Name property in win32_process WMI class as you can find out using Get-WmiObject -Class win32_process  | Get-Member)

One can check wheather the WMI event query works using wbemtest utility

Create consumer using -ScriptFile parameter (not succesfull)

At first I tried -ScriptFile parameter of New-WmiEventConsumer

$c = New-WmiEventConsumer -Name ProcessStartedConsumer –ConsumerType Script –ScriptFile D:\scripts\psh\EventConsumer.vbs

The content of file D:\scripts\psh\EventConsumer.vbs being

set fso = CreateObject(“Scripting.FileSystemObject”)

set LogFile = fso.OpenTextFile(“c:\temp\Calc.log”, 8, true)

call LogFile.WriteLine(Date() & ” ” & Time() & “: Calc.exe run”)

but I could not get it to work

Create consumer using -ScriptText parameter (successfull)

prepare VBscript code as a herestring

$VBcode = @”

set fso = CreateObject(“Scripting.FileSystemObject”)

set LogFile = fso.OpenTextFile(“c:\temp\Calc.log”, 8, true)

call LogFile.WriteLine(Date() & ” ” & Time() & “: Calc.exe run”)

“@

Create event consumer of type script

$c = New-WmiEventConsumer -Name ProcessStartedConsumer –ConsumerType Script –ScriptText $VBcode

notice the use of herestring with the -ScriptText parameter


#full code

#create filter using wql query

$f = New-WmiEventFilter -Name ProcessStarted -Query “select * from __InstanceCreationEvent within 2 where TargetInstance ISA ‘Win32_Process’ and TargetInstance.Name=’calc.exe'”

#get ready vb script code

$VBcode = @”

set fso = CreateObject(“Scripting.FileSystemObject”)

set LogFile = fso.OpenTextFile(“c:\temp\Calc.log”, 8, true)

call LogFile.WriteLine(Date() & ” ” & Time() & “: Calc.exe run”)

“@

#create event consumer of type script

$c = New-WmiEventConsumer -Name ProcessStartedConsumer –ConsumerType Script –ScriptText $VBcode

#link filter and consumer together

New-WmiFilterToConsumerBinding -Filter $f -Consumer $c

smsagent

Tips, tricks and time-savers for the Windows and ConfigMgr administrator

To The Point

Anything about Technology and Business

Brian's Power Windows Blog

Microsoft in the Enterprise. Windows, Hyper-V, Exchange, SQL, and more!

PowerScripting Podcast

Shownotes and links for the PowerScripting Podcast, a podcast to help people learn Windows Powershell

Learn Powershell | Achieve More

What is this Powershell of which you speak?