#requires -version 2.0 <# ----------------------------------------------------------------------------- Script: Get-NumberObject.ps1 Version: 1.0 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 11/18/2011 Keywords: Comments: sample usage: get-numberobject 6 get-numberobject 42 -custom {Param($x) [math]::Pow(10,$x)} 1..5 | get-numberobject Get-NumberObject 2,4,6,8 | select Number,Log "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> Function Get-NumberObject { Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter an number greater than 0", ValueFromPipeline=$True)] [alias("x")] [ValidateScript({$_ -gt 0})] [object[]]$Number, [scriptblock]$Custom ) Begin { Function Test-IsEven { Param($x) if ($x%2 -eq 0) { $True } else { $False } } #Test-IsEven Function Test-IsPrime { #http://www.wikihow.com/Check-if-a-Number-Is-Prime Param($x) if ($x -eq 1) { Write $False } Else { $Prime=$True for ($i=2;$i -le ([math]::Sqrt($x));$i++) { $z=$x/$i if ($z -is [int]) { $Prime=$False Break } } #for Write $Prime } #else } #test-isprime } #begin Process { foreach ($N in $number) { #define a hash table of values from some math operations $hash=@{ Number=$N Square=($N*$N) Cube=[math]::Pow($N,3) Sqrt=[math]::Sqrt($N) Log=[math]::Log($N) Sine=[math]::Sin($N) Cosine=[math]::Cos($N) Tangent=[math]::Tan($N) CircleArea=[math]::PI*($N*$N) Inverse=1/$N IsEven=(Test-IsEven $N) IsPrime=(Test-IsPrime $N) Exp=[math]::Exp($N) Factorial= (1..$N |foreach -begin {$r=1} -process {$r*=$_} -end {$r}) Factors=(1..$N | where {$N/$_ -is [int]}) } #if a custom calculation was passed, invoke it and add the value to the hash table if ($Custom) { $hash.Add("Custom",(Invoke-Command -ScriptBlock $custom -ArgumentList $N)) } #use the hash tables as proprties for an object $obj=New-Object -TypeName PSObject -Property $hash #let's add some methods $obj | Add-Member -MemberType ScriptMethod -Name ToBinary -value {[convert]::ToString($this.number,2)} $obj | Add-Member -MemberType ScriptMethod -Name ToOctal -value {[convert]::ToString($this.number,8)} $obj | Add-Member -MemberType ScriptMethod -Name ToHex -value {[convert]::ToString($this.number,16)} -PassThru } #foreach } #process End { #this is not used } } #end function Set-Alias -Name gno -Value Get-NumberObject