This looks very promising, going to give it a spin tomorrow when I get to work
http://www.lucd.info/2010/05/29/beyond-export-csv-export-xls/
A while back I posted a script that would take whatever input it got, into a sortable HTML table in a file.
Last night my family was here, and they wanted to see the Eurovision song contest thing, so I had some time to rewrite the script into a PowerShell V2 Advanced function, that supports pipeline input.
There are some examples in the code on how to use the function
I do not know what has happened to code highlighter, but it has suddenly decided to mess up the code, so it is not working on the site, so here is a link to the file.
Example of output:
download | new post
Here is my presentation from the 2010 Minasi conference.
Example #1
#Sessions
#Single Session
$Session = New-PSSession -ComputerName "computername"
#Multiple Sessions
$Session = New-PSSession -ComputerName "comp1","comp2".....
#Remove all Sessions
Remove-PSSession *
#Remove Named Session
Remove-PSSession $Session
#Using $session
Invoke-Command {ipconfig} -Session $Session
Enter-PSSession -Session $session
Example #2
$session = New-PSSession -ComputerName "compname"
Invoke-Command {Import-Module ActiveDirectory} -Session $session
Import-PSSession -Session $session -Module ActiveDirectory -Prefix "ctn"
notepad (Get-Module).path
Get-Command *ctn*
Example #1
List users that expires within X days
$DaysToExpire = 14
$MaxPassAge = (Get-QADObject (Get-QADRootDSE).defaultNamingContextDN).MaximumPasswordAge.days
[array]$a = Get-QADUser -Enabled -PasswordNeverExpires:$false -SizeLimit 0 -Email * |Select-Object Name,Email,@{Name="Expires";Expression={ $MaxPassAge - $_.PasswordAge.days }} | where {$_.Expires -lt 0} | Sort-Object expires
Example #2
Locate that Hyper-V Host
Get-QADComputer | Where {$_.OSname -match "2008"} | % { Get-Service -ComputerName $_.Name} | where {$_.Displayname -match "hyper"} | select Machinename, Displayname
#Kirk Munroe pointed out that Hyper-V actually registers ans SCP (Service Connection Point)
Get-QADObject -Name 'Microsoft Hyper-V' -Type serviceConnectionPoint | Get-QADComputer -Identity {$_.ParentContainerDN}
Example #3
Create test users and OU’s in AD
#Gets the default naming context
$RootDN = (Get-QADRootDSE).DefaultNamingContextDN
#Name of OU going to be created in the root of "AD"
$RootOUName = "MinasiTest"
#Create "root" OU
new-qadObject -ParentContainer $RootDN -type 'organizationalUnit' -NamingProperty 'ou' -name $RootOUName
#Create sub OU's, create as many as you like, you only need to change the -name property in the end of the line
new-qadObject -ParentContainer "OU=$RootOUName,$RootDN" -type 'organizationalUnit' -NamingProperty 'ou' -name 'Administrators'
new-qadObject -ParentContainer "OU=$RootOUName,$RootDN" -type 'organizationalUnit' -NamingProperty 'ou' -name 'Marketing'
new-qadObject -ParentContainer "OU=$RootOUName,$RootDN" -type 'organizationalUnit' -NamingProperty 'ou' -name 'Sales'
new-qadObject -ParentContainer "OU=$RootOUName,$RootDN" -type 'organizationalUnit' -NamingProperty 'ou' -name 'IT'
new-qadObject -ParentContainer "OU=$RootOUName,$RootDN" -type 'organizationalUnit' -NamingProperty 'ou' -name 'HR'
#
#
#
#Enter the DN path of the OU you want to add users to
#Note I manually put in the DN of an OU in my test environment, you will have to put one in that exists in your environment
#$OuPath = 'OU=Aprismo Users,DC=aprismo,DC=test'
$OuPath = "OU=$RootOUName,$RootDN"
#Number of users to create in each OU
$No = 5
Function AddUsers
{
param([string]$OUDN, [string]$OUName)
foreach($user in 1..$No)
{
$UserName = "Test$OUName$User"
$UserPassword = "P@ssw0rd123!"
$ExpiresOn = $((Get-Date).AddMonths(1))
$userDescription = "User added for Performance Testing on $(Get-date) and Expires on $ExpiresOn"
$user = New-QADUser -name $UserName `
-SamAccountName $UserName `
-Description $UserDescription `
-ParentContainer $OUDN `
-UserPassword $UserPassword
$user | Set-QADUser -AccountExpires ((Get-Date).AddMonths(1))
}
}
#This foreach loops through all OU's "below" $OUPath
Foreach ($OU in Get-QADObject -SearchRoot $OUPath -Type 'organizationalUnit'){
Addusers $OU.DN $OU.Name
}
Example #4
Rename Groups in AD
Get-QADGroup -Name "xyz*" | %{Set-QADGroup -Identity $_ -SamAccountName ($_.Name).Replace("xyz","abc") -whatif ;Rename-QADObject -Identity $_ -NewName ($_.Name).Replace("xyz","abc") -WhatIf }
Example #5
Output a list of servers in a Excel documents, with ping stats and if the machine is disabled/enabled
#$serverlist = Get-QADComputer -LdapFilter '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' | where {$_.Osname -like "*server*"}
$serverlist = Get-QADComputer -IncludedProperties pwdLastSet -SizeLimit 0 | where {$_.Osname -like "*server*"}
$erroractionpreference = "SilentlyContinue"
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "OS Name"
$c.Cells.Item(1,3) = "IP Address"
$c.Cells.Item(1,4) = "Ping Status"
$c.Cells.Item(1,5) = "Password last set"
$c.Cells.Item(1,6) = "Enabled/Disabled"
$c.Cells.Item(1,7) = "Physical/Virtual"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$intRow = 2
$colComputers = $serverlist
foreach ($strComputer in $colComputers)
{
$c.Cells.Item($intRow, 1) = $strComputer.Name
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strComputer.Name)
if ($Reply.status –eq “Success”)
{
$machineType = Get-WmiObject -ComputerName $strComputer.Name -Class Win32_BIOS
If ($strComputer.AccountIsDisabled) {$enab = "Disabled"} else {$enab = "Enabled"}
if ($strComputer.pwdLastSet -le (Get-Date).AddDays(-90)) {$age = "Older than 90 Days" ; $fgColor = 3} else {$age = "Less than 90 days"; $fgColor = 0}
if ($machineType.Serialnumber -like "*vmware*") {$type = "VMware"}
Elseif ($machineType.Version -like "*VRTUAL*") {$type = "Hyper-V"}
Elseif (!($machineType.Version)) {$type = "N/A"}
else {$type = "Physical"}
$c.Cells.Item($intRow, 2) = $strComputer.OSName
$c.Cells.Item($intRow, 3) = $Reply.Address.ToString()
$c.Cells.Item($intRow, 4) = "Online"
$c.Cells.item($intRow, 5).Interior.ColorIndex = $fgColor
$c.Cells.Item($intRow, 5) = $age
$c.Cells.Item($intRow, 6) = $enab
$c.Cells.Item($intRow, 7) = $type
$Reply = ""
$intRow = $intRow + 1
}
else
{
$machineType = Get-WmiObject -ComputerName $strComputer.Name -Class Win32_BIOS
If ($strComputer.AccountIsDisabled) {$enab = "Disabled"} else {$enab = "Enabled"}
if ($strComputer.pwdLastSet -le (Get-Date).AddDays(-90)) {$age = "Older than 90 Days" ; $fgColor = 3} else {$age = "Less than 90 days"; $fgColor = 0}
if ($machineType.Serialnumber -like "*vmware*") {$type = "VMware"}
Elseif (!($machineType.Version)) {$type = "N/A"}
Elseif ($machineType.Version -like "*VRTUAL*") {$type = "Hyper-V"}
else {$type = "Physical"}
$c.Cells.Item($intRow, 2) = $strComputer.OSName
$c.Cells.Item($intRow, 3) = $Reply.Address.ToString()
$c.Cells.Item($intRow, 4) = "Offline"
$c.Cells.item($intRow, 5).Interior.ColorIndex = $fgColor
$c.Cells.Item($intRow, 5) = $age
$c.Cells.Item($intRow, 6) = $enab
$c.Cells.Item($intRow, 7) = $type
$Reply = ""
$intRow = $intRow + 1
}
$d.EntireColumn.AutoFit()
}
Example #1 (From Lee Holmes’ Powershell cookbook)
“Compile C# code on the fly”
$code =@'
using System.Management.Automation;
[Cmdlet("Write", "InputObject")]
public class MyWriteInputObjectCmdlet : Cmdlet
{
[Parameter]
public string Parameter1;
[Parameter(Mandatory = true, ValueFromPipeline=true)]
public string InputObject;
protected override void ProcessRecord()
{
if (Parameter1 != null)
WriteObject(Parameter1 + ":" + InputObject);
else
WriteObject(InputObject);
}
}
'@
Add-Type -TypeDefinition $code -OutputAssembly .\ExampleModule.dll
Import-Module .\ExampleModule.dll
Example #2 (From Lee Holmes’ Powershell cookbook)
Showing how static functions are available directly
$source = @"
public class BasicTest
{
public static int Add(int a, int b)
{
return (a + b);
}
public int Multiply(int a, int b)
{
return (a * b);
}
}
"@
Add-Type -TypeDefinition $source
[BasicTest]::Add(4, 3)
$basicTestObject = New-Object BasicTest
$basicTestObject.Multiply(5, 2)
Example #3
Access .Net function to move mouse, in order to prevent screensaver from kicking in.
Function Move-Mouse {
param($minutes = 60)
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
}
}
Here are some of the scripts that I used during the demonstration in VA Beach.
Profiles:
Example #1
function prompt
{
"Xenophane " + $(get-location) + ">"
}
Example #2
function prompt
{
"Processes " + (Get-Process).Count+ " " + $(get-location) + "> "
}
Example #3 (Example taken from website)
function Prompt
{
$id = 1
$historyItem = Get-History -Count 1
if($historyItem)
{
$id = $historyItem.Id + 1
}
Write-Host -ForegroundColor DarkGray `n[$(Get-Location)]
Write-Host -NoNewLine PS$id
$host.UI.RawUI.WindowTitle = $(Get-Location)
`b
}
Example #4 (Overdone one)
function prompt
{
[wmi]$Global:Cdrive=Get-WmiObject -query "Select * from win32_logicaldisk where deviceid='c:'"
#Define Cdrive as global variable, which is type cast as a wmi
$processcount=(Get-Process).Count
#Define variable processcount as number of processes running
$cpuload=(Get-WmiObject win32_processor).loadpercentage
#cpuload is defined as a variable
$diskinfoC=" Free C: "+"{0:N2}" -f (($global:Cdrive.freespace/1gb)/($global:cdrive.size/1gb)*100)+"%"
#diskinfoC is defined, {0:N2} is .NET for 2 decimal places, -f is a the "format" property of the string object.
# Then the amount of free space on drive C is divided by the size of drive C multiplies by 100 to get
#the percentage of free space.
$time=Get-WmiObject -class Win32_OperatingSystem
#Define $time is object Win32_OperatingSystem
$t=$time.ConvertToDateTime($time.Lastbootuptime)
#Define #t as the result of the convertion of LastBootuptime into a readable dateTime format.
[TimeSpan]$uptime=New-TimeSpan $t $(get-date)
#Typecast the variable $uptime as a [timespan], the timespan cmdlet in powershell is a way to do date arithmetic in ps
#This way we can compare our variable $t (Which was Lastbootuptime) and the current time Get-date cmdlet
$up="$($uptime.days)d $($uptime.hours)h $($uptime.minutes)m $($uptime.seconds)s"
#define variable $up to display the uptime in days/hours/minuted/seconds
$TextToDisplay="CPU:"+$cpuload+"% Processes:" + $processcount + $diskinfoC+ " " + $diskinfoG+ " "+ ([char]0x25b2)+$up +" "+(Get-Date -format g)
#define one variable that contains all the data we collected so far.
Write-Host -fore red $TextToDisplay
#Write the information to the screen in red
Write-Host "My PoSh:" $(get-location) -nonewline
#Display the regular prompt.
}
I got back from Virgina Beach this past Saturday, after attending a very good conference, where I learned a lot of new an exciting stuff… And of course it was very good to meet up with the “gang” again.
This year I did a presentation on Powershell (wow 1 hour and 20 min goes past fast, when you are having fun)
As the presenter rookie I am, I was not able to time my presentation, so when time was up, even went 10 min over time, I still missed about a third of the presentation. So to make up for that, I will post all the scripts and the prensentation in its entirety, so hope you will find it usefull.
Seems as if Quest has been doing some really cool things with Powershell, from what I can read, they have “rolled” it up as a webservice, meaning that you can now run your Powershell scripts over HTTPS from either you local machine, your phone, anything that supports a newer web browser.
From what I can gather from the manual, you install it on a server running IIS, you set up the site, security etc. Then you can connect to the site from a webbrowser, and you will get a PowerShell commandline in your browser. Combined with Powershell v.2′s remoting features this has the potential of becoming an awesome tool. One of the nice features is that you can save “favourites” in your web sessions, here favourites should be seen as snippets of Powershell code, that you can just click on the run.
So imagine, you have a Powershell script that runs and checks if a particular service is running, if not it does “Something”. You are sitting by the pool drinking a nice cold beer, when you get a call that there is trouble in the office. You pick up you android phone, open up a browser connects to www.whereIWork.com/MyPowerShell, login.. click your Powershell favourite/snippet, and your are done..
If you figure out that did not solve the problem, you just do
Enter-PsSession -Computername <Problematic Servername>, you are now running a Powershell session on the remote server, where you can look around the system, and try to fix the problem, as if you were sitting in front the server, with a Powershell console open.
Can’t wait to I can find some time to get it tested, even thoug it still is in Beta.
I was asked to update my MSTSC util, so here goes.. It will now check for the configuration file and display a message if it is not there, instead of just erroring out.
I have tested it to work on Windows 7
Here is the source code:
#Include <constants .au3>
Opt("TrayOnEventMode",1)
Opt("TrayAutoPause",0)
Opt("TrayMenuMode",1) ; Default tray menu items (Script Paused/Exit) will not be shown.
Global $server[100][3]
$Console = TrayCreateMenu("Console Connect")
$Regular = TrayCreateMenu("Regular Connect")
If FileExists("servers.ini") Then
$data = IniReadSection ( @ScriptDir&"\servers.ini", "servers" )
Else
MsgBox(4096,"No Ini File found","I could not find the servers.ini file, Exiting")
Exit
EndIf
;~ For $i = 1 To $data[0][0]
;~ MsgBox(4096, "", "Key: " & $data[$i][2] & @CRLF & "Value: " & $data[$i][1])
;~ Next
$server[0][0] = $data[0][0]
For $i = 1 to $data[0][0]
$server[$i][0] = TrayCreateItem($data[$i][0], $Console)
TrayItemSetOnEvent(-1, "ServerConsole")
$server[$i][1] = TrayCreateItem($data[$i][0], $Regular)
TrayItemSetOnEvent(-1, "ServerRegular")
$server[$i][2] = $data[$i][1]
Next
TrayCreateItem("")
TrayCreateItem("About")
TrayItemSetOnEvent(-1, "DoAbout")
TrayCreateItem("")
TrayCreateItem("Exit")
TrayItemSetOnEvent(-1, "DoExit")
TraySetState()
While 1
Sleep(100)
WEnd
Func DoAbout()
Msgbox(64,"About:","Tool by Claus T. Nielsen")
EndFunc
Func DoExit()
Exit
EndFunc
Func ServerConsole()
For $i = 1 to $server[0][0]
If $server[$i][0] = @TRAY_ID Then
Run("mstsc -v:"&$server[$i][2]&" /F -admin")
ExitLoop
EndIf
Next
EndFunc
Func ServerRegular()
For $i = 1 to $server[0][0]
If $server[$i][1] = @TRAY_ID Then
Run("mstsc -v:"&$server[$i][2]&" ")
ExitLoop
EndIf
Next
EndFunc
Here is an example on the servers.ini file.
;Server.ini example ; Right side of the Equal sign is the server name/address, ; left side is the name you want displayed ;This files has to be located in the same dir as the .exe file. [Servers] ServerTest 10.0.0.1 = ServerTest ExchangeServer = 10.0.0.2 Fileserver01 = Fileserver01.domain.com
For those of you who trust me, here are two precompiled editions:
64 Bit
32 Bit
EDIT
Sorry about that folks, seems as if there was some trouble with the HTML formatting, some of the quotes had been replaced with “AMP;”, this should be fixed now.

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 