Tag Archives: powershell

Get current RDS-CAL details via PowerShell. Run this from your 2008 RDS Licensing server.

# Filename of the export
$filename = "RDS-CAL-Report.csv"
# Import RDS PowerShell Module
import-module remotedesktopservices

# Open RDS Location
Set-Location -path rds:

# Remove previous reports (Optional)
remove-item RDS:\LicenseServer\IssuedLicenses\PerUserLicenseReports\* -Recurse

# Create new RDS report
$NewReport = new-item -path RDS:\LicenseServer\IssuedLicenses\PerUserLicenseReports -Scope DOM -Name Report

# Name is automatically generated
$NewReportName = $NewReport.name

# Get issued licenses
$IssuedLicenseCount = get-item RDS:\LicenseServer\IssuedLicenses\PerUserLicenseReports\$NewReportName\Win2K8-Win2K8R2\IssuedCount
# Count issued licenses
$IssuedLicenseCountValue = $IssuedLicenseCount.CurrentValue

# Get installed licenses
$InstalledLicenseCount = get-item RDS:\LicenseServer\IssuedLicenses\PerUserLicenseReports\$NewReportName\Win2K8-Win2K8R2\InstalledCount
# Count installed licenses
$InstalledLicenseCountValue = $InstalledLicenseCount.CurrentValue

# Installed - Issued
$Available = $InstalledLicenseCount.CurrentValue - $IssuedLicenseCount.CurrentValue
# Show percentage available
$AvailablePercent = ($Available /$InstalledLicenseCount.CurrentValue)*100
$AvailablePercent = "{0:N0}" -f $AvailablePercent

# Display info

Write-host "Installed: $InstalledLicenseCountValue"
Write-host "Issued: $IssuedLicenseCountValue"
Write-host "Available: $Available [ $AvailablePercent % ]"

# Add the information into an Array

[System.Collections.ArrayList]$collection = New-Object System.Collections.ArrayList($null)
$obj = @{
Installed = $InstalledLicenseCountValue
Available = $Available
AvailablePercent = $AvailablePercent
Issued = $IssuedLicenseCountValue
Date = get-date
}

# Exit RDS location
set-location c:

# Create PSO Object with the data
$collection.Add((New-Object PSObject -Property $obj));

# Export Data into a file
$collection | export-csv $filename -NoTypeInformation -Encoding UTF8

A quick Powershell script I hacked together that will enumerate all Active Directory users, and build an XML file for an application I wrote that generates user reports for a specific application.

The output file format is similar to:

<quickreports>
  <report name="Organizational Unit">
  <database name="v001"/>
  <usrlogin name="jdoe01"/>
</report>
<quickreports>
$ErrorActionPreference= 'silentlycontinue'
$arr=@{}

foreach ($usr in Get-ADUser -Filter *  | select samaccountname) {

$user = get-aduser -identity $usr.samaccountname -ErrorAction SilentlyContinue
$userou = (($user.DistinguishedName -split "=",2)[-1].split(",")[1] -split "=",2)[-1]

$key = $userou
$value = $usr.samaccountname

if ($arr.ContainsKey("$userou")) {
$arr["$userou"] += $usr.samaccountname 
} else {
$arr["$userou"] = @()
$arr.add($key,$value)
}

}
$foo = "<?xml version=""1.0"" encoding=""utf-8""?>`r`n"
$foo += "<quickreports>`r`n"

$foo += foreach ($ou in $arr.keys) {

    write-output "  <report name=""$ou"">`r`n"

    foreach ($u in $arr["$ou"]) {
                if ($u.contains("01")) {
                    write-output "<database name=""v001""/>`r`n"
                } elseif ($u.contains("04")) {
                    write-output "<database name=""v004""/>`r`n"
                } else { 
                    write-output "<database name=""""/>`r`n"
                }
        write-output "<usrlogin name=""$u""/>`r`n"
}
    write-output "</report>`r`n"
}

$foo += "</quickreports>"

$foo | out-file quickreport.xml

# for some reason the outputted file was dumping 0x00 into the file.  Eventually
# I'll clean all this up and just write all the attributes and elements from up above
# but now is not the time as this is just a quick and dirty POC

$fn = "quickreport.xml"
$xmlDoc = [system.xml.xmldocument](get-content $fn)

$xmlDoc.save($fn)

Continuing with learning some Powershell, I cooked this up which will connect to the vCenter server and get all the VM’s and list the name, operating system and power state.

foreach ($vm in get-vm) {
	$os=get-vmguest -vm $vm.name | 	where-object {$_.osfullname -ne $null} | select osfullname;
	write-host ($vm.name.tostring() + "," + $os.osfullname + "," + $vm.powerstate.tostring()) -ErrorAction silentlycontinue
}

Example Output

VM01,Microsoft Windows Server 2008 R2 (64-bit),PoweredOn
VM02,Microsoft Windows Server 2003 (32-bit),PoweredOn
VM03,Microsoft Windows Server 2008 R2 (64-bit),PoweredOn
VM04,Microsoft Windows Server 2003 (32-bit),PoweredOn

Clear Powershell’s last 10 commands:

clear-history -count 10 -newest

After executing that, use get-history to see what’s left…

Clear the console buffer by scripting F7+2:

[system.reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[System.Windows.Forms.SendKeys]::Sendwait('%{F7 2}')

Try using the Up key to cycle through history — won’t happen.

I’ve recently been tasked with finding duplicate files across multiple shares on a network. I’ve looked at a few different “free” options out there that can do this and in the end found that PowerShell can do this for me, for free. Might want to grab a cup of coffee, or a pot, depending on how many directories and large files you have.

Get-DuplicateFiles.ps1

# USAGE:
# .Get-DuplicateFiles.ps1


param ([string] $Path = (Get-Location))
Add-Type -AssemblyName System


function Get-MD5 (
    [System.IO.FileInfo]
    $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')
) {
    # This Get-MD5 function sourced from:
    # http://blogs.msdn.com/powershell/archive/2006/04/25/583225.aspx
    $stream = $null
    $cryptoProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
    $hashAlgorithm = New-Object $cryptoProvider
    $stream = $file.OpenRead()
    $hashByteArray = $hashAlgorithm.ComputeHash($stream)
    $stream.Close()

    ## We have to be sure that we close the file stream if any exceptions are thrown.
    trap {
        if ($stream -ne $null) { $stream.Close() }
        break
    }

    return [string]$hashByteArray
}

$fileGroups = Get-ChildItem -Path $Path -Recurse |
    Where-Object { $_.Length -gt 0 } |
    Group-Object Length |
    Where-Object { $_.Count -gt 1 }

foreach ($fileGroup in $fileGroups) {
    foreach ($file in $fileGroup.Group) {
        Add-Member -MemberType NoteProperty -Name ContentHash -Value (Get-MD5 $file) -InputObject $file
    }

    $fileGroup.Group |
        Group-Object ContentHash |
        Where-Object { $_.Count -gt 1 }
}

Output Example

Count Name                      Group
----- ----                      -----
    2 187 49 165 178 166 151... {Ann-DS1.imr, Ann-DS1.imr}
    2 230 243 103 209 89 0 1... {MQ02 Mailing Labels Laser for Pat Birthday by Post Dates.imr, MQ02 Mailing Labels Laser for Pat Birthday by Post Dates.imr}
    2 129 199 76 16 247 255 ... {ANN-Folder-Subfolder Listing.imr, ANN-Folder-Subfolder Listing.imr}
    2 16 249 151 209 119 71 ... {Annotation Report.imr, Annotation Report.imr}
    2 114 146 127 255 123 23... {Annotation.mdb, Annotation.mdb}