Refresh ConfigMgr content where it’s needed

This script will check for content that needs to be refreshed, in this case its content of types like packages, applications, drivers, etc that have the state Retrying or Failed on one or more DPs.
When the script find some content error it will refresh on that DP.

    $sccmServer = "",
    $sccmSiteCode = "ABC",
    $failStates = "2, 3, 5, 6", # Retrying and Failed (Both Install and Removal)
    $packageTypes = "0, 3, 4, 8, 257, 258" # Not checking 5 (SUP) due to automatic deployments

Write-Host "Searching for failed content distributions"
ForEach ($FailedDist in (Get-WmiObject -ComputerName $sccmServer -Namespace "ROOTSMSSite_$($sccmSiteCode)" -Query "SELECT * FROM SMS_PackageStatusDistPointsSummarizer WHERE State IN ($($failStates)) AND PackageType IN ($($packageTypes))" | Sort-Object PackageID)) {
    # Figure out servername from NalPath
    $failedServer = $FailedDist.ServerNALPath.Substring($FailedDist.ServerNALPath.LastIndexOf("]")+3).Trim("")

    # Get the distribution points that content wouldn't distribute to
    ForEach ($FailedDPDist in (Get-WmiObject -ComputerName $sccmServer -Namespace "ROOTSMSSite_$($sccmSiteCode)" -Query "SELECT * FROM SMS_DistributionPoint WHERE SiteCode='$($FailedDist.SiteCode)' AND PackageID='$($FailedDist.PackageID)' AND ServerNALPath LIKE '%$($failedServer)%'") ) {
        # Refresh content on the selected DP
        Write-Host "Refreshing $($FailedDPDist.PackageID), type $($FailedDist.PackageType) in state $($FailedDist.State) on $($failedServer)"
        $FailedDPDist.RefreshNow = $true
        $FailedDPDist.Put() | Out-Null

Write-Host "Done!"

Merry Instagram Christmas

OK, this post might be a bit late… But if you have a Instagramoholic friend that you don’t know what to give for christmas, this might be the thing. 🙂

Running this will output an image of all (Well, a big chunk at least) of the users Instagram images in one single image, then just order a nice print and you are set for christmas.

Will look something like this if you use my account

    $UserName = "rirofal",
    $DownloadPath = "C:ScriptspsInstaMozDL",
    $outputImageName = "C:Scriptsmozaic.jpg",
    $instaImageSize = 250,
    $maxNofImages = 1600

if(!(Test-Path $DownloadPath)) { 
    Throw "Cant access $($DownloadPath)"

$JsonData = Invoke-WebRequest "$($UserName)/media" | ConvertFrom-Json

$imgNo = 0
while ( $JsonData.more_available -eq $true ) {
    foreach ($item in $JsonData.items) {
        $ImageURL = $item.images.standard_resolution.url
        $ImageDownloadPath = Join-Path -Path $DownloadPath -ChildPath $ImageURL.Split('/')[-1]

        if( !(Test-Path $ImageDownloadPath) ){
            Write-Host "Downloading $($ImageDownloadPath)"
            Invoke-WebRequest $ImageURL -OutFile $ImageDownloadPath
        } else {
            Write-Host "Allready downloaded $($ImageDownloadPath)"
        $imgNo ++

    if ($imgNo -gt $maxNofImages) {
        Write-Host "Reached max of $($maxNofImages)"

    $LastID = ($JsonData.items | Select -Last 1).id
    $JsonData = Invoke-WebRequest "$($UserName)/media?max_id=$LastID" | ConvertFrom-Json

# Read local files and calulate output image size
$localFiles = Get-ChildItem -Path $DownloadPath
Write-Host "Downloaded $($localFiles.Count) files"

$sqrtCount = [math]::Sqrt($localFiles.Count)

Write-Host "Square is $($sqrtCount) images"

$absSqrtCount = [math]::floor($sqrtCount)
Write-Host "Rounded down number is $([int] $absSqrtCount)"

[int] $outputImageSize = $absSqrtCount * $instaImageSize
Write-Host "Resulting ImageSize will be $($outputImageSize) px"

# Start to create output image
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null

$outFile = New-Object System.Drawing.Bitmap( $outputImageSize,  $outputImageSize )

Write-Host "Selecting $($absSqrtCount * $absSqrtCount) random local files"
$localFiles = $localFiles | Get-Random -Count ($absSqrtCount * $absSqrtCount)

$x = 0
$y = 0

$outImage = [System.Drawing.Graphics]::FromImage($outFile)
$outImage.SmoothingMode = "AntiAlias"

foreach ($localImage in $localFiles) {
    Write-Host "Adding $($localImage.FullName) to output image at X: $($x), Y: $($y)"

    $srcImg = [System.Drawing.Image]::FromFile($localImage.FullName)
    $outImage.DrawImage($srcImg, $x, $y, $instaImageSize, $instaImageSize)

    $x = $x + $instaImageSize
    if ($x -gt ($outputImageSize - $instaImageSize) ) {
        $y = $y + $instaImageSize
        $x = 0

Write-Host "Saving JPEG to $($outputImageName)"
$$outputImageName, [System.Drawing.Imaging.ImageFormat]::Jpeg)

A big thanks to for Instagram downloader code.

Get Powershell ISE to run scripts with -Verbose flag

Missing an easy way to run your scripts from ISE with the -Verbose or -Debug flag?

Easy to add… Open up your Microsoft.PowerShellISE_profile.ps1 file and add the following lines:

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Run with -Verbose', { Invoke-Expression -Command ". '$($psISE.CurrentFile.FullPath)' -Verbose" }, 'Ctrl+F5') | Out-Null
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Run with -Debug',   { Invoke-Expression -Command ". '$($psISE.CurrentFile.FullPath)' -Debug" }, 'Ctrl+F6') | Out-Null

Now when you restart ISE you should see the options under the Add-Ons menu.

Auto load command history

With these few lines in your Powershell Profile you will auto load the command history from the last session.

Run “notepad $profile” and add this:

Function Save-CommandHistory {
	$xmlPath = Join-Path (Split-Path $profile.CurrentUserAllHosts) "commandHistory.xml"
	Write-Verbose "Saving to $($xmlPath)"
	Get-History | Export-Clixml -Path $xmlPath

Function Load-CommandHistory {
	$xmlPath = Join-Path (Split-Path $profile.CurrentUserAllHosts) "commandHistory.xml"
	Write-Verbose "Loading from $($xmlPath)"
	Add-History -InputObject (Import-Clixml -Path $xmlPath)

Function Prompt {
	# Save the history
	# Show a prompt
	Write-Host "PS $($PWD.Path.Replace('Microsoft.PowerShell.CoreFileSystem::', ''))>" -NoNewline

Write-Host "Loading command history..."


SQL in Powershell without cmdlets

I am currently playing around with ConfigMgr 2012 cmdlets… and they only run in X86 (*doh*).

Anyway, I need to query a database with information about some collections and other stuff I need to create… and running SQL Server cmdlets in X86 doesn’t work.

So to get this to work I found a Powershell function that uses SqlClient from .NET instead… I rewrote the function a bit and here is the result:

Function Run-SqlQuery {
		[string] $Server = ".",
		[string] $Database = "master",
		[string] $Query,
		[Int32]  $QueryTimeout=60
	$sqlConnection = New-Object System.Data.SqlClient.SQLConnection
	$sqlConnection.ConnectionString = "Data Source=$($Server);Initial Catalog=$($Database);Integrated Security=True;"
	$sqlCommand = New-Object System.Data.SqlClient.SqlCommand($Query,$sqlConnection)
	$sqlCommand.CommandTimeout = $QueryTimeout
	$sqlDataSet = New-Object System.Data.DataSet
	$sqlDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($sqlCommand)

	return $sqlDataSet.Tables[0]

Then you can use it like this:

Run-SqlQuery -Query "EXEC SP_HelpDB"
Run-SqlQuery -Query "SELECT Col1, Col2 FROM MyTable" -Database "MyDatabase" -Server "SomeServer" | Format-Table -AutoSize

This can probably be useful if you need to run a SQL command from a box where your’e not sure if you have SQL cmlets or not.

Logon Scripts in Powershell – Part4: Trigger ConfigMgr client actions

With the ConfigMgr agent in place on your client’s you probably want to force it to start some client actions on logon to speed up deployment of new applications.

This function will work with the ConfigMgr 2007 (on x86) and 2012 agent. (The reason for not working on a Win7 x64 and ConfigMgr 2007 is the lack of X64 support).

Function Run-ConfigMgrActions {
		Trigger ConfigMgr client actions
		[string] $actionFilter1 = "Application Global Evaluation Task*",
		[string] $actionFilter2 = "Request ? Evaluate*"

	Write-Verbose "Run-ConfigMgrActions: Start actions with filter '$($actionFilter1)' or '$($actionFilter2)'"
	TRY {
		(New-Object -ComObject CPApplet.cpAppletMgr).GetClientActions() | Where-Object {$_.Name -like $actionFilter1 -or $_.Name -like $actionFilter2} | Sort-Object Name | ForEach-Object {
			Write-Verbose "Run-ConfigMgrActions: Starting ConfigMgr action: $($_.Name)"
		Write-Verbose "Run-ConfigMgrActions: Can't find and/or trigger ConfigMgr Agent"

Logon Scripts in Powershell – Part3: Storing and retrieving shares to map to/from AD

To keep you logon scripts static one way of storing information on who sould get what mapped is to use the Active Directory.

First of, talk to the AD-guys and “reserve” 3 attributes on groups (or extend the schema and add your own attributes). You need attributes for:
– Share Path
– Display Name
– Type of mapping

In the example I will use:
– displayName = Share Path
– displayNamePrintable = Display Name
– extensionAttribute3 = Type of mapping (I will use a 1 for “Network Location”, 0 for not in use and letters to map to a specific drive)

Then, populate the groups with information:

Import-Module ActiveDirectory

Get-Adgroup "MyGroupName" | Set-ADGroup -Replace @{
	DisplayNamePrintable="Some Description";
Get-Adgroup "SomeOtherGroupName" | Set-ADGroup -Replace @{
	DisplayNamePrintable="Some Description";

Get-Adgroup "ProjXDocs" | Set-ADGroup -Replace @{
	DisplayNamePrintable="ProjectX Documents";

Then, retrieve the groups for the current user with a recursive LDAP-query.

Function Get-SharesToMap {
		Read groups in AD for a user, then collect information to use when mapping disk
		$UserDN = (Get-UserDN)

	$mappedShares = @()
	$ldapFilter = "(&(member:1.2.840.113556.1.4.1941:=$($UserDN))(displayName=*)(extensionAttribute3=*)(!extensionAttribute3=0))"

	Run-LdapQuery -ldapFilter $ldapFilter | ForEach-Object {
		Write-Verbose "Get-SharesToMap: $($ssabMappedSharePath) - Mapping: $($ssabMappedShare)"
		$shareInfo = New-Object -TypeName System.Object
		$shareInfo | add-Member -memberType NoteProperty -name Group -Value $_.Properties.Item("cn")
		$shareInfo | add-Member -memberType NoteProperty -name Path -Value $_.Properties.Item('displayName')
		$shareInfo | add-Member -memberType NoteProperty -name DisplayName -Value $_.Properties.Item('displayNamePrintable')
		$shareInfo | add-Member -memberType NoteProperty -name MappedShare -Value $_.Properties.Item('extensionAttribute3')
		$mappedShares += $shareInfo

	Return $mappedShares

Now you have a list of all shares to take care of…

Get-SharesToMap | Sort-Object Path | ForEach-Object {
	$Path        = $_.Path
	$MappedShare = $_.MappedShare
	$DisplayName = $_.DisplayName

	# Map UNC path once
	If ($lastMappedPath -ne $Path) {
		Switch -regex ($MappedShare) {
			0        { Write-Verbose "Loginscript:Main: Do not map UNC path $($UncPath)" }
			1        { Create-NethoodShortcut -LinkTarget $Path -LinkName $DisplayName -Description $DisplayName }
			"[A-Z]"  { Map-UncPathToDrive -UncPath $Path -DriveLetter $MappedShare }
			default  { Write-Verbose "Loginscript:Main: $($MappedShare) Do not map path $($Path)" }
		$lastMappedPath = $Path

With this in place, no one needs to edit the logonscript to change mappings. 🙂

Sidenote 1:
To speed up the LDAP-queries add indexes on the attributes.
Start MMC
Add the snapin “Active Directory Schema”
Search for the attribute(s)
On the properties-page, check the box “Index this attribute”

Sidenote 2:
To make it easy to search the attributes, check the box “Ambigous Name Resolution (ANR)” in the properties page for the attribute
With ANR enabled you can do a LDAP-query like:
So, if someone wants to be member of the group for the share “ProjectX” just query like (ANR=ProjectX) and the group for that share will show up.