Thursday, July 31, 2014

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