Thursday, July 31, 2014

Powershell: Converting VBScript to Powershell

Below is a script directly from the Windows 2000 Scripting Guide:

Retrieving System Information
Computer Assets, Listing 8.1

Description
Retrieves information similar to that returned by the System Information utility.


Script Code


Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSettings = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colSettings
    Wscript.Echo "OS Name: " & objOperatingSystem.Name
    Wscript.Echo "Version: " & objOperatingSystem.Version
    Wscript.Echo "Service Pack: " & _
        objOperatingSystem.ServicePackMajorVersion _
            & "." & objOperatingSystem.ServicePackMinorVersion
    Wscript.Echo "OS Manufacturer: " & objOperatingSystem.Manufacturer
    Wscript.Echo "Windows Directory: " & _
        objOperatingSystem.WindowsDirectory
    Wscript.Echo "Locale: " & objOperatingSystem.Locale
    Wscript.Echo "Available Physical Memory: " & _
        objOperatingSystem.FreePhysicalMemory
    Wscript.Echo "Total Virtual Memory: " & _
        objOperatingSystem.TotalVirtualMemorySize
    Wscript.Echo "Available Virtual Memory: " & _
        objOperatingSystem.FreeVirtualMemory
    Wscript.Echo "OS Name: " & objOperatingSystem.SizeStoredInPagingFiles
Next
Set colSettings = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_ComputerSystem")
For Each objComputer in colSettings
    Wscript.Echo "System Name: " & objComputer.Name
    Wscript.Echo "System Manufacturer: " & objComputer.Manufacturer
    Wscript.Echo "System Model: " & objComputer.Model
    Wscript.Echo "Time Zone: " & objComputer.CurrentTimeZone
    Wscript.Echo "Total Physical Memory: " & _
        objComputer.TotalPhysicalMemory
Next
Set colSettings = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_Processor")
For Each objProcessor in colSettings
    Wscript.Echo "System Type: " & objProcessor.Architecture
    Wscript.Echo "Processor: " & objProcessor.Description
Next
Set colSettings = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_BIOS")
For Each objBIOS in colSettings
    Wscript.Echo "BIOS Version: " & objBIOS.Version
Next

How can this be converted to Powershell?

$strComputer = "."
$iret = [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$objWMIService= [Microsoft.VisualBasic.Interaction]::GetObject("winmgmts:impersonationLevel=impersonate}!\\" + $strComputer + "\root\cimv2")
$colSettings = $objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem")
foreach($objOperatingSystem in $colSettings)
{
    write-host "OS Name: "$objOperatingSystem.Name
    write-host "Version: "$objOperatingSystem.Version
    $strsp =  $objOperatingSystem.ServicePackMajorVersion
    $strsp = $strsp + "."
    $strsp = $strsp + $objOperatingSystem.ServicePackMinorVersion
    write-host "Service Pack: "$strsp
    write-host "OS Manufacturer: "$objOperatingSystem.Manufacturer
    write-host "Windows Directory: "$objOperatingSystem.WindowsDirectory
    write-host "Locale: "$objOperatingSystem.Locale
    write-host "Available Physical Memory: "$objOperatingSystem.FreePhysicalMemory
    write-host "Total Virtual Memory: "$objOperatingSystem.TotalVirtualMemorySize
    write-host "Available Virtual Memory: "$objOperatingSystem.FreeVirtualMemory
    write-host "OS Name: "$objOperatingSystem.SizeStoredInPagingFiles
}
$colSettings = $objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem")
foreach($objComputer in $colSettings)
{
    write-host "System Name: "$objComputer.Name
    write-host "System Manufacturer: "$objComputer.Manufacturer
    write-host "System Model: "$objComputer.Model
    write-host "Time Zone: "$objComputer.CurrentTimeZone
    write-host "Total Physical Memory: "$objComputer.TotalPhysicalMemory
}
$colSettings = $objWMIService.ExecQuery("SELECT * FROM Win32_Processor")
foreach($objProcessor in $colSettings)
{
     write-host "System Type: "$objProcessor.Architecture
     write-host "Processor: "$objProcessor.Description
}
$colSettings = $objWMIService.ExecQuery("SELECT * FROM Win32_BIOS")
foreach($objBIOS in $colSettings)
{
     write-host "BIOS Version: "$objBIOS.Version
}

And there you have it.










Powershell: Does a value exist in the registry

param
(
        [Parameter(Mandatory=$True)]
        [string]$subkeyname,
        [Parameter(Mandatory=$True)]
        [string]$ValueName,
)

$regkey = [Microsoft.Win32.Registry]::ClassesRoot
$value = $regkey.OpenSubKey($subkeyname).GetValue($ValueName)
if(!($value))
{
    write-host "Value does not exist."
}
else
{
    write-host "Value exists."
}

Powershell: Get a List of Registry Key Values

This code shows you how to acquire a list of value names after specifying a key path:

param
(
    [Parameter(Mandatory=$True)]
    [string]$Subkey,
    [Parameter(Mandatory=$True)]
    [string]$Filter
)

    $regkey = [Microsoft.Win32.Registry]::ClassesRoot
    if($Subkey)
    {
        $Names = $regkey.GetSubKeyNames()
        $NameList = New-Object 'System.Collections.Generic.List[string]'
       
        foreach($n in $Names)
        {
            $pos = $n.IndexOf($Filter)
           
            if ($pos -ne -1)
            {
                write-host $n  
                $NameList.Add($n)
        }   
        }     
    }
    else
    {
        $Names = $regkey.OpenSubKey($Subkey).GetSubKeyNames()
        $NameList = New-Object 'System.Collections.Generic.List[string]'
        foreach($n in $Names)
        {
            $pos = $n.IndexOf($Filter)
            if ($pos -gt 0)
            {
                write-output $n
                $NameList.Add($n)
        }   
        }
    }
   

Powershell: Discover if a registry key exists

This code is only one example and is targeted at the HKEY_CLASSES_ROOT:

param
(
   [Parameter(Mandatory=$True)]
   [string]$Subkey
)
function Test-Registry-key
{
    param
    (
        [Parameter(Mandatory=$True)]
        [Microsoft.Win32.RegistryKey]$Regkey,
        [Parameter(Mandatory=$True)]
        [string]$key
    )
    $rkey = $regkey.OpenSubKey($key)
    if(!($rkey))
    {
        return "Key does not exist."
    }
    else
    {
        return "Key exists."
    }

}
$regkey = [Microsoft.Win32.Registry]::ClassesRoot
$ret = Test-Registry-Key $regkey $Subkey
write-host $ret

Powershell: Working With The Registry Part 2

In  part one, we covered some of the primary functions of the Microsoft Win32 API.

Now, it is time to share some more knowledge:

When you use the RegistryKey.OpenBaseKey, you can choose three options:

  1. [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Default)
  2. [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry32)
  3. [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64)
There is a world of difference between what you see in the 32 bit and the 64 bit. Test your selections to determine which will work best for you.

Also, notice that you still have one more choice to make with respect to the target hive. For

HKEY_CLASSES_ROOT:


[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::ClassesRoot, [Microsoft.Win32.RegistryView]::Registry32)

HKEY_CURRENT_CONFIG:

[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentConfig, [Microsoft.Win32.RegistryView]::Registry32)
HKEY_CURRENT_USER:

[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser, [Microsoft.Win32.RegistryView]::Registry32)
HKEY_LOCAL_MACHINE:

[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry32)

HKEY_USERS:

[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::Users, [Microsoft.Win32.RegistryView]::Registry32)

Past this, in order to enumerate through the first level of subkeys,

$Names = $regkey.GetSubKeyNames()
foreach($Name in $Names)
{
        #Do something with the key name here
}

In order to open a sub key and then get the sub key names:

$Names = $regkey.OpenSubKey("Software\Microsoft").GetSubKeyNames()
foreach($Name in $Names)
{
        #Do something with the key name here
}

In order to get the Value Names:

$Names = $regkey.GetValueNames()
foreach($Name in $Names)
{
        #Do something with the key name here
}

In order to open a sub key and then get the Value Names of the sub key:

$Names = $regkey.OpenSubKey("Software\Microsoft").GetValueNames()
foreach($Name in $Names)
{
        #Do something with the key name here
}

In order to get the valuekind of a value:

$vkind = $regkey.OpenSubKey("ADODB.Connection\clsid").GetValueKind("")
Assuming you pointed the registrykey to ClassesRoot, this will return
RegistryValueKind.String

Of course, technically, the return value --albeit a string -- is actually a guid. And that enables you to open clsid\{00000514-0000-0010-8000-00AA006D2EA4}\InprocServer32.  Which will point you to the physical location of the file that can be checked for the correct physical file version and internal file version information.














Powershell: Working With The Registry Part3

Here's a script that will populate all the keys in HKEY_CLASSES_ROOT in alphabetical order in an excel spreadsheet:


$oexcel = new-object -comobject Excel.Application
$Workbook = $oexcel.Workbooks.Add()
$oexcel.Visible = $true

$regkey = [Microsoft.Win32.Registry]::ClassesRoot
$Names = $regkey.GetSubKeyNames()
[string]$n
[array]$myvar = [System.Array]::CreateInstance([string], 26)
$myvar[0] = "A"
$myvar[1] = "B"
$myvar[2] = "C"
$myvar[3] = "D"
$myvar[4] = "E"
$myvar[5] = "F"
$myvar[6] = "G"
$myvar[7] = "H"
$myvar[8] = "I"
$myvar[9] = "J"
$myvar[10] = "K"
$myvar[11] = "L"
$myvar[12] = "M"
$myvar[13] = "N"
$myvar[14] = "O"
$myvar[15] = "P"
$myvar[16] = "Q"
$myvar[17] = "R"
$myvar[18] = "S"
$myvar[19] = "T"
$myvar[20] = "U"
$myvar[21] = "V"
$myvar[22] = "W"
$myvar[23] = "X"
$myvar[24] = "Y"
$myvar[25] = "Z"
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()
$workbook.Worksheets.Add()

    $sheet = $workbook.worksheets.Item(1)
    $sheet.name = "A"
    $sheet = $workbook.worksheets.Item(2)
    $sheet.name = "B"
    $sheet = $workbook.worksheets.Item(3)
    $sheet.name = "C"
    $sheet = $workbook.worksheets.Item(4)
    $sheet.name = "D"
    $sheet = $workbook.worksheets.Item(5)
    $sheet.name = "E"
    $sheet = $workbook.worksheets.Item(6)
    $sheet.name = "F"
    $sheet = $workbook.worksheets.Item(7)
    $sheet.name = "G"
    $sheet = $workbook.worksheets.Item(8)
    $sheet.name = "H"
    $sheet = $workbook.worksheets.Item(9)
    $sheet.name = "I"
    $sheet = $workbook.worksheets.Item(10)
    $sheet.name = "J"
    $sheet = $workbook.worksheets.Item(11)
    $sheet.name = "K"
    $sheet = $workbook.worksheets.Item(12)
    $sheet.name = "L"
    $sheet = $workbook.worksheets.Item(13)
    $sheet.name = "M"
    $sheet = $workbook.worksheets.Item(14)
    $sheet.name = "N"
    $sheet = $workbook.worksheets.Item(15)
    $sheet.name = "O"
    $sheet = $workbook.worksheets.Item(16)
    $sheet.name = "P"
    $sheet = $workbook.worksheets.Item(17)
    $sheet.name = "Q"
    $sheet = $workbook.worksheets.Item(18)
    $sheet.name = "R"
    $sheet = $workbook.worksheets.Item(19)
    $sheet.name = "S"
    $sheet = $workbook.worksheets.Item(20)
    $sheet.name = "T"
    $sheet = $workbook.worksheets.Item(21)
    $sheet.name = "U"
    $sheet = $workbook.worksheets.Item(22)
    $sheet.name = "V"
    $sheet = $workbook.worksheets.Item(23)
    $sheet.name = "W"
    $sheet = $workbook.worksheets.Item(24)
    $sheet.name = "X"
    $sheet = $workbook.worksheets.Item(25)
    $sheet.name = "Y"
    $sheet = $workbook.worksheets.Item(26)
    $sheet.name = "Z"

for($x=0;$x -lt $myvar.GetLength(0);$x++)
{
         
    $sheet = $workbook.worksheets.Item($x+1)
    $y = 0
    foreach($Name in $Names)
    {
        $pos = $Name.IndexOf($myvar[$x])
        if($pos -eq 0)
        {
            $sheet.cells.item($y+1,1) = $Name
            $y=$y+1
        }
    } 
   
    $oexcel.Columns.HorizontalAlignment = -4131
    $iret = $oexcel.Columns.AutoFit()    
}

Powershell: Creating a Process in a Hidden Window Processes


This script Demonstrates how to create a hidden window while launching an instance of Notepad.
 

 ([wmiclass]"Win32_Process").Create("notepad")
 
How Much easier can it get? 
 

Wednesday, July 30, 2014

Powershell and event providers

When you write:

Select * From __InstanceCreationEvent WITHIN 1 where target instance ISA 'Win32_Process'"

What does that really mean?

  1. It means that when a Win32_Process Class gets created, you get notified.
  2. It means that when an __InstanceCreationEvent Class is used, you get notified.
  3. None of the above
  4. All of the above -- including None of the above
  5. All of the above -- excluding 3 and 4
  6. I'm as confused as you are, ACE, so let's crash and burn together.
Truth, an event provider is there to help us get notified when something happens. There's a whole lot of events that happen within the world of Windows and WMI.

__InstanceOperationEvent
__InstanceModificationEvent
__InstanceCreationEvent
__MethodInvocationEvent
__InstanceDeletionEvent

__ClassOperationEvent
__ClassDeletionEvent
__ClassModificationEvent
__ClassCreationEvent

__NamespaceOperationEvent
__NamespaceModificationEvent
__NamespaceDeletionEvent
__NamespaceCreationEvent

__TimerEvent
__ExtrinsicEvent
__SystemEvent

__EventDroppedEvent
__EventQueueOverflowEvent

__QOSFailureEvent
__ConsumerFailureEvent


Powershell: Creating easy to read tabular output

This one is going to be quick and to the point.

If you have been writing VBScripts and the like, you know, in order to block columns of information, by finding the max length of the entry and then use that against the length of each item:

       L = 120
      For each prop in obj.Properties_
         txtstream.WriteLine(Prop,Name & spaces(L - len(prop.Name)) & nextvalue
     Next

Of course the above is a pretty bad example.  But you get the Idea.  Get the longest length and then add padding to the right using the space function to add the number of spaces need so that the next value would start at exactly the same location.

In .Net and using power shell:

foreach($prop in $obj.Proeprties_)
{
      $txtstream.WriteLine("$prop.Name.ToString.Paddright 120, " ") + $nextValue
}

And it is done.




 

Sunday, July 27, 2014

Powershell: Working with the registry Part 1

Second to Windows Management Instrumentation, the registry is one of the most powerful tools you have as a potential money making skill set. It is also be one of the most dangerous and less understood tools of the trade.

With that said, let's jump right in.

HIVES

Sections of the registry are known as hives. The five most popular are:

  1. HKEY_CLASSES_ROOT
  2. HKEY_CURRENT_CONFIG
  3. HKEY_CURRENT_USER
  4. HKEY_LOCAL_MACHINE
  5. HKEY_USERS
Prior to .Net, you had to know each of those as constants where and you had to the APIs needed to use them. With .Net, the ability to connect to the registry is as simple as this:
 

$regkey = [Microsoft.Win32.Registry]::ClassesRoot
[array]$Names = $regkey.OpenSubKey("DataLinks").GetSubKeyNames()
foreach($n in $Names)

{
write-host $n
}

This returns: CLSID
 

I add this to the Datalinks subkey and make the call again:

[string]$Value = $regkey.OpenSubKey("DataLinks\CLSID").GetValue("")
write-host $value


And this returns:
 

{2206CDB2-19C1-11D1-89E0-00C04FD7A829}



I can then go to the clsid section and glean information about the location of the file:

[string]$value = $regkey.OpenSubKey("clsid\{2206CDB2-19C1-11D1-89E0-00C04FD7A829}\InprocServer32").GetValue("")

And that returns:

C:\Program Files\Common Files\System\Ole DB\oledb32.dll

Saturday, May 10, 2014

Powershell: Win32_Process: List account for each process

How many times have you been asked to find out what account is being used for a
specific process or service?
 
I can count about a hundred.
 
Well, in two lines you can dazzle your boss or client with this gem: 
 
$process = Get-CimInstance -Class Win32_Process
$process | Invoke-CimMethod -MethodName GetOwner

Thursday, May 8, 2014

Powershell: How to list properties from a type


I wanted to list the properties that are part of the System.Management Namespace:

To do this I needed to import the System.Management namespace into Powershell:

$Management = Add-Type -AssemblyName System.Management -PassThru

This gave me a reference to the type.

I then needed to list what was being exposed by the Add-Type syntax:

$Management | Get-Member -MemberType Property

The results are listed below:


Name                       MemberType Definition
----                       ---------- ----------
Assembly                   Property   System.Reflection.Assembly Assembly {get;}
AssemblyQualifiedName      Property   string AssemblyQualifiedName {get;}
Attributes                 Property   System.Reflection.TypeAttributes Attributes {get;}
BaseType                   Property   type BaseType {get;}
ContainsGenericParameters  Property   bool ContainsGenericParameters {get;}
CustomAttributes           Property   System.Collections.Generic.IEnumerable[System.Reflection.CustomAttributeData] CustomAttributes {get;}
DeclaredConstructors       Property   System.Collections.Generic.IEnumerable[System.Reflection.ConstructorInfo] DeclaredConstructors {get;}
DeclaredEvents             Property   System.Collections.Generic.IEnumerable[System.Reflection.EventInfo] DeclaredEvents {get;}
DeclaredFields             Property   System.Collections.Generic.IEnumerable[System.Reflection.FieldInfo] DeclaredFields {get;}
DeclaredMembers            Property   System.Collections.Generic.IEnumerable[System.Reflection.MemberInfo] DeclaredMembers {get;}
DeclaredMethods            Property   System.Collections.Generic.IEnumerable[System.Reflection.MethodInfo] DeclaredMethods {get;}
DeclaredNestedTypes        Property   System.Collections.Generic.IEnumerable[System.Reflection.TypeInfo] DeclaredNestedTypes {get;}
DeclaredProperties         Property   System.Collections.Generic.IEnumerable[System.Reflection.PropertyInfo] DeclaredProperties {get;}
DeclaringMethod            Property   System.Reflection.MethodBase DeclaringMethod {get;}
DeclaringType              Property   type DeclaringType {get;}
FullName                   Property   string FullName {get;}
GenericParameterAttributes Property   System.Reflection.GenericParameterAttributes GenericParameterAttributes {get;}
GenericParameterPosition   Property   int GenericParameterPosition {get;}
GenericTypeArguments       Property   type[] GenericTypeArguments {get;}
GenericTypeParameters      Property   type[] GenericTypeParameters {get;}
GUID                       Property   guid GUID {get;}
HasElementType             Property   bool HasElementType {get;}
ImplementedInterfaces      Property   System.Collections.Generic.IEnumerable[type] ImplementedInterfaces {get;}
IsAbstract                 Property   bool IsAbstract {get;}
IsAnsiClass                Property   bool IsAnsiClass {get;}
IsArray                    Property   bool IsArray {get;}
IsAutoClass                Property   bool IsAutoClass {get;}
IsAutoLayout               Property   bool IsAutoLayout {get;}
IsByRef                    Property   bool IsByRef {get;}
IsClass                    Property   bool IsClass {get;}
IsCOMObject                Property   bool IsCOMObject {get;}
IsConstructedGenericType   Property   bool IsConstructedGenericType {get;}
IsContextful               Property   bool IsContextful {get;}
IsEnum                     Property   bool IsEnum {get;}
IsExplicitLayout           Property   bool IsExplicitLayout {get;}
IsGenericParameter         Property   bool IsGenericParameter {get;}
IsGenericType              Property   bool IsGenericType {get;}
IsGenericTypeDefinition    Property   bool IsGenericTypeDefinition {get;}
IsImport                   Property   bool IsImport {get;}
IsInterface                Property   bool IsInterface {get;}
IsLayoutSequential         Property   bool IsLayoutSequential {get;}
IsMarshalByRef             Property   bool IsMarshalByRef {get;}
IsNested                   Property   bool IsNested {get;}
IsNestedAssembly           Property   bool IsNestedAssembly {get;}
IsNestedFamANDAssem        Property   bool IsNestedFamANDAssem {get;}
IsNestedFamily             Property   bool IsNestedFamily {get;}
IsNestedFamORAssem         Property   bool IsNestedFamORAssem {get;}
IsNestedPrivate            Property   bool IsNestedPrivate {get;}
IsNestedPublic             Property   bool IsNestedPublic {get;}
IsNotPublic                Property   bool IsNotPublic {get;}
IsPointer                  Property   bool IsPointer {get;}
IsPrimitive                Property   bool IsPrimitive {get;}
IsPublic                   Property   bool IsPublic {get;}
IsSealed                   Property   bool IsSealed {get;}
IsSecurityCritical         Property   bool IsSecurityCritical {get;}
IsSecuritySafeCritical     Property   bool IsSecuritySafeCritical {get;}
IsSecurityTransparent      Property   bool IsSecurityTransparent {get;}
IsSerializable             Property   bool IsSerializable {get;}
IsSpecialName              Property   bool IsSpecialName {get;}
IsUnicodeClass             Property   bool IsUnicodeClass {get;}
IsValueType                Property   bool IsValueType {get;}
IsVisible                  Property   bool IsVisible {get;}
MemberType                 Property   System.Reflection.MemberTypes MemberType {get;}
MetadataToken              Property   int MetadataToken {get;}
Module                     Property   System.Reflection.Module Module {get;}
Name                       Property   string Name {get;}
Namespace                  Property   string Namespace {get;}
ReflectedType              Property   type ReflectedType {get;}
StructLayoutAttribute      Property   System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute {get;}
TypeHandle                 Property   System.RuntimeTypeHandle TypeHandle {get;}
TypeInitializer            Property   System.Reflection.ConstructorInfo TypeInitializer {get;}
UnderlyingSystemType       Property   type UnderlyingSystemType {get;}

Thursday, May 1, 2014

Powershell: Running A Job

You can start a job like this:

PS C:\Users\Administrator> Start-Job -ScriptBlock {Get-Process -ComputerName .}

Or this:

PS C:\Users\Administrator> Start-Job -ScriptBlock {Get-Process -ComputerName localhost}

Or this:

PS C:\Users\Administrator> Start-Job -ScriptBlock {Get-Process -ComputerName WIN-Q7SQIHMFTHM}







Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      Job2            BackgroundJob   Running       True            localhost            Get-Process

Then use Get-Job to determine if the job has completed:







PS C:\Users\Administrator> Get-Job -Id 2

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      Job2            BackgroundJob   Completed     True            localhost            Get-Process

To view the information, use Receive-Job:








PS C:\Users\Administrator> Receive-Job -Id 2

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    527      26     5292      17708    96     4.31   6016 CcmExec

Tuesday, April 29, 2014

Powershell: How to filter for specific groups of WMI classes

$ns
function enumclasses
{
    $classnames = Get-WmiObject -namespace $ns -class Meta_Class | select name  
    foreach($cn in $classnames)
    {
        $pos = $cn.Name.IndexOf("Win32")
        if($pos -gt -1)
        {
            write-host $cn.Name
        }   
    }        
}  

$ns = "root\cimv2"
enumclasses

Powershell: How to enumerate through WMI Classes

$ns
function enumclasses
{
    $classnames = Get-WmiObject -namespace $ns -class Meta_Class | select name  
    foreach($cn in $classnames)
    {
            write-host $cn.Name  
    }        
}  

$ns = "root\cimv2"
enumclasses

Powershell: How to recursively enumerate through namespaces

$ns
function enumNamespaces
{
    write-host $ns
    $Names = Get-WmiObject -namespace $ns -class __NameSpace | select name  
    foreach($n in $Names)
    {
         $ns = $ns + "\" + $n.Name
         enumNamespaces
         $ns = $ns.Replace("\" + $n.Name, "")     
    }        
}  

$ns = "root"
enumNamespaces

Monday, April 28, 2014

How to use Powershell to pad output using echo

$objs = Get-WMIObject -namespace root\cimv2 -class Win32_Battery

foreach($obj in $objs)
{
    foreach($prop in $obj.Properties)
    {
         echo $prop.Name.PadRight(30, " ") = $prop.Value
    }
}

How to use Powershell to pad output using write-host

$objs = Get-WMIObject -namespace root\cimv2 -class Win32_Battery

foreach($obj in $objs)
{
    foreach($prop in $obj.Properties)
    {
         write-host $prop.Name.PadRight(30, " ") = $prop.Value
    }
}

How to use Powershell to create a database using ADOX

function GetValue
{
    param
    (
    [string]$Name,
    [object]$obj
    )

    [string]$PName = $Name + " = "
    [string]$tempstr = $obj.GetObjectText_(0)

    $pos = $tempstr.IndexOf($PName)
    if ($pos -gt 0)
    {
        $pos = $pos + $PName.Length
        $tempstr = $tempstr.SubString($pos, ($tempstr.Length - $pos))
        $pos = $tempstr.IndexOf(";")
        $tempstr = $tempstr.SubString(0, $pos)
        $tempstr = $tempstr.Replace('"', "")
        $tempstr = $tempstr.Replace("}", "")
        $tempstr = $tempstr.Replace("{", "")
        $tempstr = $tempstr.Trim()
        if($tempstr.Length -gt 14)
        {
            if($obj.Properties_.Item($Name).CIMType -eq 101)
            {
                [System.String]$tstr = $tempstr.SubString(4, 2)
                $tstr = $tstr + "/"
                $tstr = $tstr + $tempstr.SubString(6, 2)
                $tstr = $tstr + "/"
                $tstr = $tstr + $tempstr.SubString(0, 4)
                $tstr = $tstr + " "
                $tstr = $tstr + $tempstr.SubString(8, 2)
                $tstr = $tstr + ":"
                $tstr = $tstr + $tempstr.SubString(10, 2)
                $tstr = $tstr + ":"
                $tstr = $tstr + $tempstr.SubString(12, 2)
                $tempstr = $tstr
            }
        }
        return $tempstr
    }
    else
    {
        return ""
    }
}


    $l = new-object -comobject Wbemscripting.SWbemLocator
    $svc = $l.ConnectServer(".", "root\cimv2")
    $svc.Security_.AuthenticationLevel=6
    $svc.Security_.ImpersonationLevel=3
    $ob = $svc.Get("Win32_Process")

    $ocat = new-object -comobject ADOX.Catalog
    $ocat.Create("Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + System.Environment.CurrentDirectory + "\Process.mdb")
    $otable = new-object -comobject ADOX.Table
    $otable.Name = "Processes_properties"

    foreach($prop in $ob.Properties_)
    {
        $ocolumn = new-object -comobject ADOX.Column
        $oColumn.Name = $prop.Name
        $oColumn.Type = 203
        $otable.Columns.Append($oColumn)
    }

    $ocat.Tables.Append($otable)
   
    $objs = $ob.Instances_(0)

    $rs = new-object -comobject ADODB.Recordset
    $rs.ActiveConnection = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + System.Environment.CurrentDirectory + "\Process.mdb"
    $rs.CursorLocation = 3
    $rs.LockType = 3
    $rs.Source = "Select * From Processes_Properties"
    $rs.Open()

    foreach($obj in $objs)
    {
        $rs.AddNew()
        foreach($prop in $obj.Properties_)
        {
            $rs.Fields($prop.Name).Value = GetValue $prop.Name $obj
        }
        $rs.Update()
    }

How to use Powershell to discover the current Domain using two lines of code

$iret = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain

Tuesday, March 25, 2014

Access And Powershell: How to populate a table

Here's the code:

function GetValue
{
    param
    (
    [string]$Name,
    [object]$obj
    )

    [string]$PName = $Name + " = "
    [string]$tempstr = $obj.GetObjectText_(0)

    $pos = $tempstr.IndexOf($PName)
    if ($pos -gt 0)
    {
        $pos = $pos + $PName.Length
        $tempstr = $tempstr.SubString($pos, ($tempstr.Length - $pos))
        $pos = $tempstr.IndexOf(";")
        $tempstr = $tempstr.SubString(0, $pos)
        $tempstr = $tempstr.Replace('"', "")
        $tempstr = $tempstr.Replace("}", "")
        $tempstr = $tempstr.Replace("{", "")
        $tempstr = $tempstr.Trim()
        if($tempstr.Length -gt 14)
        {
            if($obj.Properties_.Item($Name).CIMType -eq 101)
            {
                [System.String]$tstr = $tempstr.SubString(4, 2)
                $tstr = $tstr + "/"
                $tstr = $tstr + $tempstr.SubString(6, 2)
                $tstr = $tstr + "/"
                $tstr = $tstr + $tempstr.SubString(0, 4)
                $tstr = $tstr + " "
                $tstr = $tstr + $tempstr.SubString(8, 2)
                $tstr = $tstr + ":"
                $tstr = $tstr + $tempstr.SubString(10, 2)
                $tstr = $tstr + ":"
                $tstr = $tstr + $tempstr.SubString(12, 2)
                $tempstr = $tstr
            }
        }
        return $tempstr
    }
    else
    {
        return ""
    }
}

param
(
    Manditory=$True
    $Databasename
)

    $l = new-object -comobject Wbemscripting.SWbemLocator
    $svc = $l.ConnectServer(".", "root\cimv2")
    $svc.Security_.AuthenticationLevel=6
    $svc.Security_.ImpersonationLevel=3
    $ob = $svc.Get("Win32_Process")

    $oaccess = new-object -comobject Access.Application
    $oaccess.CreateCurrentDatabase($DatabaseName, 9)

    $db = $oAccess.CurrentDB()
    $tbldef = $db.CreateTableDef("Processes_Properties")

    foreach($prop in $ob.Properties_)
    {
        $fld = $tbldef.CreateField($prop.Name, 12)
        $fld.AllowZeroLength = $true
        $tbldef.Fields.Append($fld)
    }
    $db.TableDefs.Append($tbldef)
   
    $objs = $ob.Instances_(0)

    $rs = $db.OpenRecordset("Select * From Processes_Properties", Exclusive:=False)
    foreach($obj in $objs)
    {
        $rs.AddNew()
        foreach($prop in $obj.Properties_)
        {
            $rs.Fields($prop.Name).Value = GetValue $prop.Name $obj
        }
        $rs.Update()
    }

Saturday, March 22, 2014

How to acquire a list of special folders

If you were wondering how to acquire a list of special folders, this is an easy way of doing it:

$ws = new-object -comobject wscript.shell
$rt = $ws.SpecialFolders

When you type $rt on the next line:

$rt
And press enter, Powershell will display a list of special folders like this:

C:\Users\Public\Desktop
C:\ProgramData\Microsoft\Windows\Start Menu
C:\ProgramData\Microsoft\Windows\Start Menu\Programs
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
C:\Users\Administrator\Desktop
C:\Users\Administrator\AppData\Roaming
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Templates
C:\Windows\Fonts
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Network Shortcuts
C:\Users\Administrator\Desktop
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\SendTo
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Recent
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Star
C:\Users\Administrator\Favorites
C:\Users\Administrator\Documents
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

Suppose you knew that the special folder for fonts would always be the 9th one -- it is zero based:








$rt.Item(8)
C:\Windows\Fonts

Friday, March 21, 2014

Building Shortcut Scripts Through Automation

Due to popular demand for information on how to create shortcut scripts, I'm wondering if anyone would be interested in a tool that would help you do this?

Please reply if you are interested.

Here's a screenshot of the tool:





Here's the results:


Wednesday, March 19, 2014

How To Run Control Panel Wizzards Using Powershell

Here's a link to a site that shows how to do these using VB6:

http://vbnet.mvps.org/index.html?code/system/controlpnl.htm

To accomplish the same in Powershell, simply copy the command line parameters:

rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,1

And then place quotes around it as shown below:

$ws = new-object -comobject wscript.shell
$ws.Run("rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,1")

Thursday, March 13, 2014

Powershell: How to create an Inputbox

Here's how you can create an InputBox in Powershell:

$Iret = [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$Answer = [Microsoft.VisualBasic.Interaction]::InputBox("Please Enter a language", "Language Selection", "C#")

Powershell: Using Visual Basic's CreateObject

Here's how you can use CreateObject in Powershell:

$Iret = [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$Iret = [Microsoft.VisualBasic.Interaction]::CreateObject("ADODB.Connection")

How To Create A msgbox in Powershell

One of the rather charming features of Powershell is its ability to enable you to use other existing .Net framework languages. I like it because it makes you feel like you aren't giving up on what you already know.

Such is the case with the Msgbox:

$Iret = [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$Iret = [Microsoft.VisualBasic.Interaction]::MsgBox("This works just fine")

How To Create A Messagebox In Powershell

Here's how to create a Messagebox:

$Iret = [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Iret = [System.Windows.Forms.MessageBox]::Show("Hello World")

There you go.