Tuesday, April 26, 2011

Scripting Games 2011 Advanced Category: final result 4th

Well, finally I'm the 4th in these Scripting Games 2011 Advanced Category competition. Just after Glenn Sizemore, one of "VMware vSphere PowerCLI Reference: Automating vSphere Administration" author

http://blogs.technet.com/b/heyscriptingguy/archive/2011/04/25/final-results-winners-for-the-2011-scripting-games-advanced-category.aspx

Sunday, April 24, 2011

The 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files

The 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files

My personal script:
http://2011sg.poshcode.org/1811
Average Rating: 5.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

Function CreateTempFile {
<#
.SYNOPSIS
Create temp file
.DESCRIPTION
create temp file then return filename
.PARAMETER encoding
write file in encoding format
You can use: "Unicode", "UTF7", "UTF8", "UTF32", "ASCII","BigEndianUnicode", "Default","OEM"
"Default" = ANSI format / Default parameter = "Default"
.PARAMETER notepad
display temp file in notepad after creation
.EXAMPLE
"hahaha" | CreateTempFile
write "hahaha" in a temp file and return filename
.EXAMPLE
"hohoho" | CreateTempFile -notepad
write "hohoho" in a temp file and display it in notepad then return filename
.EXAMPLE
dir C:\ | CreateTempFile -encoding unicode
write directory of c:\ in a temp file in unicode format then return filename
#>
Param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeLine = $true)]
[psobject] $inputdata,

[Parameter(Mandatory = $false, Position = 1)]
[ValidateSet("Unicode", "UTF7", "UTF8", "UTF32", "ASCII","BigEndianUnicode", "Default","OEM")]
[string] $Encoding="Default",

[Parameter(Mandatory = $false, Position = 2)]
[switch]$notepad,
[Switch]$Whatif
)

# temp file name
# use windows IO function but can use %temp%\(get-date).ToString('yyyyMMdd')
$tempfile = [System.IO.Path]::GetTempFileName()

# create temp file
Write-Debug "Create Temp file $tempFile"
Write-Verbose "Create Temp file $tempFile"
if ($Whatif) {
Write-Host "What if: Create Temp file $tempFile"
} else {
Out-File -filePath $tempFile -InputObject $inputdata -Encoding unicode
}

# open temp file in notepad if switch
if ($notepad) {
Write-Debug "Open file $tempFile in notepad"
Write-Verbose "Open file $tempFile in notepad"
if ($Whatif) {
Write-Host "What if: Open file $tempFile in notepad"
} else {
Notepad $tempFile | Out-Null
}
}

# return temp filename
Write-Debug "return tempfile name"
Write-Verbose "return tempfile name"
if ($Whatif) {
Write-Host "What if: return $tempFile"
return
} else {
return $tempfile
}
}

The 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username

The 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username

My personal script:
http://2011sg.poshcode.org/1781
Average Rating: 3.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $string = "My log",

[Parameter(Mandatory = $false, Position = 1)]
[ValidateNotNullOrEmpty()]
[String] $foldername = "HSGLogFiles",

[Parameter(Mandatory = $false, Position = 2)]
[ValidateNotNullOrEmpty()]
[switch] $mydoc
)

<#
.SYNOPSIS
Create log file
.DESCRIPTION
create filename (YYYYMMDD_username.log) in
.PARAMETER string
String to write Default: "My log"
.PARAMETER foldername
Folder name to write Default: "HSGLogFiles"
.PARAMETER path
path where write foldername Default: "CommonApplicationData"
.PARAMETER mydoc
switch to write in my document's directory / replace path folder
.EXAMPLE
CreateLogFile
write file C:\ProgramData\HSGLogFiles\20110420_franck.log
(if we are april 20 2011 and my username is franck in Windows 7)
.EXAMPLE
CreateLogFile -mydoc
write file %userprofile%\Documents\HSGLogFiles\20110420_franck.log
(if we are april 20 2011 and my username is franck)
#>



# if switch mydoc write directory on my document's folder
if ($mydoc) {
$path = [Environment]::GetFolderPath("MyDocuments") + "\" + $foldername
} else {
$path = [Environment]::GetFolderPath("CommonApplicationData") + "\" + $foldername

}


# Create directory if not already exist
if (!(Test-Path -path $path)) {
New-Item $path -type directory | Out-Null
}


# create filename (YYYYMMDD_username.log) if not already exist
$filename = (get-date).ToString('yyyyMMdd') + "_" + ($env:USERNAME) + ".log"
If ((Test-Path("$path\$filename")) -eq $False){
"Log file" | Out-File "$path\$filename"
}

The 2011 Scripting Games Advanced Event 8: Use PowerShell to Remove Metadata and Resize Images

The 2011 Scripting Games Advanced Event 8: Use PowerShell to Remove Metadata and Resize Images

My personal script:
http://2011sg.poshcode.org/1714
Average Rating: 5.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 8: Use PowerShell to Remove Metadata and Resize Images
#
# by F.Richard 2011-04
#
#
# Windows form Generated By: SAPIEN Technologies, Inc., PrimalForms 2009
#

#Requires -Version 2.0



# Gloval variables for preferences
$global:ImageFolder = ""
$global:SaveFolder =""



#----------------------------------------------

function Select-Directory() {
param(
[string] $folder = ""
)
# Solution 1 : System.Windows.Forms.FolderBrowserDialog
# but requires STA (Single Threaded Apartment) mode to function correctly (that means -sta switch)
# or
# Solution 2 : COM object
# http://stackoverflow.com/questions/216817/call-folderbrowserdialog-from-powershell#217527
#
$app = New-Object -COM Shell.Application
$directory = $app.BrowseForFolder( 0, "Select Directory", 0 ) # , $folder
$path = $directory.Self.Path
if( $path ) { return $path }
}




function Set-FilesToListbox() {
param(
[string] $folder = (Split-Path -parent $MyInvocation.MyCommand.Path)
)
$listboxFile.Items.Clear()
# only files # where{!($_.PSISContainer)})
ForEach ($File in Get-ChildItem "$folder\*" -include *.bmp, *.tif, *.tiff, *.gif, *.jpg, *.jpeg, *.png ) {
$listboxFile.Items.Add($File.Name) | Out-Null
}

}


function Get-XMLpreferences() {
$defaultfolder = (Get-Location).Path
if (Test-Path($defaultfolder + "\" + "preferences.xml")) {
$xml = New-Object XML
$xml.Load($defaultfolder + "\" + "preferences.xml")
$lbImageFolder.Text = $xml.Preferences.ImageFolder
Set-FilesToListbox -folder $xml.Preferences.ImageFolder
$lbSaveFolder.Text = $xml.preferences.SaveFolder
} else {
$lbImageFolder.Text = $defaultfolder
Set-FilesToListbox -folder $defaultfolder
$lbSaveFolder.Text = $defaultfolder
}
$global:ImageFolder = $lbImageFolder.Text
$global:SaveFolder = $lbSaveFolder.Text



}



function Set-XMLpreferences() {
$defaultfolder = (Get-Location).Path

$xml = New-Object XML
$xmlroot = $xml.CreateElement("Preferences")
$xml.AppendChild($xmlroot) | Out-Null

$imagefolder = $xml.CreateElement("ImageFolder")
$ImageFolder.PSBase.InnerText = $global:ImageFolder
$xmlroot.AppendChild($ImageFolder) | Out-Null

$savefolder = $xml.CreateElement("SaveFolder")
$savefolder.PSBase.InnerText = $global:Savefolder
$xmlroot.AppendChild($savefolder) | Out-Null

$xml.Save($defaultfolder + "\" + "preferences.xml")
}



function Resize-Image() {
param(
[Array] $files
)
foreach ($file in $files) {
$imagefile = $lbImageFolder.Text + "\" + $file
$OldBitmap = [System.Drawing.Image]::FromFile($imagefile)
$width = [int]($OldBitmap.Width * (1/2))
$height = [int]($OldBitmap.Height * (1/2))
$NewBitmap = New-Object System.Drawing.Bitmap($width,$height)
$graphic=[System.Drawing.Graphics]::FromImage($NewBitmap)
$graphic.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphic.DrawImage($OldBitmap, 0, 0, $width, $height) # resize

$savefile = $lbSaveFolder.Text + "\SHARE_" + $file
if (Test-Path($savefile)) {
Remove-Item ($savefile)
}
$NewBitmap.Save($savefile, ([System.Drawing.Imaging.ImageFormat]::jpeg))
$NewBitmap.Dispose()
$OldBitmap.Dispose()
}
[System.Windows.Forms.MessageBox]::Show("Resize Done","Resize")

}


function Resize-ImageKeepMetadata() {
# with this function we keep metada

param(
[Array] $files
)
foreach ($file in $files) {
$image = New-Object -ComObject Wia.ImageFile
$image.LoadFile($file)
$width = $image.Width * (1/2)
$height = $image.Height * (1/2)

$filter = New-Object -ComObject Wia.ImageProcess
$scale = $filter.FilterInfos.Item("Scale").FilterId
$filter.Filters.Add($scale)
$filter.Filters.Item(1).Properties.Item("PreserveAspectRatio") = $True
$filter.Filters.Item(1).Properties.Item("MaximumWidth") = $width
$filter.Filters.Item(1).Properties.Item("MaximumHeight") = $height

$image = $filter.Apply($image.PSObject.BaseObject)
$savefile = $lbSaveFolder.Text + "\SHARE_" + $file
if (Test-Path($savefile)) {
Remove-Item ($savefile)
}
# $image.SaveFile($savefile)
$image = $null
$filter = $null
}
[System.Windows.Forms.MessageBox]::Show("Resize Done","Resize")

}




#----------------------------------------------
#region Application Functions
#----------------------------------------------

function OnApplicationLoad {
#Note: This function runs before the form is created
#Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
#Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
#Important: Form controls cannot be accessed in this function
#TODO: Add snapins and custom code to validate the application load

return $true #return true for success or false for failure
}

function OnApplicationExit {
#Note: This function runs after the form is closed
#TODO: Add custom code to clean up and unload snapins when the application exits

# Save program preferences
Set-XMLpreferences

$script:ExitCode = 0 #Set the exit code for the Packager
}

#endregion

#----------------------------------------------
# Generated Form Function
#----------------------------------------------
function GenerateForm {

#----------------------------------------------
#region Import Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
#endregion

#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$formMain = New-Object System.Windows.Forms.Form
$btPrepareToShareAll = New-Object System.Windows.Forms.Button
$rtbMetadata = New-Object System.Windows.Forms.RichTextBox
$listboxFile = New-Object System.Windows.Forms.ListBox
$btPrepareToShare = New-Object System.Windows.Forms.Button
$lbSaveFolder = New-Object System.Windows.Forms.Label
$btSaveFolder = New-Object System.Windows.Forms.Button
$pictbox = New-Object System.Windows.Forms.PictureBox
$lbImageFolder = New-Object System.Windows.Forms.Label
$btImageFolder = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
# User Generated Script
#----------------------------------------------


$FormEvent_Load={
# Load program preferences
Get-XMLpreferences

}

$handler_btImageFolder_Click={
$oldFolder = $lbImageFolder.Text
$newFolder = Select-Directory -folder $oldFolder
if ($newFolder) {
$lbImageFolder.Text = $newFolder
Set-FilesToListbox -folder $newFolder
}
$global:ImageFolder = $newFolder

}

$handler_btSaveFolder_Click={
$oldFolder = $lbSaveFolder.Text
$newFolder = Select-Directory -folder $oldFolder
if ($newFolder) {
$lbSaveFolder.Text = $newFolder
}
$global:SaveFolder = $newFolder

}

$handler_listboxFile_SelectedIndexChanged={
#TODO: Place custom script here
$file = $lbImageFolder.Text + "\" + $listboxFile.Text
$pictbox.Image = [System.Drawing.Image]::Fromfile($file)

$image = New-Object -ComObject Wia.ImageFile
$image.LoadFile($file)

# use EXIF quick reference
# http://nicholasarmstrong.com/2010/02/exif-quick-reference/
# and Display Detailed Image Information / Shared Samples
# http://msdn.microsoft.com/en-us/library/ms630826%28v=vs.85%29.aspx
$content = ""
$content += "Height: " + $image.Height + "`n"
$content += "Width: " + $image.Width + "`n"
$content += "Depth: " + $image.PixelDepth + "`n"
$content += "HorizontalResolution : " + $image.HorizontalResolution + "`n"
$content += "VerticalResolution : " + $image.VerticalResolution + "`n"
$content += "FrameCount : " + $image.FrameCount + "`n"
if ($image.IsIndexedPixelFormat) { $content += "Pixel data contains palette indexes" + "`n" }
if ($image.IsAlphaPixelFormat) { $content += "Pixel data has alpha information" + "`n" }
if ($image.IsExtendedPixelFormat) { $content += "Pixel data has extended color information (16 bit/channel)" + "`n" }
if ($image.IsAnimated) { $content += "Image is animated" + "`n" }
if ($image.Properties.Exists("271")) { $content += "Equipment Maker:" + $image.Properties.Item("271").Value + "`n" }
if ($image.Properties.Exists("272")) { $content += "Equipment Model:" + $image.Properties.Item("272").Value + "`n" }
$orientation = @{ 1 = "Horizontal"; 3 = "Rotate 180 degrees"; 6 = "Rotate 90 degrees clockwise" ; 8 = "Rotate 270 degrees clockwise" }
if ($image.Properties.Exists("274")) { $content += "Orientation:" + $orientation[[int]$image.Properties.Item("274").Value] + "`n" }
if ($image.Properties.Exists("282")) { $content += "X Resolution:" + $image.Properties.Item("282").Value.Value + "`n" }
if ($image.Properties.Exists("283")) { $content += "Y Resolution:" + $image.Properties.Item("283").Value.Value + "`n" }
$unit = @{ 1 = "None"; 2 = "Inches"; 3 = "Centimetres" }
if ($image.Properties.Exists("296")) { $content += "Resolution Unit:" + $unit[[int]$image.Properties.Item("296").Value] + "`n" }
if ($image.Properties.Exists("306")) { $content += "Modified Date Time:" + $image.Properties.Item("306").Value + "`n" }
if ($image.Properties.Exists("33434")) { $content += "Exposure Time:" + $image.Properties.Item("33434").Value.Value + "`n" }
if ($image.Properties.Exists("33437")) { $content += "F Number:" + $image.Properties.Item("33437").Value.Value + "`n" }
if ($image.Properties.Exists("34855")) { $content += "ISO Speed:" + $image.Properties.Item("34855").Value + "`n" }
if ($image.Properties.Exists("36867")) { $content += "Date Taken:" + $image.Properties.Item("36867").Value + "`n" }
if ($image.Properties.Exists("36868")) { $content += "Date Created:" + $image.Properties.Item("36868").Value + "`n" }
if ($image.Properties.Exists("37377")) { $content += "Shutter Speed:" + $image.Properties.Item("37377").Value.Value + "`n" }
if ($image.Properties.Exists("37378")) { $content += "Aperture:" + $image.Properties.Item("37378").Value.Value + "`n" }
if ($image.Properties.Exists("37380")) { $content += "Exposure Compensation:" + $image.Properties.Item("37380").Value.Value + "`n" }
if ($image.Properties.Exists("37381")) { $content += "Maximum Aperature:" + $image.Properties.Item("37381").Value.Value + "`n" }
$metering = @{ 0 = "Unknown"; 1 = "Average"; 2 = "Center-weighted average" ; 3 = "Spot"; 4 = "Multi-spot"; 5 = "Multi-segment"; 6 = "Partial"; 255 = "Unknown" }
if ($image.Properties.Exists("37383")) { $content += "Metering Mode:" + $metering[[int]$image.Properties.Item("37383").Value] + "`n" }
$flash = @{ 0 = "No Flash"; 10 = "Flash off"; 1 = "Flash on"; 11 = "Flash auto" }
if ($image.Properties.Exists("37385")) { $content += "Flash:" +$image.Properties.Item("37385").Value + "`n" }
if ($image.Properties.Exists("37386")) { $content += "Equipment Maker Note:" + $image.Properties.Item("37386").Value.Value + "`n" }
if ($image.Properties.Exists("37510")) { $content += "User Comment:" + $image.Properties.Item("37510").Value.Value + "`n" }
if ($image.Properties.Exists("40961")) { $content += "Color Space:" + $image.Properties.Item("40961").Value + "`n" }
if ($image.Properties.Exists("40962")) { $content += "Pixel X Dimension:" + $image.Properties.Item("40962").Value + "`n" }
if ($image.Properties.Exists("40963")) { $content += "Pixel Y Dimension:" + $image.Properties.Item("40963").Value + "`n" }
if ($image.Properties.Exists("41486")) { $content += "Focal Plane X Resolution:" + $image.Properties.Item("41486").Value + "`n" }
if ($image.Properties.Exists("41487")) { $content += "Focal Plane Y Resolution:" + $image.Properties.Item("41487").Value + "`n" }
$focal = @{ 1 = "None"; 2 = "Inches"; 3 = "Centimetres" ; 4 = "Millimetres"; 5 = "Micrometres" }
if ($image.Properties.Exists("41488")) { $content += "Focal Plane Resolution Unit:" + $focal[[int]$image.Properties.Item("41488").Value] + "`n" }
$sensing = @{ 1 = "Not defined"; 2 = "One-chip colour area"; 3 = "Two-chip colour area" ; 4 = "Three-chip colour area"; 5 = "Colour sequential area"; 7 = "Trilinear"; 8 = "Colour sequential linear" }
if ($image.Properties.Exists("41495")) { $content += "Sensing Method:" + $sensing[[int]$image.Properties.Item("41495").Value] + "`n" }
$filesrc = @{ 1 = "Film scanner"; 2 = "Reflection print scanner"; 3 = "Digital camera" }
if ($image.Properties.Exists("41728")) { $content += "File Source:" + $filesrc[[int]$image.Properties.Item("41728").Value] + "`n" }
$custrender = @{ 0 = "Normal"; 1 = "Custom" }
if ($image.Properties.Exists("41985")) { $content += "Custom Rendered:" + $custrender[[int]$image.Properties.Item("41985").Value] + "`n" }
$exposure = @{ 0 = "Auto"; 1 = "Manual"; 2 = "Auto Bracket" }
if ($image.Properties.Exists("41986")) { $content += "Exposure Mode:" + $exposure[[int]$image.Properties.Item("41986").Value] + "`n" }
$white = @{ 0 = "Auto"; 1 = "Manual" }
if ($image.Properties.Exists("41987")) { $content += "White Balance:" + $white[[int]$image.Properties.Item("41987").Value] + "`n" }
if ($image.Properties.Exists("41988")) { $content += "Digital Zoom Ratio:" + $image.Properties.Item("41988").Value + "`n" }
if ($image.Properties.Exists("41989")) { $content += "Focal Length in 35 mm Format:" + $image.Properties.Item("41989").Value + "`n" }
$scene = @{ 0 = "Standard"; 1 = "Landscape"; 2 = "Portrait"; 3 = "Night" }
if ($image.Properties.Exists("41990")) { $content += "Scene Capture Type:" + $scene[[int]$image.Properties.Item("41990").Value] + "`n" }
$gain = @{ 0 = "None"; 1 = "Low gain up"; 2 = "High gain up"; 3 = "Low gain down"; 4 = "High gain down" }
if ($image.Properties.Exists("41991")) { $content += "Gain Control:" + $gain[[int]$image.Properties.Item("41991").Value] + "`n" }
$contrast = @{ 0 = "Normal"; 1 = "Low"; 2 = "High" }
if ($image.Properties.Exists("41992")) { $content += "Contrast:" + $contrast[[int]$image.Properties.Item("41992").Value] + "`n" }
$saturation = @{ 0 = "Normal"; 1 = "Low"; 2 = "High" }
if ($image.Properties.Exists("41993")) { $content += "Saturation:" + $saturation[[int]$image.Properties.Item("41993").Value] + "`n" }
$sharpness = @{ 0 = "Normal"; 1 = "Soft"; 2 = "Hard" }
if ($image.Properties.Exists("41994")) { $content += "Sharpness:" + $sharpness[[int]$image.Properties.Item("41994").Value] + "`n" }
$sdr = @{ 0 = "Unknown"; 1 = "Macro"; 2 = "Close" ; 3 = "Distant" }
if ($image.Properties.Exists("41996")) { $content += "Subject Distance Range:" + $sdr[[int]$image.Properties.Item("41996").Value] + "`n" }
$image = $null
$rtbMetadata.Lines = $content
}

$handler_btPrepareToShareAll_Click={
$files = @( )
for ($i = 0; $i -lt $listboxFile.items.count; $i++) {
$files += $listboxFile.items.item($i)
}
Resize-Image -files $files
}

$handler_btPrepareToShare_Click={
$files = @( )
#foreach ($objItem in $listboxFile.SelectedItems) {$files += $objItem} # for MultiExtended
$files += $listboxFile.Text
Resize-Image -files $files

}

#----------------------------------------------
# Generated Events
#----------------------------------------------

$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$formMain.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
#
# formMain
#
$formMain.Controls.Add($btPrepareToShareAll)
$formMain.Controls.Add($rtbMetadata)
$formMain.Controls.Add($listboxFile)
$formMain.Controls.Add($btPrepareToShare)
$formMain.Controls.Add($lbSaveFolder)
$formMain.Controls.Add($btSaveFolder)
$formMain.Controls.Add($pictbox)
$formMain.Controls.Add($lbImageFolder)
$formMain.Controls.Add($btImageFolder)
$formMain.ClientSize = New-Object System.Drawing.Size(792,573)
$formMain.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$formMain.Name = "formMain"
$formMain.Text = "Image Resizer"
$formMain.add_Load($FormEvent_Load)
#
# btPrepareToShareAll
#
$btPrepareToShareAll.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btPrepareToShareAll.Location = New-Object System.Drawing.Point(17,538)
$btPrepareToShareAll.Name = "btPrepareToShareAll"
$btPrepareToShareAll.Size = New-Object System.Drawing.Size(184,23)
$btPrepareToShareAll.TabIndex = 9
$btPrepareToShareAll.Text = "Prepare to Share All Image"
$btPrepareToShareAll.UseVisualStyleBackColor = $True
$btPrepareToShareAll.add_Click($handler_btPrepareToShareAll_Click)
#
# rtbMetadata
#
$rtbMetadata.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200)
$rtbMetadata.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$rtbMetadata.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$rtbMetadata.Location = New-Object System.Drawing.Point(438,69)
$rtbMetadata.Name = "rtbMetadata"
$rtbMetadata.ReadOnly = $True
$rtbMetadata.Size = New-Object System.Drawing.Size(342,492)
$rtbMetadata.TabIndex = 8
$rtbMetadata.Text = ""
#
# listboxFile
#
$listboxFile.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$listboxFile.FormattingEnabled = $True
$listboxFile.Location = New-Object System.Drawing.Point(17,69)
$listboxFile.Name = "listboxFile"
#$listboxFile.SelectionMode = [System.Windows.Forms.SelectionMode]::MultiExtended
$listboxFile.Size = New-Object System.Drawing.Size(400,134)
$listboxFile.TabIndex = 6
$listboxFile.add_SelectedIndexChanged($handler_listboxFile_SelectedIndexChanged)
#
# btPrepareToShare
#
$btPrepareToShare.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btPrepareToShare.Location = New-Object System.Drawing.Point(233,538)
$btPrepareToShare.Name = "btPrepareToShare"
$btPrepareToShare.Size = New-Object System.Drawing.Size(184,23)
$btPrepareToShare.TabIndex = 5
$btPrepareToShare.Text = "Prepare to Share Selected Image"
$btPrepareToShare.UseVisualStyleBackColor = $True
$btPrepareToShare.add_Click($handler_btPrepareToShare_Click)
#
# lbSaveFolder
#
$lbSaveFolder.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
$lbSaveFolder.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lbSaveFolder.Location = New-Object System.Drawing.Point(156,39)
$lbSaveFolder.Name = "lbSaveFolder"
$lbSaveFolder.Size = New-Object System.Drawing.Size(624,23)
$lbSaveFolder.TabIndex = 4
#
# btSaveFolder
#
$btSaveFolder.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btSaveFolder.Location = New-Object System.Drawing.Point(17,39)
$btSaveFolder.Name = "btSaveFolder"
$btSaveFolder.Size = New-Object System.Drawing.Size(133,23)
$btSaveFolder.TabIndex = 3
$btSaveFolder.Text = "Select Save Folder"
$btSaveFolder.UseVisualStyleBackColor = $True
$btSaveFolder.add_Click($handler_btSaveFolder_Click)
#
# pictbox
#
$pictbox.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
$pictbox.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$pictbox.Location = New-Object System.Drawing.Point(17,220)
$pictbox.Name = "pictbox"
$pictbox.Size = New-Object System.Drawing.Size(400,300)
$pictbox.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
$pictbox.TabIndex = 2
$pictbox.TabStop = $False
#
# lbImageFolder
#
$lbImageFolder.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
$lbImageFolder.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lbImageFolder.Location = New-Object System.Drawing.Point(156,11)
$lbImageFolder.Name = "lbImageFolder"
$lbImageFolder.Size = New-Object System.Drawing.Size(624,23)
$lbImageFolder.TabIndex = 1
#
# btImageFolder
#
$btImageFolder.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btImageFolder.Location = New-Object System.Drawing.Point(17,11)
$btImageFolder.Name = "btImageFolder"
$btImageFolder.Size = New-Object System.Drawing.Size(133,23)
$btImageFolder.TabIndex = 0
$btImageFolder.Text = "Select Image Folder"
$btImageFolder.UseVisualStyleBackColor = $True
$btImageFolder.add_Click($handler_btImageFolder_Click)
#endregion Generated Form Code

#----------------------------------------------

#Save the initial state of the form
$InitialFormWindowState = $formMain.WindowState
#Init the OnLoad event to correct the initial state of the form
$formMain.add_Load($Form_StateCorrection_Load)
#Show the Form
return $formMain.ShowDialog()

} #End Function


# Test WIA is installed by testing if "%WINDIR%\system32\wiaaut.dll" exist and
$testWIA = New-Object -ComObject Wia.ImageFile
if ($testWIA -eq $isnull) {
Write-Host "Windows Image Acquisition Library dll seems to be not registered"
Exit
}
$wiafile = "$env:WINDIR\system32\wiaaut.dll"
if (!(Test-Path($wiafile))) {
Write-Host "Windows Image Acquisition Library dll $wiafile is installed but not registered. Run this next commandline to registered it:"
Write-Host "regsvr32 C:\windows\system32\wiaaut.dll"
Exit
}



#Call OnApplicationLoad to initialize
if(OnApplicationLoad -eq $true)
{
#Create the form
GenerateForm | Out-Null

#Perform cleanup
OnApplicationExit
}


The 2011 Scripting Games Advanced Event 7: Map User's Names and Twitter Names with PowerShell

The 2011 Scripting Games Advanced Event 7: Map User's Names and Twitter Names with PowerShell

My personal script:
http://2011sg.poshcode.org/1528
Average Rating: 3.50 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 7: Map User's Names and Twitter Names with PowerShell
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $url = "http://www.sqlsaturday.com/70/networking.aspx",

[Parameter(Mandatory = $false, Position = 1, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $output = "TwitterName.csv"
)




# Get-WebPage
# Windows PowerShell, Invalid Certificates, and Automated Downloading
#http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/25/windows-powershell-invalid-certificates-and-automated-downloading.aspx
# + some personal modifications
Function Get-WebPage {
<#
.Synopsis
Gets the content at a specified http url
.Parameter url
Url that returns content
.Parameter file
Optional parameter that redirects download of content to a file. If left out
content is returned as a string
.Parameter useragent
to define user agent
.Parameter user
user to permit connection
.Parameter password
password to permit connection
.Parameter domain
user's domain to permit connection
.Parameter proxyurl
proxy Url to permit connection
.Parameter proxyurl
proxy port to permit connection
.Parameter force
Forces the acceptance of content from an untrusted source (eg. invalid certificate)
.EXAMPLE
Get-WebPage -url "http://www.mysite.com"
return web page mysite.com
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -user "usr" -password "pass" -domain "mydom"
return web page mysite.com using particular user
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -file "contentsite.htm" -proxyurl "proxy.comp.net" -proxyport "8080"
return web page mysite.com to file "contentsite.htm" using proxy proxy.comp.net:8080
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -useragent "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
return web page mysite.com using specific user agent
#>
Param(
[string] $url,
[string] $file = "",
[string] $useragent = "",
[string] $user = "",
[string] $password = "",
[string] $domain = "",
[string] $proxyurl = "",
[string] $proxyport = "",
[switch] $force
)
if($force) {
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
}

$webclient = New-Object system.net.webclient
#Proxy required
if ($proxyurl -ne "" -or !$webClient.Proxy.IsBypassed($url)) {
$proxy = New-Object System.Net.WebProxy($proxyurl, $proxyport)
#$proxy.Credentials = (Get-Credential).GetNetworkCredential()
$webclient.Proxy = $proxy
}
if ($useragent -ne "") {
$webclient.Headers.Add("user-agent", $useragent) # :ex "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
}

if ($user -ne "") {
$webclient.Credentials = New-Object System.Net.NetworkCredential($user, $password, $domain)
}
$webClient.UseDefaultCredentials = $true

if ($file -eq "") {
return $webclient.DownloadString($url)
} else {
$webclient.DownloadFile($url, $file)
}
}



Function Get-RegexName {
<#
.Synopsis
return array of captured regex group
.Parameter content
content to capture
.Parameter regex
regular expression with group to capture
#>
Param(
[string] $content,
[string] $regex,
[string] $regexaction = "match",
[string] $regexoptions = "IgnoreCase"
)
$arrName = @( )
$matches = [regex]::Matches($content, $regex, $regexoptions)
foreach($match in $matches) {
if ($match.Groups["name"].Value.Trim().length -gt 0) {
$arrName += $match.Groups["name"].Value.Trim()
}
}
return $arrName
}


Function Get-TwitterToUser {
<#
.Synopsis
return user name from twitter name using csv file
.Parameter file
csv file
#>
Param(
[string] $file
)
$hashTwitterToUser = @{ }
Import-Csv $output | ForEach-Object { $hashTwitterToUser[$_.twitname] = $_.username }

return $hashTwitterToUser
}


Function Get-UserToTwitter {
<#
.Synopsis
return twitter name from user name using csv file
.Parameter file
csv file
#>
Param(
[string] $file
)
$hashUserToTwitter = @{ }
Import-Csv $output | ForEach-Object { $hashUserToTwitter[$_.username] = $_.twitname }

return $hashUserToTwitter
}



Function Get-TwitterName {
<#
.Synopsis
write all twitter name from a web page to a .csv file
.Parameter url
url to examine default: "http://www.sqlsaturday.com/70/networking.aspx"
.Parameter output
outup filename default: "TwitterName.csv"
#>

[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $url = "http://www.sqlsaturday.com/70/networking.aspx",

[Parameter(Mandatory = $false, Position = 1, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $output = "TwitterName.csv"
)
# Get web page content to file
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
$content = Get-WebPage -url $url -file "$strCurDir\temp.txt" -force
$content = Get-Content "$strCurDir\temp.txt"
Remove-Item "$strCurDir\temp.txt"

[Array] $arrTwitUserName = @( )
# get all twitter name
# must use (?!:) trick to do not have line like this one
# a href="http://www.twitter.com/http://twitter.com/sqlvariant
$regex = "]*>(?.*?)"
$arrTD = Get-RegexName -content $content -regex $regex
foreach ($td in $arrTD) {
# get only user name and a href ref
$td_simplified = [regex]::Replace($td, "<[/]?(font|span|img|[ovwxp]:\w+)[^>]*?>", "$1", "IgnoreCase")

# Get Twitter name
$regex = "twitter.com/(?[^?/ ]*)\b(?!:)"
$twitname = Get-RegexName -content $td_simplified -regex $regex
if ($twitname) {
# Get username
$username = [regex]::Replace($td_simplified, "<[/]?(a|[ovwxp]\w+)[^>]*?>", "$1", "IgnoreCase")

# create new object
$obj = New-Object PSObject
$obj | Add-Member -MemberType noteproperty -Name "twitname" -Value $twitname.Trim()
$obj | Add-Member -MemberType noteproperty -Name "username" -Value $username.Trim()
$arrTwitUserName += $obj
}
}


# Write file
$arrTwitUserName | Export-Csv $output -NoTypeInformation

}

# main
Get-TwitterName -url $url -output $output

# test to user name from twitter name from csv file
$hashTwitterToUser = Get-TwitterToUser -file $output
Write-host "test Get-TwitterToUser: 'gunnyek' real name is"$hashTwitterToUser["gunneyk"]

# test to return user name from twitter name from csv file
$hashUserToTwitter = Get-UserToTwitter -file $output
Write-host "test Get-TwitterToUser: 'David Taylor' twitter name is"$hashUserToTwitter["David Taylor"]

The 2011 Scripting Games Advanced Event 6: Use PowerShell to Get Twitter Names from a Web Page

The 2011 Scripting Games Advanced Event 6: Use PowerShell to Get Twitter Names from a Web Page

My personal script:
http://2011sg.poshcode.org/1518
Average Rating: 4.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 6: Use PowerShell to Get Twitter Names from a Web Page
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $url = "http://www.sqlsaturday.com/70/networking.aspx",

[Parameter(Mandatory = $false, Position = 1, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $output = "TwitterName.txt",

[Parameter(Mandatory = $false, Position = 2, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $regex = "twitter.com/(?[^?/ ]*)\b(?!:)"
)





# Get-WebPage
# Windows PowerShell, Invalid Certificates, and Automated Downloading
#http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/25/windows-powershell-invalid-certificates-and-automated-downloading.aspx
# + some personal modifications
Function Get-WebPage {
<#
.Synopsis
Gets the content at a specified http url
.Parameter url
Url that returns content
.Parameter file
Optional parameter that redirects download of content to a file. If left out
content is returned as a string
.Parameter useragent
to define user agent
.Parameter user
user to permit connection
.Parameter password
password to permit connection
.Parameter domain
user's domain to permit connection
.Parameter proxyurl
proxy Url to permit connection
.Parameter proxyurl
proxy port to permit connection
.Parameter force
Forces the acceptance of content from an untrusted source (eg. invalid certificate)
.EXAMPLE
Get-WebPage -url "http://www.mysite.com"
return web page mysite.com
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -user "usr" -password "pass" -domain "mydom"
return web page mysite.com using particular user
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -file "contentsite.htm" -proxyurl "proxy.comp.net" -proxyport "8080"
return web page mysite.com to file "contentsite.htm" using proxy proxy.comp.net:8080
.EXAMPLE
Get-WebPage -url "http://www.mysite.com" -useragent "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
return web page mysite.com using specific user agent
#>
Param(
[string] $url,
[string] $file = "",
[string] $useragent = "",
[string] $user = "",
[string] $password = "",
[string] $domain = "",
[string] $proxyurl = "",
[string] $proxyport = "",
[switch] $force
)
if($force) {
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
}

$webclient = New-Object system.net.webclient
#Proxy required
if ($proxyurl -ne "" -or !$webClient.Proxy.IsBypassed($url)) {
$proxy = New-Object System.Net.WebProxy($proxyurl, $proxyport)
#$proxy.Credentials = (Get-Credential).GetNetworkCredential()
$webclient.Proxy = $proxy
}
if ($useragent -ne "") {
$webclient.Headers.Add("user-agent", $useragent) # :ex "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
}

if ($user -ne "") {
$webclient.Credentials = New-Object System.Net.NetworkCredential($user, $password, $domain)
}
$webClient.UseDefaultCredentials = $true

if ($file -eq "") {
return $webclient.DownloadString($url)
} else {
$webclient.DownloadFile($url, $file)
}
}



Function Get-RegexName {
<#
.Synopsis
return array of captured regex group
.Parameter content
content to capture
.Parameter regex
regular expression with group to capture
#>
Param(
[string] $content,
[string] $regex,
[string] $regexaction = "match",
[string] $regexoptions = "IgnoreCase"
)
$arrName = @( )
$matches = [regex]::Matches($content, $regex, $regexoptions)
foreach($match in $matches) {
if ($match.Groups["name"].Value.Trim().length -gt 0) {
$arrName += $match.Groups["name"].Value.Trim()
}
}
return $arrName
}



Function Get-TwitterName {
<#
.Synopsis
write all twitter name in a web page
.Parameter url
url to examine default: "http://www.sqlsaturday.com/70/networking.aspx"
.Parameter output
outup filename default: "TwitterName.txt"
.Parameter regex
regular expression with group to capture default: "twitter.com/(?[^?/ ]*)\b(?!:)"
#>

[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $url = "http://www.sqlsaturday.com/70/networking.aspx",

[Parameter(Mandatory = $false, Position = 1, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $output = "TwitterName.txt",

[Parameter(Mandatory = $false, Position = 2, ValueFromPipeLine = $False, ValueFromPipelineByPropertyName = $False)]
[ValidateNotNullOrEmpty()]
[String] $regex = "twitter.com/(?[^?/ ]*)\b(?!:)"
)
# Get web page content
$content = Get-WebPage -url $url -force

# get all twitter name
# must use (?!:) trick to do not have line like this one
# a href="http://www.twitter.com/http://twitter.com/sqlvariant
$arrTwitName = Get-RegexName -content $content -regex $regex

# Write file
$arrTwitName | Out-File $output

}




# main
Get-TwitterName -url $url -output $output -regex $regex

The 2011 Scripting Games Advanced Event 5: Use PowerShell to Determine Upgrade to Windows 7 Eligibility

The 2011 Scripting Games Advanced Event 5: Use PowerShell to Determine Upgrade to Windows 7 Eligibility

My personal script:
http://2011sg.poshcode.org/1130
Average Rating: 4.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 5: Use PowerShell to Determine Upgrade to Windows 7 Eligibility
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String[]] $computername = $Env:COMPUTERNAME

)




Function Get-ComputerInfos {
<#
.SYNOPSIS
Get Computer informations
.DESCRIPTION
Use PowerShell to get computer informations
.PARAMETER computername
computer name ex: mycomputer default:localhost
.EXAMPLE
Get-ComputerInfos
get localhost computer information
.EXAMPLE
.EXAMPLE
Get-ComputerInfos mycomputer
get mycomputer computer information
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $computername = $Env:COMPUTERNAME
)
trap [Exception] {
write-host
write-error $("TRAP: " + $_.Exception.GetType().FullName)
write-error $("TRAP: " + $_.Exception.Message)
continue;
}

$objParent = New-Object PSObject

# Get CPU speed and architectuure
$wmicpus = Get-WmiObject -Class "Win32_Processor" -ComputerName $computername -Property MaxClockSpeed
Foreach($wmicpu in $wmicpus){
$debug = "CPUspeed: " + $wmicpu.MaxClockSpeed
Write-Debug $debug
$objParent | Add-Member -MemberType noteproperty -Name "CPUspeed" -Value $wmicpu.MaxClockSpeed
break
}

# "Win32_ComputerSystem" TotalPhysicalMemory NOT report correct information -> use Win32_PhysicalMemory Capacity sum
$capacity = (Get-WmiObject Win32_PhysicalMemory -ComputerName $computername -Property Capacity | measure-object Capacity -sum).Sum/1MB
Write-Debug "RAMCapacity: $capacity"
$objParent | Add-Member -MemberType noteproperty -Name "RAMCapacity" -Value $capacity

# Get all size drives
$sizedrives = Get-WmiObject -Class "Win32_DiskDrive" -ComputerName $computername -Property Size | Select Size
Write-Debug "sizedrives: $sizedrives"
$objParent | Add-Member -MemberType noteproperty -Name "objDrive" -Value $sizedrives

# solution 1: get microsoft site compatibility list then regex html
# http://www.microsoft.com/windows/compatibility/windows-7/en-us/Search.aspx?type=Hardware&category=Graphics%20Cards%20%26%20Components&compat=all&os=32-bit&s=asus%207800&l=en-us
# solution 2: use dxdiag command with invoke-command
# start /wait dxdiag /whql:off /t -> generate dxdiag.txt -> line DirectX Version: DirectX 9.0c (4.09.0000.0904)
# solution 3: use remote registry
$Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername)
$RegKey = $Registry.OpenSubKey("Software\Microsoft\DirectX\" )
$directxversion = $RegKey.GetValue("Version")
$objParent | Add-Member -MemberType noteproperty -Name "directxversion" -Value $directxversion
# DirectX 9.0 "4.09.0000.0900" to test if >= 9 then test 4 first letter "4.09"
# else can use switch version but then i need exactly all directx version
if ($directxversion.substring(0,4) -ge "4.09") {
$directx = 9
} else {
$directx = 0
}
Write-Debug "DirectX: $directx"
$objParent | Add-Member -MemberType noteproperty -Name "directx" -Value $directx

return $objParent
}




# Test-IsAdministrator
# http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/25/use-powershell-to-add-local-users-to-local-groups.aspx
Function Test-IsAdministrator {
    <#
    .Synopsis
        Tests if the user is an administrator
    .Description
        Returns true if a user is an administrator, false if the user is not an administrator        
    .Example
        Test-IsAdministrator
#>   
    param()
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
return (New-Object Security.Principal.WindowsPrincipal $currentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
} #end function Test-IsAdministrator



# Main Program
<#
.SYNOPSIS
Get Computer informations
.DESCRIPTION
Use PowerShell to get computer informations
.PARAMETER computername
computer name ex: mycomputer default:localhost
.EXAMPLE
AdvEvent5.ps1
get localhost computer information
.EXAMPLE
AdvEvent5.ps1 -debug
get localhost computer information with debug
.EXAMPLE
"computer1" | AdvEvent5.ps1
get computer1 information
.EXAMPLE
AdvEvent5.ps1 -computer computer1,computer2
get computer1 and computer2 information
#>

if (!(Test-IsAdministrator)) {
Write-Warning "Your user is not Administrator on this host"
}
$x32 = @{"cpu" = "1000"; "memory" = "1024"; "disk" = "16"; "directx" = "9"}
$x64 = @{"cpu" = "2000"; "memory" = "2048"; "disk" = "20"; "directx" = "9"}


# foreach computer
foreach ($computer in $computername) {
$obj = Get-ComputerInfos -computername $computer

# with -debug switch too lazy and no time to do a function with array of hash including debug

# 32bits
$eligibilityX32=$False
if ($obj.directx -ge $x32["directx"]) {
$debug = "DirectX Version: >= 9 (Eligibil 32bits)"
Write-Debug $debug
if ($obj.CPUspeed -ge $x32["cpu"]) {
$debug = "Computer CPU:" + $obj.CPUspeed + " >= " + $x32["cpu"] + " (Eligibil 32bits)"
Write-Debug $debug
if ($obj.RAMCapacity -ge $x32["memory"]) {
$debug = "Computer RAM:" + $obj.RAMCapacity + " >= " + $x32["memory"] + " (Eligibil 32bits)"
Write-Debug $debug
foreach ($disk in $obj.objDrive) {
if (($disk.Size/1GB) -ge $x32["disk"]) {
$eligibilityX32=$True
$debug = "Computer Disks:Disk >= " + $x32["disk"] + " (Eligibil 32bits)"
Write-Debug $debug
break
} else {
$debug = "Computer Disks:Disk < " + $x32["disk"] + " (NOT Eligibil 32bits)"
Write-Debug $debug
}
}
} else {
$debug = "Computer RAM:" + $obj.RAMCapacity + " < " + $x32["memory"] + " (NOT Eligibil 32bits)"
Write-Debug $debug
}
} else {
$debug = "Computer CPU:" + $obj.CPUspeed + "<" + $x32['cpu'] + " (NOT Eligibil 32bits)"
Write-Debug $debug
}
} else {
$debug = "DirectX Version: < 9 (NOT Eligibil 32bits)"
Write-Debug $debug
}
Write-Debug "eligibilityX32: $eligibilityX32"

# 64bits
$eligibilityX64=$False
if ($obj.directx -ge $x64["directx"]) {
$debug = "DirectX Version: >= 9 (Eligibil 64bits)"
Write-Debug $debug
if ($obj.CPUspeed -ge $x64["cpu"]) {
$debug = "Computer CPU:" + $obj.CPUspeed + " >= " + $x64["cpu"] + " (Eligibil 64bits)"
Write-Debug $debug
if ($obj.RAMCapacity -ge $x64["memory"]) {
$debug = "Computer RAM:" + $obj.RAMCapacity + " >= " + $x64["memory"] + " (Eligibil 64bits)"
Write-Debug $debug
foreach ($disk in $obj.objDrive) {
if (($disk.Size/1GB) -ge $x64["disk"]) {
$eligibilityX64=$True
$debug = "Computer Disks:Disk >= " + $x64["disk"] + " (Eligibil 64bits)"
Write-Debug $debug
break
} else {
$debug = "Computer Disks:Disk < " + $x64["disk"] + " (NOT Eligibil 64bits)"
Write-Debug $debug
}
}
} else {
$debug = "Computer RAM:" + $obj.RAMCapacity + " < " + $x64["memory"] + " (NOT Eligibil 64bits)"
Write-Debug $debug
}
} else {
$debug = "Computer CPU:" + $obj.CPUspeed + "<" + $x64['cpu'] + " (NOT Eligibil 64bits)"
Write-Debug $debug
}
} else {
$debug = "DirectX Version: < 9 (NOT Eligibil 64bits)"
Write-Debug $debug
}
Write-Debug "eligibilityX64: $eligibilityX64"

if ($eligibilityX64 -and $eligibilityX32 -and ($obj.RAMCapacity -ge 3072)) {
Write-Host "$computer best upgraded to a 64-bit (x64) Windows 7 operating system."
} else {
Write-Host "$computer best upgraded to a 32-bit (x86) Windows 7 operating system."
}
}

The 2011 Scripting Games Advanced Event 4: Use PowerShell to Investigate the SvcHost Process

The 2011 Scripting Games Advanced Event 4: Use PowerShell to Investigate the SvcHost Process

My personal script:
http://2011sg.poshcode.org/1268
Average Rating: 2.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 4: Use PowerShell to Investigate the SvcHost Process
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $computername = $Env:COMPUTERNAME,

[Parameter(Mandatory = $false, Position = 1)]
[ValidateNotNullOrEmpty()]
[String] $processname = "svchost.exe",

[Parameter(Mandatory = $false, Position = 2)]
[ValidateNotNullOrEmpty()]
[String] $ReportFile = "report.txt"
)


Function Get-ProcService {
<#
.SYNOPSIS
Get Process and service associated
.DESCRIPTION
Use PowerShell to Investigate the SvcHost Process
.PARAMETER $computername
computer name ex: mycomputer default:localhost
.PARAMETER processname
process name ex: myprocess.exe default:svchost.exe
.EXAMPLE
Get-ProcService
Investigate the SvcHost.exe Process
.EXAMPLE
Get-ProcService -processname myprocess.exe
Investigate the myprocess.exe Process
#>
Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $computername = $Env:COMPUTERNAME,

[Parameter(Mandatory = $false, Position = 1)]
[ValidateNotNullOrEmpty()]
[String] $processname = "svchost.exe"
)
# Get processes containing processname
$objProcesses = Get-WmiObject -ComputerName $computername Win32_Process | Where-Object { $_.Name -eq $processname }

# Get services containing processname
$objServices = Get-WmiObject -ComputerName $computername Win32_Service | Where-Object { $_.PathName.contains($processname) }

# Loop into all processname
[Array] $arrObj = @( )
Foreach($objProcess in $objProcesses) {
$objParent = New-Object PSObject
$objParent | Add-Member -MemberType noteproperty -Name "ProcessId" -Value $objProcess.ProcessId
$objParent | Add-Member -MemberType noteproperty -Name "PrivatePageCount" -Value ($objProcess.PrivatePageCount/1KB) # PageFileUsage = PrivatePageCount / 1024 only in W2K8 not in XP = Memory Commit Size in Task Manager
$objParent | Add-Member -MemberType noteproperty -Name "PageFaults" -Value $objProcess.PageFaults
$objParent | Add-Member -MemberType noteproperty -Name "CommandLine" -Value $objProcess.CommandLine # work only in W2K8 not XP

# for each processname get services associated
[Array] $arrObjChild = @( )
$processid = $objProcess.ProcessId
Foreach($objService in $objServices) {
if ($objService.ProcessId -eq $processid) {
$objParent | Add-Member -MemberType noteproperty -Name "CommandLine" -Value $objService.PathName -Force # work in XP
$objChild = New-Object PSObject
$objChild | Add-Member -MemberType noteproperty -Name "StartMode" -Value $objService.StartMode
$objChild | Add-Member -MemberType noteproperty -Name "State" -Value $objService.State
$objChild | Add-Member -MemberType noteproperty -Name "ServiceName" -Value $objService.Name
$arrObjChild += $objChild
}
}
$objParent | Add-Member -MemberType noteproperty -Name "objService" -Value $arrObjChild
$arrObj += $objParent

}
return $arrObj
}


# Main Program

# Get all process and services associated
[Array] $arrObj = @( )
$arrObj = Get-ProcService -computername $computername -processname $processname

# Display Informations and produce a written report
$report = "There are " + ($arrObj.Count) + " instances of " + $processname + " running"
$report
$report | Out-File $ReportFile

$report = $arrObj | select ProcessId -ExpandProperty objService | Select processId, StartMode, State, ServiceName | Sort-Object ProcessId | Format-Table -AutoSize
$report
$report | Out-File $ReportFile -Append

$report = $arrObj | Select ProcessId, PrivatePageCount, PageFaults, CommandLine | Sort-Object ProcessId | Format-Table -AutoSize
$report
$report | Out-File $ReportFile -Append

The 2011 Scripting Games Advanced Event 3: Use PowerShell to Query Classic Event and ETL Diagnostic Logs

The 2011 Scripting Games Advanced Event 3: Use PowerShell to Query Classic Event and ETL Diagnostic Logs

My personal script:
http://2011sg.poshcode.org/1011
Average Rating: 4.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 3: Use PowerShell to Query Classic Event and ETL Diagnostic Logs
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

# Main Program
Param(
[String] $action = "localhost",
[String] $inputfile,
[String] $iNbEvents,
[String] $providername,
[String] $level,
[Int] $id,
[Int] $days,
[String] $logname,
[String] $message
)



# ***********************************************

Function isComputerInADomain {
<#
.SYNOPSIS
Is computer in a domain
.DESCRIPTION
Is computer in a domain. Return $True or $False
.PARAMETER strComputer
Computer name. Default to localhost.
.EXAMPLE
isComputerInADomain
is local machine in a domain ?
.EXAMPLE
isComputerInADomain mycomputer
is mycomputer in a domain ?
#>
Param ([string] $strComputer)
$strComputer = $(if ($strComputer) {$strComputer} else {Get-Content ENV:COMPUTERNAME})
if ((Get-WmiObject -ComputerName $strComputer Win32_ComputerSystem).PartOfDomain -eq $true) {
return $true
} else {
return $false
}
}

# ***********************************************

Function GetUserDomainDNS {
<#
.SYNOPSIS
return user domain name in DNS format ex: domain.net
.DESCRIPTION
return user domain name in DNS format ex: domain.net
.EXAMPLE
GetUserDomainDNS
return user domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
Return $strDomainDNS
}

# ***********************************************

Function GetComputerDomainDNS {
<#
.SYNOPSIS
return local computer domain name in DNS format ex: domain.net
.DESCRIPTION
return local computer domain name in DNS format ex: domain.net
.EXAMPLE
GetComputerDomainDNS
return local computer domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name
Return $strDomainDNS
}

# ***********************************************

# GetDomainDN
# get Domain name in DNS format ex: domain.net
#
Function GetDomainDN {
<#
.SYNOPSIS
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.DESCRIPTION
from domain name DNS format domain.net to
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.PARAMETER strDomainDNS
Domain name in DNS format. Ex: domain.net
.EXAMPLE
GetDomainDN domain.net
return DC=DOMAIN,DC=NET
.EXAMPLE
GetDomainDN -strDomainDNS domain.net
return DC=DOMAIN,DC=NET
#>
Param ([string] $strDomainDNS)
$strDomainDN = "DC=" + $strDomainDNS -replace "\.",",DC="
Return $strDomainDN
}

# ***********************************************

Function SearchAD {
<#
.SYNOPSIS
return AD query
.DESCRIPTION
return AD query
.PARAMETER options
Hashtable
.EXAMPLE
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = "(objectCategory=computer)"
$hashSearchAD["strSearchScope"] = "Subtree"
$hashSearchAD["colAttributes"] = "name"
$hashSearchAD["strBaseDN"] = "DC=DOMAIN,DC=NET"
searchAD $hashSearchAD
#>
Param ([hashtable] $options)
$strFilter = $(if ($options.ContainsKey("strFilter")) {$options["strFilter"]} else {""}) # ex: '(objectCategory=computer)'
$strSearchScope = $(if ($options.ContainsKey("strSearchScope")) {$options["strSearchScope"]} else {"Subtree"}) # Base, OneLevel or Subtree
$colAttributes = $(if ($options.ContainsKey("colAttributes")) {$options["colAttributes"]} else {""}) # ex: '"name", "jobTitle", "telephoneNumber"
$strBaseDN = $(if ($options.ContainsKey("strBaseDN")) {$options["strBaseDN"]} else {""}) # ex: DC=Domain,DC=NET

$strBase = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://" + $strBaseDN)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $strBase
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = $strSearchScope
Foreach ($attribute in $colAttributes){$objSearcher.PropertiesToLoad.Add($attribute)}

$dtResult = New-Object "System.Data.DataTable"
$dtResult = $objSearcher.FindAll() # .FindOne() .FindAll()
#Write-host "count:" $dtResult.count
return $dtResult
}

# ***********************************************

Function TestFile {
<#
.SYNOPSIS
Test if file exist
.DESCRIPTION
Test if file strFilename exist
Then test if file exist in strCurDir\strFilename path
Return filename path
.PARAMETER strFilename
filename to test
.PARAMETER strCurDir
directory to test filename if not in current directory
.EXAMPLE
TestFile -strFilename abcdefghijkl.txt
return
ERROR: file abcdefghijkl.txt NOT exist
ERROR: file D:\Datas\Dev\abcdefghijkl.txt NOT exist
.EXAMPLE
TestFile -strFilename regedit.exe -strCurDir C:\WINDOWS
return C:\WINDOWS\regedit.exe
#>
Param(
[String] $strFilename,
[String] $strCurDir
)
if ($strFilename) {
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
If ((Test-Path("$strFilename")) -eq $False){
If ($strFilename.ToUpper().Contains($strCurDir.ToUpper()) ) {
Write-Host "ERROR: file $strFilename NOT exist"
return
} Else {
If ((Test-Path("$strCurDir\$strFilename")) -eq $False){
Write-Host "ERROR: file $strFilename NOT exist"
Write-Host "ERROR: file $strCurDir\$strFilename NOT exist"
return
} Else {
$strFilename = "$strCurDir\$strFilename"
}
}
}
return $strFilename
}
}


# ***********************************************

Function GetFileIntoArr {
<#
.SYNOPSIS
Import File into an array
.DESCRIPTION
Import File into an array
.PARAMETER strFilename
filename to import
.PARAMETER strCurDir
directory to test filename if not in current directory
.PARAMETER arrFile
array where file is imported
.PARAMETER strComment
1st line character for comment line (default: #)
.EXAMPLE
[Array] $arrContent = @( )
GetFileIntoArr -strFilename .\content.txt -arrFile ([Ref]$arrContent)
return
#>
Param(
[String] $strFilename,
[String] $strCurDir,
[Ref]$arrFile,
[String] $strComment
)
$strComment = $(if ($strComment) {$strComment} else {"#"})
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })

$retFilename = TestFile -strFilename $strFilename -strCurDir $strCurDir
if ($retFilename) {
$Content = Get-Content "$retFilename"
Foreach ($line in $Content) {
$comment = $False
If ($line.Trim().length -gt 0) { # take only line with data and without # at begininng of the line
# if we do not want to use comment
If ($strComment -eq "#") {
If ($line.substring(0,1) -eq "#") {
$comment = $True
}
}
If ($comment -eq $False) {
# Get Search & Replace
$arrFile.Value += $line.Trim()
}
}
}
return $True
} else {
return $False
}
}

# ***********************************************

Function GetADComputerToArray {
<#
.SYNOPSIS
return AD Computer query to array
.DESCRIPTION
return AD Computer query to array
.PARAMETER strDomainDN
Domain name in DN format. Default: Computer Domain Name ex: DC=DOMAIN,DC=NET
.PARAMETER strFilter
Computer AD filter. Default: (objectCategory=computer)
.PARAMETER strSearchScope
Domain name in DNS format. Default: Subtree
.PARAMETER colAttributes
Attributes to get. Default: name
.EXAMPLE
[Array] $arrComputers = @( )
GetADComputerToArray -array ([Ref]$arrComputers)
#>
Param(
[Ref]$array,
[String] $strDomainDN,
[String] $strFilter,
[String] $strSearchScope,
[String] $colAttributes
)
$strDomainDN = $(if ($strDomainDN) {$strDomainDN} else {GetDomainDN -strDomainDNS (GetComputerDomainDNS)})
$strFilter = $(if ($strFilter) {$strFilter} else {'(objectCategory=computer)'})
$strSearchScope = $(if ($strSearchScope) {$strSearchScope} else {"Subtree"})
$colAttributes = $(if ($colAttributes) {$colAttributes} else {"name"})
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = $strFilter
$hashSearchAD["strSearchScope"] = $strSearchScope # Base, OneLevel or Subtree
$hashSearchAD["colAttributes"] = $colAttributes # ex: '"name", "jobTitle", "telephoneNumber"
$hashSearchAD["strBaseDN"] = $strDomainDN
$dtResult = SearchAD($hashSearchAD)
If ($dtResult -ne $Null) {
Foreach ($row in $dtResult){
If ($row.GetType().Name -eq "Int32") {
} else {
$result = $row.GetDirectoryEntry()
$array.Value += $result.Name
Write-Host $result.Name
}
}
return $True
} else {
return $False
}
}

# ***********************************************



Function Get-AdvEvent3 {
<#
.SYNOPSIS
2011 Scripting Games Advanced Event 3
.DESCRIPTION
2011 Scripting Games Advanced Event 3
Use PowerShell to Query Classic Event and ETL Diagnostic Logs
.PARAMETER action
action : ad / file / localhost
.PARAMETER inputfile
inputfile filename for file option
.PARAMETER iNbEvents
number max of events to display ex: 1, 5 ...
.PARAMETER providername
provider name ex: "Microsoft-Windows-Diagnostics-Performance"
.PARAMETER level
level of severity ex: 1, 2 ...
0 = LogAlways
1 = Critical
2 = Error
3 = Warning
4 = Informational
5 = Verbose
.PARAMETER id
event id ex: 100, 247 ...
.PARAMETER days
get event in last days ex: 2 for 2 last days
.PARAMETER logname
log name ex: "Microsoft-Windows-Diagnostics-Performance/Operational"
.PARAMETER message
message ex: "resolution"
.EXAMPLE
Get-AdvEvent3
Get process module version for AD query computers
.EXAMPLE
Get-AdvEvent3 ad
Get event query for local computer
.EXAMPLE
Get-AdvEvent3 file filename.txt
Get event query for local computer
.EXAMPLE
Get-AdvEvent3 -level 1 -message "resolution" -days 5
get all event with severity 1 critical and message containing "resolution" in last 5 days
#>
Param(
[String] $action = "localhost",
[String] $inputfile,
[String] $iNbEvents,
[String] $providername,
[String] $level,
[Int] $id,
[Int] $days,
[String] $logname,
[String] $message
)
$iNbEvents = $(if ($iNbEvents) {$iNbEvents} else { 1 })
$providername = $(if ($providername) {$providername} else {""})
$level = $(if ($level) {$level} else { "" })
$id = $(if ($id) {$id} else {""})
$logname = $(if ($logname) {$logname} else {""})
$message = $(if ($message) {$message} else {""})
$date = $(if ($days) {[DateTime]::Now.AddDays(- $days).Date} else {[datetime]::today})


# local computername
$computername = (Get-Content ENV:COMPUTERNAME)
[Array] $arrComputers = @( )
# Default action = localhost
switch($action) {
# localhost
"localhost" {
$arrComputers += $computername
}

# AD Query
"ad" {
if(isComputerInADomain) {
# AD query but only Servers
GetADComputerToArray -array ([Ref]$arrComputers) -strFilter "(&(objectcategory=computer)(|(operatingsystem=Windows 2000 Server)(operatingsystem=Windows Server*))) "
} else {
Write-Host "ERROR: $computername is NOT in a domain. You cound not use switch $action"
return
}
}

# File content
"file" {
if ($inputfile) {
if (!(GetFileIntoArr -strFilename $inputfile -arrFile ([Ref]$arrComputers))) {
return
}
} else {
Write-Host "ERROR: With action $action switch you need a filename.txt as second parameter inputfile"
return
}
}

# Others actions = Help
Default {
get-help Get-AdvEvent3 -full
return
}
}

$string=""
Foreach ($computer in $arrComputers) {
Write-Output $string.PadRight(80,"-")
Write-Output "Computername: $computer"
# Event Enabled and writed today
$objEventsList = Get-WinEvent -ComputerName $computer -ListLog * -ErrorAction SilentlyContinue | where-object { $_.IsEnabled -eq "True" -and $_.recordcount -and $_.lastwritetime -gt $date}
[Array] $arrObj = @( )
Foreach($objEvents in $objEventsList) {
# Get Events and filter with parameter given
$objCurEvents = Get-WinEvent -ComputerName $computer -LogName $objEvents.LogName -MaxEvents $iNbEvents -ErrorAction SilentlyContinue | where-object { $_.TimeCreated -gt $date}
if ( $logname -ne "") {
$objCurEvents = $objCurEvents | Where-Object { $_.LogName -eq $logname }
}
if ($providername -ne "") {
$objCurEvents = $objCurEvents | Where-Object { $_.ProviderName -eq $providername }
}
if ($id -ne "") {
$objCurEvents = $objCurEvents | Where-Object { $_.Id -eq $id }
}
if ($message -ne "") {
if (!$objCurEvents.message.isNull) {
$objCurEvents = $objCurEvents | Where-Object { $_.Message.Contains($message) }
}
}
if ($level -ne "") {
$objCurEvents = $objCurEvents | Where-Object { $_.Level -eq $level }
}

if ($objCurEvents) {
foreach ($objCurEvent in $objCurEvents) {
$obj = New-Object PSObject
$obj | Add-Member -MemberType noteproperty -Name "TimeCreated" -Value $objCurEvent.TimeCreated
$obj | Add-Member -MemberType noteproperty -Name "ProviderName" -Value $objCurEvent.ProviderName
$obj | Add-Member -MemberType noteproperty -Name "Id" -Value $objCurEvent.Id
$obj | Add-Member -MemberType noteproperty -Name "Message" -Value $objCurEvent.Message
$obj | Add-Member -MemberType noteproperty -Name "LogName" -Value $objCurEvent.LogName
if ($level -ne "") {
$obj | Add-Member -MemberType noteproperty -Name "Level" -Value $objCurEvent.Level
}

$arrObj += $obj
}
}
}

$arrObj | Format-Table
}

}


# ***********************************************

# Main program

Get-AdvEvent3 -action $action -inputfile $inputfile -iNbEvents $iNbEvents -providername $providername -level $level -id $id -days $days -logname $logname -message $message

The 2011 Scripting Games Advanced Event 2: Use PowerShell to Identify Status of Service Dependencies

The 2011 Scripting Games Advanced Event 2: Use PowerShell to Identify Status of Service Dependencies

My personal script:
http://2011sg.poshcode.org/804
Average Rating: 3.50 by 3 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 2: Use PowerShell to Identify Status of Service Dependencies
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

# Main Program
Param(
[parameter(Position=0)]
[String[]]
$action,
[parameter(Position=1)]
[String[]]
$inputfile
)




# ***********************************************

Function isComputerInADomain {
<#
.SYNOPSIS
Is computer in a domain
.DESCRIPTION
Is computer in a domain. Return $True or $False
.PARAMETER strComputer
Computer name. Default to localhost.
.EXAMPLE
isComputerInADomain
is local machine in a domain ?
.EXAMPLE
isComputerInADomain mycomputer
is mycomputer in a domain ?
#>
Param ([string] $strComputer)
$strComputer = $(if ($strComputer) {$strComputer} else {Get-Content ENV:COMPUTERNAME})
if ((Get-WmiObject -ComputerName $strComputer Win32_ComputerSystem).PartOfDomain -eq $true) {
return $true
} else {
return $false
}
}

# ***********************************************

Function GetUserDomainDNS {
<#
.SYNOPSIS
return user domain name in DNS format ex: domain.net
.DESCRIPTION
return user domain name in DNS format ex: domain.net
.EXAMPLE
GetUserDomainDNS
return user domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
Return $strDomainDNS
}

# ***********************************************

Function GetComputerDomainDNS {
<#
.SYNOPSIS
return local computer domain name in DNS format ex: domain.net
.DESCRIPTION
return local computer domain name in DNS format ex: domain.net
.EXAMPLE
GetComputerDomainDNS
return local computer domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name
Return $strDomainDNS
}

# ***********************************************

# GetDomainDN
# get Domain name in DNS format ex: domain.net
#
Function GetDomainDN {
<#
.SYNOPSIS
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.DESCRIPTION
from domain name DNS format domain.net to
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.PARAMETER strDomainDNS
Domain name in DNS format. Ex: domain.net
.EXAMPLE
GetDomainDN domain.net
return DC=DOMAIN,DC=NET
.EXAMPLE
GetDomainDN -strDomainDNS domain.net
return DC=DOMAIN,DC=NET
#>
Param ([string] $strDomainDNS)
$strDomainDN = "DC=" + $strDomainDNS -replace "\.",",DC="
Return $strDomainDN
}

# ***********************************************

Function SearchAD {
<#
.SYNOPSIS
return AD query
.DESCRIPTION
return AD query
.PARAMETER options
Hashtable
.EXAMPLE
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = "(objectCategory=computer)"
$hashSearchAD["strSearchScope"] = "Subtree"
$hashSearchAD["colAttributes"] = "name"
$hashSearchAD["strBaseDN"] = "DC=DOMAIN,DC=NET"
searchAD $hashSearchAD
#>
Param ([hashtable] $options)
$strFilter = $(if ($options.ContainsKey("strFilter")) {$options["strFilter"]} else {""}) # ex: '(objectCategory=computer)'
$strSearchScope = $(if ($options.ContainsKey("strSearchScope")) {$options["strSearchScope"]} else {"Subtree"}) # Base, OneLevel or Subtree
$colAttributes = $(if ($options.ContainsKey("colAttributes")) {$options["colAttributes"]} else {""}) # ex: '"name", "jobTitle", "telephoneNumber"
$strBaseDN = $(if ($options.ContainsKey("strBaseDN")) {$options["strBaseDN"]} else {""}) # ex: DC=Domain,DC=NET

$strBase = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://" + $strBaseDN)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $strBase
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = $strSearchScope
Foreach ($attribute in $colAttributes){$objSearcher.PropertiesToLoad.Add($attribute)}

$dtResult = New-Object "System.Data.DataTable"
$dtResult = $objSearcher.FindAll() # .FindOne() .FindAll()
#Write-host "count:" $dtResult.count
return $dtResult
}

# ***********************************************

Function TestFile {
<#
.SYNOPSIS
Test if file exist
.DESCRIPTION
Test if file strFilename exist
Then test if file exist in strCurDir\strFilename path
Return filename path
.PARAMETER strFilename
filename to test
.PARAMETER strCurDir
directory to test filename if not in current directory
.EXAMPLE
TestFile -strFilename abcdefghijkl.txt
return
ERROR: file abcdefghijkl.txt NOT exist
ERROR: file D:\Datas\Dev\abcdefghijkl.txt NOT exist
.EXAMPLE
TestFile -strFilename regedit.exe -strCurDir C:\WINDOWS
return C:\WINDOWS\regedit.exe
#>
Param(
[String] $strFilename,
[String] $strCurDir
)
if ($strFilename) {
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
If ((Test-Path("$strFilename")) -eq $False){
If ($strFilename.ToUpper().Contains($strCurDir.ToUpper()) ) {
Write-Host "ERROR: file $strFilename NOT exist"
return
} Else {
If ((Test-Path("$strCurDir\$strFilename")) -eq $False){
Write-Host "ERROR: file $strFilename NOT exist"
Write-Host "ERROR: file $strCurDir\$strFilename NOT exist"
return
} Else {
$strFilename = "$strCurDir\$strFilename"
}
}
}
return $strFilename
}
}


# ***********************************************

Function GetFileIntoArr {
<#
.SYNOPSIS
Import File into an array
.DESCRIPTION
Import File into an array
.PARAMETER strFilename
filename to import
.PARAMETER strCurDir
directory to test filename if not in current directory
.PARAMETER arrFile
array where file is imported
.PARAMETER strComment
1st line character for comment line (default: #)
.EXAMPLE
[Array] $arrContent = @( )
GetFileIntoArr -strFilename .\content.txt -arrFile ([Ref]$arrContent)
return
#>
Param(
[String] $strFilename,
[String] $strCurDir,
[Ref]$arrFile,
[String] $strComment
)
$strComment = $(if ($strComment) {$strComment} else {"#"})
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })

$retFilename = TestFile -strFilename $strFilename -strCurDir $strCurDir
if ($retFilename) {
$Content = Get-Content "$retFilename"
Foreach ($line in $Content) {
$comment = $False
If ($line.Trim().length -gt 0) { # take only line with data and without # at begininng of the line
# if we do not want to use comment
If ($strComment -eq "#") {
If ($line.substring(0,1) -eq "#") {
$comment = $True
}
}
If ($comment -eq $False) {
# Get Search & Replace
$arrFile.Value += $line.Trim()
}
}
}
return $True
} else {
return $False
}
}

# ***********************************************

Function GetXlsIntoArr {
<#
.SYNOPSIS
Import Excel file into an array
.DESCRIPTION
Import Excel file into an array
.PARAMETER strFilename
filename to import
.PARAMETER strSheet
sheet to open
.PARAMETER arrFile
array where file is imported
.PARAMETER strComment
1st line character for comment line (default: #)
.EXAMPLE
[Array] $arrContent = @( )
GetFileIntoArr -strFilename .\content.txt -arrFile ([Ref]$arrContent)
return
#>
Param(
[String] $strFilename,
[String] $strCurDir,
[String] $strSheet,
[Int] $iColumn,
[Ref]$arrFile
)
$strComment = $(if ($strComment) {$strComment} else {"#"})
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
$strSheet = $(if ($strSheet) {$strSheet} else {""})
$iColumn = $(if ($iColumn) {$iColumn} else {1})
$retFilename = TestFile -strFilename $strFilename -strCurDir $strCurDir
if ($retFilename) {
$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=$false
if ($retFilename.substring(0,2) -eq ".\") { $retFilename = (Get-Location).Path + $retFilename.substring(1, $retFilename.length - 1) }
$objWorkbook=$objExcel.Workbooks.Open($retFilename)
if ($strSheet -eq "") {
$strSheet = $objWorkbook.ActiveSheet.Name
}
$objSheet = $objWorkbook.sheets.item($strSheet)
for ($iRow = 1 ; $iRow -le ($objSheet.UsedRange.Rows).count; $iRow++) {
$arrFile.Value += $objSheet.cells.item($iRow,$iColumn).value2
}
$objexcel.quit()
return $True
} else {
return $False
}
}

# ***********************************************

Function GetADComputerToArray {
<#
.SYNOPSIS
return AD Computer query to array
.DESCRIPTION
return AD Computer query to array
.PARAMETER strDomainDN
Domain name in DN format. Default: Computer Domain Name ex: DC=DOMAIN,DC=NET
.PARAMETER strFilter
Computer AD filter. Default: (objectCategory=computer)
.PARAMETER strSearchScope
Domain name in DNS format. Default: Subtree
.PARAMETER colAttributes
Attributes to get. Default: name
.EXAMPLE
[Array] $arrComputers = @( )
GetADComputerToArray -array ([Ref]$arrComputers)
#>
Param(
[Ref]$array,
[String] $strDomainDN,
[String] $strFilter,
[String] $strSearchScope,
[String] $colAttributes
)
$strDomainDN = $(if ($strDomainDN) {$strDomainDN} else {GetDomainDN -strDomainDNS (GetComputerDomainDNS)})
$strFilter = $(if ($strFilter) {$strFilter} else {'(objectCategory=computer)'})
$strSearchScope = $(if ($strSearchScope) {$strSearchScope} else {"Subtree"})
$colAttributes = $(if ($colAttributes) {$colAttributes} else {"name"})
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = $strFilter
$hashSearchAD["strSearchScope"] = $strSearchScope # Base, OneLevel or Subtree
$hashSearchAD["colAttributes"] = $colAttributes # ex: '"name", "jobTitle", "telephoneNumber"
$hashSearchAD["strBaseDN"] = $strDomainDN
$dtResult = SearchAD($hashSearchAD)
If ($dtResult -ne $Null) {
Foreach ($row in $dtResult){
If ($row.GetType().Name -eq "Int32") {
} else {
$result = $row.GetDirectoryEntry()
$array.Value += $result.Name
Write-Host $result.Name
}
}
}
}

# ***********************************************



Function Get-AdvEvent2 {
<#
.SYNOPSIS
2011 Scripting Games Advanced Event 2
.DESCRIPTION
2011 Scripting Games Advanced Event 2
Use PowerShell to Identify Status of Service Dependencies
.PARAMETER action
action : ad / file / localhost
.PARAMETER inputfile
inputfile filename for file option
.EXAMPLE
Get-AdvEvent2 ad
Get process module version for AD query computers
.EXAMPLE
Get-AdvEvent2 file filename.txt
Get process module version for all computers in filename.txt
.EXAMPLE
Get-AdvEvent2 excel filename.xls
Get process module version for all computers in excel file filename.xls
#>
Param(
[String] $action,
[String] $inputfile
)
# local computername
$computername = (Get-Content ENV:COMPUTERNAME)
[Array] $arrComputers = @( )

# Default action = localhost
switch($action) {
# AD Query
"ad" {
if(isComputerInADomain) {
# AD query but only Servers
GetADComputerToArray -array ([Ref]$arrComputers) -strFilter "(&(objectcategory=computer)(|(operatingsystem=Windows 2000 Server)(operatingsystem=Windows Server*))) "
} else {
Write-Host "ERROR: $computername is NOT in a domain. You cound not use switch $action"
return
}
}

# File content
"file" {
if ($inputfile) {
if (!(GetFileIntoArr -strFilename $inputfile -arrFile ([Ref]$arrComputers))) {
return
}
} else {
Write-Host "ERROR: With action $action switch you need a filename.txt as second parameter inputfile"
return
}
}

# File content
"excel" {
if ($inputfile) {
if (!(GetXlsIntoArr -strFilename $inputfile -arrFile ([Ref]$arrComputers))) {
return
}
} else {
Write-Host "ERROR: With action $action switch you need a filename.xls as second parameter inputfile"
return
}
}

# Others actions = Help
Default {
get-help Get-AdvEvent2 -full
return
}
}


#$ErrorActionPreference = Continue
$string=""
Foreach ($computer in $arrComputers) {
# Test if computer is a Server
$win32os = $null
$win32os = Get-WmiObject -ComputerName $computer Win32_OperatingSystem
if ( ($win32os -ne $null) -and ($win32os.ProductType -ne 1)) {
Write-Output $string.PadRight(80,"-")
Write-Output "Computername: $computer"
# Get all services running
$services = Get-Service -Computername $computer | Where-Object { $_.Status -eq "Running" }
Foreach ($service in $services) {
Write-Output $service.Name
Write-Output $string.PadRight($service.Name.Length,"-")
# Get all Dependent services
$service.DependentServices | Select-Object -Property name, status | Format-Table -HideTableHeaders
Write-Output "`r`n"
}
}

}

}


# ***********************************************

# Main program

Get-AdvEvent2 -action $action -inputfile $inputfile

The 2011 Scripting Games Advanced Event 1: Finding Process Module Versions by Using PowerShell

The 2011 Scripting Games Advanced Event 1: Finding Process Module Versions by Using PowerShell

My personal script:
http://2011sg.poshcode.org/597
with a "wow..nice script" comment by Ed Wilson which is a real gift for me
Average Rating: 3.50 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 1: Finding Process Module Versions by Using PowerShell
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

# Main Program
Param(
[parameter(Position=0)]
[String[]]
$action="Localhost",
[parameter(Position=1)]
[String[]]
$inputfile
)




# ***********************************************

Function isComputerInADomain {
<#
.SYNOPSIS
Is computer in a domain
.DESCRIPTION
Is computer in a domain. Return $True or $False
.PARAMETER strComputer
Computer name. Default to localhost.
.EXAMPLE
isComputerInADomain
is local machine in a domain ?
.EXAMPLE
isComputerInADomain mycomputer
is mycomputer in a domain ?
#>
Param ([string] $strComputer)
$strComputer = $(if ($strComputer) {$strComputer} else {Get-Content ENV:COMPUTERNAME})
if ((Get-WmiObject -ComputerName $strComputer Win32_ComputerSystem).PartOfDomain -eq $true) {
return $true
} else {
return $false
}
}

# ***********************************************

Function GetUserDomainDNS {
<#
.SYNOPSIS
return user domain name in DNS format ex: domain.net
.DESCRIPTION
return user domain name in DNS format ex: domain.net
.EXAMPLE
GetUserDomainDNS
return user domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
Return $strDomainDNS
}

# ***********************************************

Function GetComputerDomainDNS {
<#
.SYNOPSIS
return local computer domain name in DNS format ex: domain.net
.DESCRIPTION
return local computer domain name in DNS format ex: domain.net
.EXAMPLE
GetComputerDomainDNS
return local computer domain name ex: domain.net
#>
[string] $strDomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name
Return $strDomainDNS
}

# ***********************************************

# GetDomainDN
# get Domain name in DNS format ex: domain.net
#
Function GetDomainDN {
<#
.SYNOPSIS
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.DESCRIPTION
from domain name DNS format domain.net to
return domain name in Distinguished Name format ex: DC=DOMAIN,DC=NET
.PARAMETER strDomainDNS
Domain name in DNS format. Ex: domain.net
.EXAMPLE
GetDomainDN domain.net
return DC=DOMAIN,DC=NET
.EXAMPLE
GetDomainDN -strDomainDNS domain.net
return DC=DOMAIN,DC=NET
#>
Param ([string] $strDomainDNS)
$strDomainDN = "DC=" + $strDomainDNS -replace "\.",",DC="
Return $strDomainDN
}

# ***********************************************

Function SearchAD {
<#
.SYNOPSIS
return AD query
.DESCRIPTION
return AD query
.PARAMETER options
Hashtable
.EXAMPLE
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = "(objectCategory=computer)"
$hashSearchAD["strSearchScope"] = "Subtree"
$hashSearchAD["colAttributes"] = "name"
$hashSearchAD["strBaseDN"] = "DC=DOMAIN,DC=NET"
searchAD $hashSearchAD
#>
Param ([hashtable] $options)
$strFilter = $(if ($options.ContainsKey("strFilter")) {$options["strFilter"]} else {""}) # ex: '(objectCategory=computer)'
$strSearchScope = $(if ($options.ContainsKey("strSearchScope")) {$options["strSearchScope"]} else {"Subtree"}) # Base, OneLevel or Subtree
$colAttributes = $(if ($options.ContainsKey("colAttributes")) {$options["colAttributes"]} else {""}) # ex: '"name", "jobTitle", "telephoneNumber"
$strBaseDN = $(if ($options.ContainsKey("strBaseDN")) {$options["strBaseDN"]} else {""}) # ex: DC=Domain,DC=NET

$strBase = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://" + $strBaseDN)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $strBase
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = $strSearchScope
Foreach ($attribute in $colAttributes){$objSearcher.PropertiesToLoad.Add($attribute)}

$dtResult = New-Object "System.Data.DataTable"
$dtResult = $objSearcher.FindAll() # .FindOne() .FindAll()
#Write-host "count:" $dtResult.count
return $dtResult
}

# ***********************************************

Function TestFile {
<#
.SYNOPSIS
Test if file exist
.DESCRIPTION
Test if file strFilename exist
Then test if file exist in strCurDir\strFilename path
Return filename path
.PARAMETER strFilename
filename to test
.PARAMETER strCurDir
directory to test filename if not in current directory
.EXAMPLE
TestFile -strFilename abcdefghijkl.txt
return
ERROR: file abcdefghijkl.txt NOT exist
ERROR: file D:\Datas\Dev\abcdefghijkl.txt NOT exist
.EXAMPLE
TestFile -strFilename regedit.exe -strCurDir C:\WINDOWS
return C:\WINDOWS\regedit.exe
#>
Param(
[String] $strFilename,
[String] $strCurDir
)
if ($strFilename) {
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
If ((Test-Path("$strFilename")) -eq $False){
If ($strFilename.ToUpper().Contains($strCurDir.ToUpper()) ) {
Write-Host "ERROR: file $strFilename NOT exist"
return
} Else {
If ((Test-Path("$strCurDir\$strFilename")) -eq $False){
Write-Host "ERROR: file $strFilename NOT exist"
Write-Host "ERROR: file $strCurDir\$strFilename NOT exist"
return
} Else {
$strFilename = "$strCurDir\$strFilename"
}
}
}
return $strFilename
}
}


# ***********************************************

Function GetFileIntoArr {
<#
.SYNOPSIS
Import File into an array
.DESCRIPTION
Import File into an array
.PARAMETER strFilename
filename to import
.PARAMETER strCurDir
directory to test filename if not in current directory
.PARAMETER arrFile
array where file is imported
.PARAMETER strComment
1st line character for comment line (default: #)
.EXAMPLE
[Array] $arrContent = @( )
GetFileIntoArr -strFilename .\content.txt -arrFile ([Ref]$arrContent)
return
#>
Param(
[String] $strFilename,
[String] $strCurDir,
[Ref]$arrFile,
[String] $strComment
)
$strComment = $(if ($strComment) {$strComment} else {"#"})
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })

$retFilename = TestFile -strFilename $strFilename -strCurDir $strCurDir
if ($retFilename) {
$Content = Get-Content "$retFilename"
Foreach ($line in $Content) {
$comment = $False
If ($line.length -gt 0) { # take only line with data and without # at begininng of the line
# if we do not want to use comment
If ($strComment -eq "#") {
If ($line.substring(0,1) -eq "#") {
$comment = $True
}
}
If ($comment -eq $False) {
# Get Search & Replace
$arrFile.Value += $line.Trim()
}
}
}
return $True
} else {
return $False
}
}

# ***********************************************


Function GetADComputerToArray {
<#
.SYNOPSIS
return AD Computer query to array
.DESCRIPTION
return AD Computer query to array
.PARAMETER strDomainDN
Domain name in DN format. Default: Computer Domain Name ex: DC=DOMAIN,DC=NET
.PARAMETER strFilter
Computer AD filter. Default: (objectCategory=computer)
.PARAMETER strSearchScope
Domain name in DNS format. Default: Subtree
.PARAMETER colAttributes
Attributes to get. Default: name
.EXAMPLE
[Array] $arrComputers = @( )
GetADComputerToArray -array ([Ref]$arrComputers)
#>
Param(
[Ref]$array,
[String] $strDomainDN,
[String] $strFilter,
[String] $strSearchScope,
[String] $colAttributes
)
$strDomainDN = $(if ($strDomainDN) {$strDomainDN} else {GetDomainDN -strDomainDNS (GetComputerDomainDNS)})
$strFilter = $(if ($strFilter) {$strFilter} else {'(objectCategory=computer)'})
$strSearchScope = $(if ($strSearchScope) {$strSearchScope} else {"Subtree"})
$colAttributes = $(if ($colAttributes) {$colAttributes} else {"name"})
$hashSearchAD = @{ }
$hashSearchAD["strFilter"] = $strFilter
$hashSearchAD["strSearchScope"] = $strSearchScope # Base, OneLevel or Subtree
$hashSearchAD["colAttributes"] = $colAttributes # ex: '"name", "jobTitle", "telephoneNumber"
$hashSearchAD["strBaseDN"] = $strDomainDN
$dtResult = SearchAD($hashSearchAD)
If ($dtResult -ne $Null) {
Foreach ($row in $dtResult){
If ($row.GetType().Name -eq "Int32") {
} else {
$result = $row.GetDirectoryEntry()
$array.Value += $result.Name
Write-Host $result.Name
}
}
}
}

# ***********************************************



Function Get-AdvEvent1 {
<#
.SYNOPSIS
2011 Scripting Games Advanced Event 1
.DESCRIPTION
2011 Scripting Games Advanced Event 1
Finding Process Module Versions by Using PowerShell
.PARAMETER action
action : ad / file / localhost
.PARAMETER inputfile
inputfile filename for file option
.EXAMPLE
Get-AdvEvent1
"Localhost only"
Get process module version for Localhost
.EXAMPLE
Get-AdvEvent1 ad
Get process module version for AD query computers
.EXAMPLE
Get-AdvEvent1 file filename.txt
Get process module version for all computers in filename.txt
#>
Param(
[String] $action,
[String] $inputfile
)
# local computername
$computername = (Get-Content ENV:COMPUTERNAME)
[Array] $arrComputers = @( )

# Default action = localhost
switch($action) {
"localhost" {
$arrComputers += $computername
}

# AD Query
"ad" {
Write-Host "AD"
if(isComputerInADomain) {
GetADComputerToArray -array ([Ref]$arrComputers)
} else {
Write-Host "ERROR: $computername is NOT in a domain. You cound not use switch $action"
return
}
}

# File content
"file" {
if ($inputfile) {
if (!(GetFileIntoArr -strFilename $inputfile -arrFile ([Ref]$arrComputers))) {
return
}
} else {
Write-Host "ERROR: With action $action switch you need a filename.txt as second parameter inputfile"
return
}
}

# Others actions = Help
Default {
get-help Get-AdvEvent1 -full
return
}
}


# Check "Windows Spooler Driver" module in Notepad process
$processName="notepad"
[Array] $arrObj = @( )
Foreach ($computer in $arrComputers) {
# Create process
$process = ([WMICLASS]"\\$computer\ROOT\CIMV2:win32_process").Create($processName)
if ($process.ReturnValue -eq 0) {
Start-Sleep -m 100 # Else too fast on my machine
# Get Process Id
$proc = invoke-command -computername $computer -scriptblock {param($id) get-process -id $id -module} -ArgumentList $process.ProcessId
# Get informations in custom object
$obj = New-Object PSObject
# Multilanguage below: Description -eq "Windows Spooler Driver" only for english
$obj = $proc | where-object {$_.ModuleName -eq "winspool.drv"} | select @{Name="computer"; Expression = {$computer}},ModuleName,Size,Filename,FileVersion
# Kill process
[System.Diagnostics.Process]::GetProcessByID($process.ProcessId,$computer).kill()
if ($obj) { $arrObj += $obj }
} else {
# Write-Host "Failed to create process!"
}
}

# Display information
$arrObj | ConvertTo-Csv -NoTypeInformation

}


# ***********************************************

# Main program

Get-AdvEvent1 -action $action -inputfile $inputfile