About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).
Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Sunday, November 09, 2014

Powershell Profile Setup and Resize script on startup

1)Setup your profile for powershell: 

if (!(test-path $profile )) 
{new-item -type file -path $profile -force} 

2)Open up the profile:
Notepad $profile
 
3)Cut and paste resize into notepad and save: 
 
##
## Author   : Roman Kuzmin
## Synopsis : Resize console window/buffer using arrow keys
##

function Size($w, $h)
{
    New-Object System.Management.Automation.Host.Size($w, $h)
}

function resize()
{
Write-Host '[Arrows] resize  [Esc] exit ...'
$ErrorActionPreference = 'SilentlyContinue'
for($ui = $Host.UI.RawUI;;) {
    $b = $ui.BufferSize
    $w = $ui.WindowSize
    switch($ui.ReadKey(6).VirtualKeyCode) {
        37 {
            $w = Size ($w.width - 1) $w.height
            $ui.WindowSize = $w
            $ui.BufferSize = Size $w.width $b.height
            break
        }
        39 {
            $w = Size ($w.width + 1) $w.height
            $ui.BufferSize = Size $w.width $b.height
            $ui.WindowSize = $w
            break
        }
        38 {
            $ui.WindowSize = Size $w.width ($w.height - 1)
            break
        }
        40 {
            $w = Size $w.width ($w.height + 1)
            if ($w.height -gt $b.height) {
                $ui.BufferSize = Size $b.width $w.height
            }
            $ui.WindowSize = $w
            break
        }
        27 {
            return
        }
    }
  }
}
 
 
4) Change policy for the profile, exit powershell and open a new version "Run as Administrator":
Set-ExecutionPolicy bypass -Scope CurrentUser
 
 
5) Close powershell and open a new version, type resize.

Friday, October 03, 2008

Some Cool Powershell Commands

A list of useful and fun commands to remember.

1) Using wmiobject

get-wmiobject -list | where {$_.name -like "win32*"} | more
to get a list of classes that provide great information about your computer. Some uses are…


get-wmiobject -class win32_quickfixengineering

(return a history of all patches installed on your computer)


get-wmiobject -class win32_service | where {$_.name -like 'IISADMIN'}

(return if you are running IIS)

2) Using get-childitem

get-childitem c:\ Measure-Object -Character -Word -Line

Lines
-----

89

get-childitem c:\ -force Measure-Object -Character -Word -Line

Lines
-----
141

force hidden files to be visible.

(get-childItem c:\Eftmcon).Count
counting how many items are in a folder.

3) Using select-string and out-string

select-string -path 001460_20081002_1.dat -pattern "2007[0-9]*"
find all lines from a file matching 2007 followed by zero or more numbers and display what that line would look like.

gc crm3.txt | out-string -stream | foreach {$_ -replace "2007","2008"} > text.txt

This will at least replace all 2007 for 2008 and write it out to a file of your choice. Here I use get-content to read in a file in which I then pipe it to out-string to send it out as one string and do my replace.

4) Playing with Merlin

$agent = new-object -com Agent.Control.2
$agent.Connected = 1
$agent.Characters.Load("Merlin")
$merlin = $agent.Characters.Character("Merlin")
$merlin.Show()
$merlin gm

Display Merlin

$merlin.Play("DoMagic1")
Make him animate a move from the $merlin.AnimationNames list

Sources:

Edited: Removed an extra PS in the Merlin.

Edited (10/14/2008): Added the missing "pipes" and "greater than" sign back in, since they were missing.

Tuesday, September 30, 2008

Finding smallest whole number on Google

The Math Factor Podcast was wondering what was the lowest number that Google did not archive.

I figured, a Powershell script would be fun to make to solve this problem. Here is what I wrote so far:

 

clear-variable -name doc
clear-variable -name link
clear-variable -name anchors
clear-variable -name ie
clear-variable -name Notfound

$ie = new-object -com "InternetExplorer.Application"
$Notfound = $true
$i = 1000
$ie.navigate("http://www.google.com/search?hl=en&q=" + $i + "&btnG=Search")
Start-Sleep –s 3

while($Notfound)
{
   $doc = $ie.document

       $anchors = $doc.getElementsByTagName("a")
       "Searching number: " + $i
       $j = $i
       foreach ($link in $anchors)
       {
               if($link.href)
               {
              $link.href
                     if($link.href.StartsWith("http://www.google.com/swr?q="))
                  {
                     $i = $i + 1
                                $ie.navigate("http://www.google.com/search?hl=en&q=" + $i + "&btnG=Search")
                Start-Sleep –s 3
                clear-variable -name doc
                 clear-variable -name link
                clear-variable -name anchors
                  }
               }
       }

        if($j -eq $i)
       {
              $Notfound = $false
              "Number not found: " + $i
       }
}

 

I ran into the problem of my program running to fast, which is why I had to add “Start-Sleep –s 3”. This makes the program wait 3 seconds for google to reply.

The problem with a time delay is, lets assume the number is 1 Million. It would basically take me 34 days to reach the number.

I guess if I has a independent server, I could solve this and let it run for a year.

Thursday, February 28, 2008

Finding all variables and functions in Powershell

To get the list of all the variables or functions that have been declared and pre-existing:

ls variable:*

ls function:*

Note: You can change the wildcard(*) if you are looking for something more specific.

ls can obviously be substituted with dir or get-childitem if you are more familiar with those key-words.

Something Interesting:

If you want to look more closely at what the function is actually doing then you just need to type: $function:<name of function> like so:

$function:mkdir

which will return:

param([string] $name) New-Item $name -type directory

Thursday, February 07, 2008

Signing your PowerShell script

I got an error "File ... cannot be loaded. The file ... is not digitally signed. The script will not execute on the system. Please see "get-help about_signing" for more details.." when starting PowerShell today, after installing the new Windows SDK.

So, I scrambled to find a solution on how to make a certificate and sign it to a PowerShell script. On Scott Hanselman's Blog: http://www.hanselman.com/blog/SigningPowerShellScripts.aspx 
he shows a easy to follow step by step on how to do so.

 

P.S. 

I also had to rest my Home directory.

Tuesday, February 05, 2008

Running Powershell in C#

Found this interesting article on Code Project the other day, on how to run PowerShell scripts from within C#.

http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx

Prerequisites:

Code:

Add a reference System.Management.Automation from C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

Import

using System.Management.Automation;

using System.Collections.ObjectModel;

using System.Management.Automation.Runspaces;

 

Note: I did have to edit his function, to get it to work for me, and also added a try/catch to spew out the error.

private string RunScript(string scriptText)

{

    // create Powershell runspace

    Runspace runspace = RunspaceFactory.CreateRunspace();

 

    // open it

    runspace.Open();

 

   // create a pipeline and feed it the script text

   Pipeline pipeline = runspace.CreatePipeline();

   pipeline.Commands.AddScript(scriptText);

 

   // add an extra command to transform the script output objects into nicely formatted strings

   // remove this line to get the actual objects that the script returns. For example, the script

   // "Get-Process" returns a collection of System.Diagnostics.Process instances.

   pipeline.Commands.Add("Out-String");

 

   // execute the script

   Collection<PSObject> results = new Collection<PSObject>();

   try

   {

      results = pipeline.Invoke();

   }

   catch (Exception ex)

   {

      results.Add(new PSObject((object)ex.Message));

   }

 

 

   // close the runspace

   runspace.Close();

 

   // convert the script result into a single string

   StringBuilder stringBuilder = new StringBuilder();

   foreach (PSObject obj in results)

   {

       stringBuilder.AppendLine(obj.ToString());

   }

 

   return stringBuilder.ToString();

}

 

Technorati Tags: ,,,

Monday, January 28, 2008

Some Unix commands for PowerShell

I've been playing with PowerShell a little and decided to make some Unix commands that were not ported over.

 

Command Function
whoami

function whoami
{  [System.Security.Principal.WindowsIdentity]::GetCurrent().Name       
}

~ (works better if it was not an alias)

function ~
{
   $home
}

mkdir

function mkdir([string] $name)
{
   New-Item $name -type directory
}

touch

function touch([string] $path = ".\", [string] $name)
{
   $file = $path + $name
   $result = test-path $file
   if($result -eq $true)
   {
      ##"Changing LastWriteTime"
      gci $file | foreach{$_.lastwritetime = $(get-date)}
   }
   else
   {
      ##"Creating new file"
      new-item $file -type file
   }
}

find (still currently working on this one. I need to implement wild cards)

function find([string] $name = "", [string] $ext = "", [string] $drive = "C:")
{
   $computer = "."
   if($name -ne "")
   {
      $files = get-wmiobject -computer $computer cim_datafile -filter "FileName = '$name'"
   }
   if($ext -ne "")
   {
      $files = get-wmiobject -computer $computer cim_datafile -filter "Extension = '$ext'"
   }

   $files | add-member --type PropertySet "FindInfo" ([string[]]("Name","FileType","Extension","CreationDate")) -force
   $files | select FindInfo | ft -wrap
}

 

I figured re-writing Unix commands might help me learn powershell. I'm going to use http://en.wikibooks.org/wiki/Guide_to_UNIX/Commands as source of basic Unix commands to implement.

Wednesday, January 16, 2008

How to make a new command in Windows PowerShell

Lets say you have a idea for a new function that you would like to implement in Window's PowerShell. In this case I made a Unix like whoami command:

function whoami
{
     [System.Security.Principal.WindowsIdentity]::GetCurrent().Name       
}

when in PowerShell it returned for me: mss/wandrus. Simple enough. Now to get the command to be usable every time an new PowerShell is opened.

 

Type within PowerShell:  Get-Variable profile | Format-List

This should give you the information on what file and directory path are needed to place your custom scripts. In this case I was given:

C:\Document and Settings\wandrus\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

 

Which meant that I had to create a new folder (WindowsPowerShell) and a new script file in notepad (Microsoft.PowerShell_profile.ps1) where I've place my function.

Monday, December 17, 2007

Powershell and BizTalk

One of the jobs I hated when doing support was going through the process of stopping and starting services then re-sending data through biztalk. I think with the power of PowerShell, you now can automate all of these tedious tasks into one simple cmdlet. (get-help *-service should be a good start)

Powershell is a really nice feature and I believe anyone that has any basic UNIX/Linux knowledge should be able to pick up the basics real quick.