Posts RSS Comments RSS 117 Posts and 170 Comments till now

Archive for March, 2007

C# to PowerShell Translation Thought Process

A gentleman on the powershell news group the other day was asking about executing SQL stored procedures and I provided him with example that I had posted earlier in my blog (Click Here) While I’m not sure my answer was exactly what he was looking for he was a little curious as to how I went about translating the original C# code. To be clear I am not a coder nor do I truly know C#, but I know enough to translate. Anyway, I decided this would be a good idea for a post

So… Here we GO!

First… I used this as the C# example
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

I will show you my thought process by section I will include my comments and after I will post Both code Sections

This was fairly simple. In C# you have the ability to take namespace shortcuts by using ‘using ;’ In PowerShell we dont as of yet have that ability so I had to figure out what class SqlConnection was. A MSDN query returned System.Data.SqlClient.SqlConnection. The resulting PowerShell code is

The C# Code:

  1. // Setup
  2. conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
  3. conn.Open();

The Powershell Code:

  1. $srv = "srv1"
  2. $db = "Northwind"
  3. $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv;DataBase=$db;IntegratedSecurity=SSPI")
  4. $conn.Open() | out-null # The out-null is because the method returns a value and I dont want that output

Again… I had to find out what SqlCommand was referencing so… back to MSDN… System.Data.SqlClient.SqlCommand. BTW… I think I should take time now to tell you it is a REALLY GOOD idea to get use to the idea of constructors (how the object should be created) and how to use MSDN to determine the correct way to create an instance of the class/object. It really helps to know what a class is expecting. In this example its good to know the constructor is wanting a string of the SP and A connection OBJECT to use.

The C# Code:

  1. // 1.  create a command object identifying
  2. //     the stored procedure
  3. SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

Here is the PowerShell Code:

  1. $cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)

Here was the tricky part (at least sorta.) From the C# code its not clear if the CommandType.StoredProcedure is a property and it turns out its not. It is an enumeration. It took me a few clicks to figure it out. The first clue was when looking for CommandType… I got an enum and it turns out the valid options was StoredProcedure, TableDirect, or Text (MSDN LINK) Clearly this was an enum, but I was a little unsure how do to enums in powershell. I found this blog by /\/\0\/\/ that helped a lot (/\/\o\/\/ Link)

The C# Code:

  1. // 2. set the command object so it knows
  2. //    to execute a stored procedure
  3. cmd.CommandType = CommandType.StoredProcedure;

I ended up with this Powershell Line:

  1. $cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’

This was fairly simple as well… Just had to drop the new sqlparameter because strongly typing was not required. Again the out-null was because the method returns data I did not want as well as set the parameters.

The C# Code:

  1. // 3. add parameter to command, which
  2. //    will be passed to the stored procedure
  3. cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

The PowerShell Code:

  1. $cmd.Parameters.Add("@CustomerID","ANATR") | out-Null

These two parts are really just the excution of the the previous code. I think the only difference is the way PowerShell Writes output

The C# Code:

  1. // execute the command
  2. rdr = cmd.ExecuteReader();
  3.  
  4. // iterate through results, printing each to console
  5. while (rdr.Read())
  6. {
  7.  Console.WriteLine(
  8.  "Product: {0,-35} Total: {1,2}",
  9.  rdr["ProductName"],
  10.  rdr["Total"]);
  11. }

The Powershell Code:

  1. $rdr = $cmd.ExecuteReader()
  2. While($rdr.Read()){
  3.     Write-Host "Product Name: " $rdr[‘ProductName’]
  4.     Write-Host "Total: " $rdr[‘Total’]
  5. }

Here is the Complete PowerShell Code.

  1. $srv = "srv1"
  2. $db = "Northwind"
  3. $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv1;DataBase=$db;Integrated Security=SSPI")
  4. $conn.Open() | out-null
  5. $cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)
  6. $cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’
  7. $cmd.Parameters.Add("@CustomerID","ANATR") | out-Null
  8. $rdr = $cmd.ExecuteReader()
  9. While($rdr.Read()){
  10.     Write-Host "Product Name: " $rdr[‘ProductName’]
  11.     Write-Host "Total: " $rdr[‘Total’]
  12. }
  13. $conn.Close()
  14. $rdr.Close()

Kill-UserProcess (my first whatif Script)

There was a post on the forums about Killing all the processes for a user so I decided to write a script for it… sounded like something I could use. I thought about using get-process or [System.Diagnostics.Process] for remoting, but instead I went with WMI.

Below is the script and here are some example usages

Get User Processes on Server
PS> kill-userProcess -server Serverx -user jloser
Get User Processes on Server and Kill using -whatif
PS> kill-userProcess -server Serverx -user jloser -kill -whatif
Get User Processes on Server and kill them
PS> kill-userProcess -server Serverx -user jloser -kill
Get User Process on Server Kill/Whatif
PS> kill-userProcess -server Serverx -user jloser -process explorer.exe -kill -whatif
Get User Process on Server just kill
PS> kill-userProcess -server Serverx -user jloser -process explorer.exe -kill

[code]
function Kill-UserProcess{
param([string]$server,[string]$user,[string]$process,[switch]$Kill,[switch]$whatif)
if($server){$processes = Get-WmiObject Win32\_Process -ComputerName $server}
else{$processes = Get-WmiObject Win32\_Process}
if($user){
if($kill){if(!$process){Write-Host “Killing all Processes for User [$user]“}}
foreach($p in $processes){
if($p.GetOwner().user -match “$user”){
if($process){
if($p.Name -match “$process”){
if($kill){
Write-Host “Killing Process [$($p.Name)] for User [$user]”
if($whatif){
write-Host “What if: Performing operation “”kill”" on Target “”$($p.Name)”".”
}
}
else{
Write-Host “Killing Process $($p.Name)”
$p.Terminate() | out-null
}
return $true
}
}
if($kill){
if($whatif){
write-Host “What if: Performing operation “”kill”" on Target “”$($p.Name)”".”
}
else{
Write-Host “Killing Process $($p.Name)”
$p.Terminate() | out-Null
}
}
else{
Write-Host “$p.Name”
}
}
}
}
}
[/code]