Creating and using custom objects

1 11 2007

Listener Mace writes:

I’ve seen this code:

$values = new-object ‘object[,]’ 5,2

Can you expound on that?

The author fills the array.
$k = 0
foreach ($j in $exchangeserverlist)
{
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values[$k,0] = $j.Name
$values[$k,1] = $perf.RawValue
$k = $k + 1
}

Now, how do you sort the array based on the performance data in the second
column?

I’m guessing there’s a more “powershell” was of doing what’s needed rather
than resorting to arrays. E.g.,
$p = get-process
$p | sort-object ws

How would you create a collection of custom objects. Each custom object
would have two custom properties “exchangeserver” and “perfdata”.
{create the custom collection — somehow}
$co | sort-object perf
<!–[if !supportLineBreakNewLine]–>

Here is my response:

Hal taught me a cool way to create custom objects that he learned from PowerShell MVP Brandon Shell. Here’s a link to the post.

 

Here’s the code you may want to try…

 

$k = 0
$co = $(foreach ($j in $exchangeserverlist)
{

$values = “” | Select-Object server,perf # this is where your custom object is created
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values .server = $j.Name #populating custom object

$values.perf = $perf.RawValue #populating custom object
$k = $k + 1

$values

})

$co | sort-object perf

 

 

Jaykul on IRC helped me figure out that you need to create the custom object in the loop. I tried to do it outside the loop and it didn’t work the way I wanted it to.

 

Or you could use this method that Hal suggested

$k = 0
$co = @() # this creates an empty array

 

foreach ($j in $exchangeserverlist)
{

$values = “” | Select-Object server,perf # this is where your custom object is created
$perf = New-Object System.Diagnostics.PerformanceCounter($perfobj1,
$counter1, $instance1, $j.Name)
$values .server = $j.Name #populating custom object
$values.perf = $perf.RawValue #populating custom object
$k = $k + 1
$co += $values # this populates the array

})

$co | sort-object perf

Thanks for listening!

Jonathan





Get free disk space one-liner

31 10 2007

Listener Bill writes,

I have been looking at the get-help and get-member cmdlets, but have so far not found one thing I want to have as a “one-liner” – a command line that will return the free space on a certain drive.

“`”${env:computername}`”,`”” + (gwmi -Query “SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = ‘C:'”).FreeSpace / 1GB + ‘”‘ | sc my.csv

Got kinda ugly with the quote escaping. I’ll explain…

The concept here is to, in one line, build a string and then write it to a log file. First I write a quote to the string, because I chose to create it in CSV style. Had to escape it using the backtick ` character. Then I snag the computername from the env: virtual drive (or PSProvider). I had to use the curly braces around it because during variable substitution inside of a string, the colon can be a delimiter for setting scope on a variable so I wanted to tell it explicitly not to do that. We talk about this in Episode 11. Then more quotes and commas for the CSV format. Then I do a Get-WmiObject call. I felt like being fancy so I used a WQL query string which looks a lot like SQL. The query said to grab just one property from the Win32_LogicalDisk class where the ID is “C:”. Then access that property and divide it by 1 GB and add a closing quote. Pipe the whole thing to Set-Content and Bob’s your uncle.

Having said that, I wouldn’t do it this way. But it would work, I tested it.

Keep the feedback, and questions coming!

-hal





Episode 11 – A new PowerShell community

27 10 2007

A Podcast about Windows PowerShell.

Listen:

Introduction

News

  • PowerShell Community (powershellcommunity.org)
    • “Real” non-profit organization created by corporate sponsors including Microsoft, Quest, Sapien, and ShellTools.
    • Event calendar, blog hosting, forums, etc.
    • Still under construction.
  • PowerShell Central (powershellcentral.com)
    • Hosted by BSonPosh and lots of help contributed by Jaykul.
    • “All PowerShell bloggers” aggregate news feed, very cool script repository, news, etc.
    • Still under construction.
  • Relaunch and refocus of Powershell Live (ShellTools) as well as a new developer blog. New features in development like context menus for collections and pipelines.

Resources

Tips

Cmdlet of the week

  • Write-Verbose
      • Use in parameter section of functions and combine with an If statement to enable or disable verbose logging.

    Function Get-Foo {
    Param ( [switch] $Verbose )
    If ($Verbose) { $VerbosePreference = “Continue” }
    Write-Verbose “My verbose stuff goes here
    Write-Verbose “
    and is not seen at all unless”
    Write=Verbose “I supply the -verbose switch”
    }

One-Liners

  • write-verbose “$(Get-Date -f ‘s’) my log entry goes here”

Gotchas

  • Problems occur when a brackets “[” are in your filenames.
  • Careful with following the $_ automatic variable by a colon
    • Out-Host “This $_:won’t work right.”
    • Out-Host “This ${_}:will.”

Thanks for listening! We love feedback and news tips, you can send them to powerscripting@gmail.com. Join our Facebook group “PowerScripting Podcast”.





Episode 10 – WinRM will power PowerShell Remoting in V2

13 10 2007

A Podcast about Windows PowerShell.

Listen:

Introduction

  • We’ve had over 5,400 downloads so far! Thanks, everyone!

News

  • PowerShell remoting will work via WinRM according to thisfrom the Scripting NewsWire
    • “Something else to consider. Sometime before the end of the year an upgraded CTP (Community Technology Preview) version of Windows PowerShell will be released, an upgrade that will enable you to run most Windows PowerShell cmdlets against remote computers. The catch? This new version of Windows PowerShell also relies on WinRM as its remote transport protocol. If you’re interested in using Windows PowerShell to manage remote computers you’ll need to download and install WinRM on your Windows XP and Windows Server 2003 machines.”
  • New Blog: PowerShell Pro
    • “PowerShell Pro is a community devoted to compiling the leading resources needed in achieving that goal. Whether you are an advanced PowerShell user or just starting out, PowerShell Pro is dedicated to presenting information required for your success.”
    • Lots of content. Nice format.
  • Powershell “Yahoo Pipe”created by Jaykul.
    • Aggregate RSS feed containing articles from tons of PowerShell blogs.
  • Another company “Gets it”: IBM
    • Dale Lane in the UK has written on his blog about PowerShell Cmdlets he’s developing for IBM WebSphere.
  • Overview of next PS Virtual User’s Group – Dec 4th
    • Oisin presenting talk about cmdlet development, new foundations in pscx, and touching on providers
      and paths in PowerShell

Cmdlet of the week: Set-PSDebug

Check out Keith Hill’s article on Set-PSDebug: Effective PowerShell Item 5: Use Set-PSDebug -Strict In Your Scripts – Religiously

  • dynamic languages like PS allow you to use a variable without initializing it
  • equivalent to “option explicit” in Vbscript
  • ERROR: set-psdebug -strict; $foo += “bar”
  • NO ERROR: $foo = “hello” ; $foo += “bar”

Resources

Tips

  • Hal talks about working with CSV and other forms of structured text.
  • Source: Import-WebCsv
# Import a URL as CSV and write output to pipeline
Function Import-WebCsv {
    Param ( $url )

    $tempFile = [System.IO.Path]::GetTempFileName()
    $webClient = new-object System.Net.WebClient
    $webClient.DownloadFile($url,$tempFile)
    $data = import-csv $tempFile
    [System.IO.File]::Delete($tempFile)
    write-output $data
}

PowerShell Moments

  • “netsh dhcp server \SERVERNAME scope SCOPEID add reservedip 10.10.0.1
    00c0ffee0001″
  • $vms = import-csv ipandmacs.csv
    $vms | % {“netsh dhcp server \myserver scope myscope ” + $_.IP + ” “+ $_.Mac} | out-file createdhcpreservations.cmd
  • There is a bigip.conf file that for nodes at least looks like this
  • node 10.10.10.1 {
    limit 1
    }
    the limit has to do with how many connections per host you can have.
    Well i banged out this config file using Powershell 1..216 | % {“node 10.10.10.” + $_ + ” {`n   limit 1`n}”} | out-file
    bigipconf.txt – Thanks Andy!

One-Liners

  •  $ErrorActionPreference = “silentlycontinue”
  • gc scott.txt | %{$u=$_; trap {“$u,deleted”} if(get-qaduser $_ -disabled){“$_,disabled”}else{“$_,active”}} | out-file “User Status.csv”

Gotchas

Closing

Thanks for listening! Keep the feedback coming, we really love hearing from you. Also don’t forget to write reviews and vote for us on iTunes, Podcast Alley and wherever else you may find us.





Episode 9 – PowerShell V2 news is coming in November

29 09 2007

A Podcast about Windows PowerShell.

Listen:

Introduction

  • Thanks to /\/\o\/\/ and Kirk at Poshoholic for mentioning us on their blogs. We loved Kirk’s post about namespaces with the Star Trek references.  That’s the Trouble with Tribbles!

News

  • According to Bruce Payette in this post, details of PowerShell V2’s upcoming features will be released in November at ITForum!
  • From $hay@Israel’ s blog: There is a new book titled “Windows PowerShell in Practice” that is being worked on by Jim Truher and /\/\o\/\/.  It will be published by Manning and will cover topics such as, the PowerShell SDK (writing cmdlets, providers etc) advanced scripting techniques and domain specific examples.
  • Citrix, Citrix, and more Citrix!  Brandon Shell has gifted us with a veritable cornucopia of sixteen (16!) Citrix management functions such as:
    • Get-CitrixFarm
    • Publish-CitrixApplication
  • Keith Hill and /\/\o\/\/ will be a guest speaker in the first Windows PowerShell Virtual User Group Meeting (From Marco Shaw’s blog)
  • Phoul from the #Powershell IRC channel has a new blog up(http://insecure-complexity.com/).  In his own words:
    • “Especially to the new PowerShell users. I’m writing a blog that will be focused around my findings in my experience learning PowerShell. It will have scripts and tutorials and some neat tips n tricks after I get a little more acquainted with PowerShell. For now it has a profile example and a useful script for signing your scripts.”

Cmdlet of the week

  • We were going to do Set-PSDebug but Hal didn’t do his homework.  Instead, we gave the royal treatment to Get-Service!

Resources – Got a ton for ya this week:

Tips

  • PowerShell is a scripting engine AND a shell
    • Don Jones had an article about this in Technet (October Issue) when it comes out online it should be here
    • Don Jones Technet article “Scripting One Line at a Time”.  This talks about how you go about building a script based on the interactive nature of PowerShell
  • $profile discussion part 2
    1. Gather your reusable bits into functions. Since they may be shared, be sure to comment them well.
    2. Categorize these functions by type.
    3. Organize each category of functions into a unique .PS1 file. I recommend prepending the filenames with “lib-” or similar.
    4. Place all the files in your profile directory, or on a file server, and dot-source them in your profile using something like this:

# place in your profile to load shared scripts
New-Psdrive -name Scripts -Psprovider FileSystem -root \\server\scripts
Get-ChildItem Scripts:lib-*.ps1 | Foreach-Object { . $_ }

Powershell Moments

  • Hal shares his frustration having to work with an NT 4.0 domain and how many ADSI queries don’t work against it, even if he uses the WinNT addressing scheme, as opposed to LDAP.
  • Jonathan shares how easy the Quest cmdlets make it to “copy” users from one domain to another. His code was similar to this:
    • Connect-QADService -service ‘domain.dev’
    • $users – GetQADUser -SearchRoot ‘OU=Users,DC=domain,DC=dev’
    • Disconnect-QADService
    • Connect-QADService -service ‘domain.tst’
    • $users | %{new-qaduser -name $_.Name -ParentContainer ‘OU=Users,DC=domain,DC=tst’ -SamAccountName $_.LogonName -description $_.description -displayname $_.DisplayName -firstName $_.firstname -lastname $_.lastname -UserPrincipalName $_.name}

One-liners

# extract part of a filename

dir | Foreach-Object { $_.name.substring(0,8) }

Gotchas

  • From Poshoholic– If you convert any string to a boolean value in PowerShell, the resulting boolean value will be boolean True.  (With the exception of empty strings, which are $false.)

Powershell challenge

  • Hal asked if anyone knows how to set SACLs on remote files.  Not file ACLs but security auditing stuff.  Turns out it might be much easier than he thought (using set-acl on a UNC path), but if you’ve got any code to share that’s great!

Thanks for listening!  Keep the feedback coming, we really love hearing from you.  Also don’t forget to write reviews and vote for us on iTunes, Podcast Alley and wherever else you may find us.





Episode 8 – Meet Hal Rottenberg!

18 09 2007

A Podcast about Windows PowerShell.

 Thanks for listening! Please send us you feedback.





Episode 7 – Don’t Forget What You Already Know

3 09 2007

A Podcast about Windows PowerShell.

  • Can you use -match instead of -eq?  Jeffery Snover’s blog post.

Whenever you find yourself using –EQ, ask yourself if that is really want you want. You might be cheating yourself out of a ton great stuff. “

  • Don’t forget what you already know    
    • $u = “user”; net localgroup administrators | where {$_ -match $u}
  • Scott Hanselman’s blog post about finding out if a user is in the local admin group

  • Gotchas

 

  • Powershell challenge
    • out-file $profile -noclobber -append -input `n’function sub($x,$y){$x – $y}’

 Thanks for listening!





Episode 6 – User Groups are Starting to Sprout

26 06 2007

A Podcast about Windows PowerShell.

    • Introduction
    • News
    • PowerShell Analyzer can be pre-ordered for $59 and it will be $129
    • Next update new-qaduser will require samAccountname
    • “The PowerShell Guy” wants to start a Dutch PowerShell User group http://shrinkster.com/q3r
    • Marco Shaw wants to start a Canadian PowerShell User Group http://shrinkster.com/q3s – cool blog with some interesting PS stuff
    • Don Jones said he has podfaded
    • Cmdlets of the week
    • Copy-item
    • Clear-content
    • Get-alias
    • Resources
    • From Pawel  a good article on Processing XML with PowerShell http://shrinkster.com/pzc
    • Also from Pawel  “I have the Step-by-Step book it is not too good still better than Powershell for Absolute Begineers “
    • German book that Pawel will pronounce for us

    • Kevin found a PowerShell gadget for Vista (sidebar) –

 

PowerShell Gadget is a small gadget that hosts the PowerShell console window in your Sidebar. Commands can be entered straight into the collapsed gadget or, by clicking on the PowerShell icon, the complete PowerShell console is available.

http://shrinkster.com/q3o

 

      • Technet Radio podcast “Review of Server Management in Windows Server 2008” – http://shrinkster.com/q4r (direct link to mp3 file)
      • Tips
        • The default user profile is stored in $profile, it does not exist by default
        • test-path $profile will tell you if the profile exists
        • you can open the profile quickly with PS> notepad $profile

 

    • One-Liners
      • new-item -path $profile -itemtype file -force – to create a profile
      • copy $profile “$env:userprofile\my documents\” – back up your profile
    • Gotchas
      • PowerShell challenge answers discussed in Episode 5 do not check for an explicit deny (thanks Pavel!)
      • Some PowerShell graphical help tools like the one from Sapien and the one from The Scripting Guys may have an issue where in the examples the script blocks are not surrounded by {}
    • Powershell challenge
      • Create a function and add it to your profile from within PowerShell (Warning: back up your profile first!)
    • Feedback
      • PowerScripting (@) gmail (.) com
      • Voicemail line 206-202-0377
      • add a comment to this post

 

Thanks for listening!





Episode 5 – PowerShell Hits a Million

8 06 2007

A Podcast about Windows PowerShell.

  • Introduction
    • Shout-out to Mark Allen for answering the challenge
  • News
    • New AD cmdlets – the one step account creation works great
    • From the ScriptingNewswire, May 2007
      • Windows PowerShell guide for beginners
      • Downloadable and cmdlet-accessible graphical help for Windows PowerShell

  • Gotchas
    • New-QADUser
    •  Make sure you set the samAccountName and the UPN




Episode 4 – Get Data and Format the Output

25 05 2007

A Podcast about Windows PowerShell.

News

  • New PowerShell book in the works “Windows PowerShell: The Definitive Guide” by Lee Holmes’ (a developer on the PowerShell team) from O’Reilly they have an early access program http://shrinkster.com/p8l
  • Windows Server 2008
  • AD Cmdlets 1.0.2 released – http://shrinkster.com/p8e
    • Support for Vista and Server 2008
    • You now have the ability to create enabled user accounts
    • Dmitry’s PowerBlog – http://shrinkster.com/p8d

Cmdlets of the week

  • Get-content (GC, type, cat)
  • Format-List (FL)
  • Format-Table(FT)

Resource

  • Free PowerShell ebook
    • Published by Microsoft Switzerland and recently translated into English due to it’s great popularity
    • Subtitle is “An introduction to scripting technologies for people with no real background knowledge”
    • 44 pages
    • http://shrinkster.com/pau

Tips

  • Get started now, jump in – PowerShell is your hammer and you are looking for nails
  • Go through the free manual, work the labs

One-liners

  • $time = [datetime]::now
  • $time | gm   there is a method called addDays
  • $time.addDays(-90)
  • [datetime]::now.addDays(-90)  – we are calling the static member “Now” from the type literal [datetime]  to see this use [datetime] | gm -static  you will see things like “now” and “today”
  • or you could use (get-date).adddays(-90)

Powershell challenge

  • Use PowerShell to find all of the files or folders in the current directory where System does not have Full Control

 








Design a site like this with WordPress.com
Get started