Recently, I ran into an issue when auditing TFS. The issue was related to an intermittent problem where the Powershell script would sometimes work, and sometimes fail. From a developer perspective, this is an impossibility. Code either works or it doesn't. If it sometimes work, then there is most likely something else at play.
Inevitably this lead me down the path of dependencies. I had to ensure that we had the right TFS DLLs loaded for the script. This can easily be done with reflection via the GetAssemblies() method of the CurrentDomain within the AppDomain object in Powershell. The simple command:
[AppDomain]::CurrentDomain.GetAssemblies()
returns a comprehensive list of loaded DLLs. From here you can identify if your DLL is loaded, or as was the case in another session for me, identify that wrong versions of the target DLL is loaded. That's good, but how do I use that logically in Powershell code e.g. when I want to see if a DLL is already loaded before attempting to load it again. (As we know, that throws ugly red text that the operator might mistake for an error rather than the EXPECTED error it is.)
Therefore, using the pipe, we could do something like this:
([AppDomain]::CurrentDomain.GetAssemblies() | where {$_ -match "Microsoft.TeamFoundation.Client"}).Location -eq ""
As you can see, we pipe the output from GetAssemblies() to the where clause attempting to match with the DLL partial name, e.g. "Microsoft.TeamFoundation.Client" in this case.
By wrapping the entire statement in parentheses, we can access the .Location property of the returned object, provided there is one. If there is none, the location value would be blank and by doing an equal check for blank, we can get a boolean result statement that identifies if a given DLL is loaded. :-)
Enjoy
C
The SharePoint Knowledge Collection of Cornelius J. van Dyk, an 9 x SharePoint MVP
27 February 2017
20 February 2017
Beware of [System.Reflection.Assembly]::LoadWithPartialName!!!
If you've been in the Powershell world for any length of time, you will most certainly be familiar with this construct:
[System.Reflection.Assembly]::LoadWithPartialName(...)
This is how we quickly add DLL references to Powershell scripts without having to know the entire name of the DLL in question e.g.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
which loads the Microsoft.SharePoint.dll and makes all the SharePoint cmdlets available to Powershell.
BEWARE!!! In some cases, quickly = lazy = bad.
If you are referencing a DLL that may have more than hone version on the host system, it becomes imperative that you ensure you are actually loading the right DLL. I recently ran into this kind of thing when a script was trying to execute some TFS 2015 commands. The script would fail however, apparently without any logical reason.
It turns out, the reason was quite logical after all. The script was loading the "Microsoft.VisualStudio.TeamFoundation.dll" using the LoadWithPartialName() method. Even with the TFS SDK installed, the script would load the wrong version of the DLL since the 2013 version of the exact same named DLL was in the GAC. Since the GAC trumps everything else, the script would load the old version of the DLL from the GAC and then try to use it with newer versions of related DLLs, hence the failure to execute correctly.
If there's ever any doubt, rather use the best practice LoadFrom() method thus:
[System.Reflection.Assembly]::LoadFrom("C:\Program Files\Common Files\Microsoft Shared\web server extensions\15\ISAPI\Microsoft.SharePoint");
This way, you're 100% guaranteed the proper DLL is loaded and leveraged in your Powershell script.
Enjoy
C
[System.Reflection.Assembly]::LoadWithPartialName(...)
This is how we quickly add DLL references to Powershell scripts without having to know the entire name of the DLL in question e.g.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
which loads the Microsoft.SharePoint.dll and makes all the SharePoint cmdlets available to Powershell.
BEWARE!!! In some cases, quickly = lazy = bad.
If you are referencing a DLL that may have more than hone version on the host system, it becomes imperative that you ensure you are actually loading the right DLL. I recently ran into this kind of thing when a script was trying to execute some TFS 2015 commands. The script would fail however, apparently without any logical reason.
It turns out, the reason was quite logical after all. The script was loading the "Microsoft.VisualStudio.TeamFoundation.dll" using the LoadWithPartialName() method. Even with the TFS SDK installed, the script would load the wrong version of the DLL since the 2013 version of the exact same named DLL was in the GAC. Since the GAC trumps everything else, the script would load the old version of the DLL from the GAC and then try to use it with newer versions of related DLLs, hence the failure to execute correctly.
If there's ever any doubt, rather use the best practice LoadFrom() method thus:
[System.Reflection.Assembly]::LoadFrom("C:\Program Files\Common Files\Microsoft Shared\web server extensions\15\ISAPI\Microsoft.SharePoint");
This way, you're 100% guaranteed the proper DLL is loaded and leveraged in your Powershell script.
Enjoy
C
16 January 2017
Quick Tip - How to migrate your Windows 7 Sticky Notes to Windows 10
With versions of Windows prior to version 10, the little Sticky Notes app that a lot of people depend on for quick notes (we really should use OneNote instead!) was easily transferred from an old computer to a new computer by simply copying the file located here:
%AppData%\Microsoft\Sticky Notes\StickyNotes.snt
to the same location on the new computer. With Windows 10, the Sticky Notes app has graduated to the Microsoft App Store so it changed quite a bit. Notes are no longer stored in that single .snt file and on top of that, there isn't a %AppData%\Microsoft\Sticky Notes folder anywhere to be found.
Fear not. The solution, courtesy of Donovan Lange, an Engineering Manager for Sticky Notes, is pretty simple, though not well documented. The following assumes a NEW computer with Windows 10. If you simply upgrade to Windows 10, Sticky Notes will auto upgrade to the new version.
Simply follow these steps to migrate your old notes from Windows versions prior to 10, to Windows 10:
- Open Windows Explorer.
- In the address bar, paste the following without the quotes: "%AppData%\Microsoft\Sticky Notes".
- Make a copy of the StickyNotes.snt file you find in this folder to transferable media such as a flash drive.
- On the new computer, insert the flash drive and open File Explorer.
- In the address bar, paste the following without the quotes: "%LOCALAPPDATA%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbw\LocalState"
- You will most likely NOT see a "Legacy" folder in this location.
- Right click > New > Folder and name the folder "Legacy" without the quotes.
- Double click to drill down to the Legacy folder.
- Now navigate to your flash drive and copy the "StickyNotes.snt" file.
- Navigate back to the %LOCALAPPDATA%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbw\LocalState\Legacy folder and paste the StickyNotes.snt file here.
- Once copied, right click on StickyNotes.snt and rename the file to "ThresholdNotes.snt" without the quotes.
- Close File Explorer.
- Close the Sticky Notes app.
- Restart the Sticky Notes app.
- You'll be presented with your old notes AND any notes you've taken in the new app. You'll also be asked to upgrade the old notes to the new version at this point.
That's it!
Enjoy
C
C
19 December 2016
Powershell Tip - How to flush the SharePoint config cache
Every SharePoint administrator knows that flushing the config cache becomes necessary from time to time. This has traditionally been a very manual process whereby the .xml files are deleted from the cache folder and then the cache.ini file's content is overwritten with a single character.
The following script makes that an automatic process. The script was generated using my GenPSS utility.
Enjoy
C
The following script makes that an automatic process. The script was generated using my GenPSS utility.
##############################################################################
########################## Clear-SPConfigCache.ps1 ###########################
##############################################################################
Description: === DESCRIPTION HERE ===
Author: Cornelius J. van Dyk | http://blog.cjvandyk.com | @cjvandyk
Version: 1.00
Creation Date: 12/19/2016 12:00:00 AM
Licensed under GPL 3.0 http://opensource.org/licenses/GPL-3.0.
Modified by:
Version:
Modified Date:
Instructions:
1) Simply run this script to clear the SharePoint config cache.
#############################################################################>
##############################################################################
################################# Parameters #################################
##############################################################################
#[CmdletBinding()]
#Param ([Parameter(Mandatory=$true, HelpMessage="PARAMETER 1 PROMPT HERE?")][ValidateNotNullOrEmpty()][string]$PARM1NAME,
# [Parameter(Mandatory=$false, HelpMessage="PARAMETER 2 PROMPT HERE?")][ValidateNotNullOrEmpty()][string]$PARM2NAME)
##############################################################################
############################### Thread Handling ##############################
##############################################################################
#Optimize memory optimization through thread re-use.
if ($ver.Version.Major -gt 1)
{
$Host.Runspace.ThreadOptions = "ReuseThread";
}
##############################################################################
############################### Error Handling ###############################
##############################################################################
#Since the script is intended to run unattended, errors should be suppressed.
$ErrorActionPreference = "SilentlyContinue";
##############################################################################
################################### Modules ##################################
##############################################################################
#Remove the module before re-importing it to ensure the Powershell session
#gets the latest version.
Remove-Module cjvandyk.quix;
Import-Module cjvandyk.quix;
##############################################################################
################################## Snapins ###################################
##############################################################################
Add-pssnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
##############################################################################
################################# Transcript #################################
##############################################################################
#Ensure a new recording is taken by calling Stop-Recording first.
try
{
Stop-Recording;
}
catch {}
#Start the transcript without overwriting any existing file, but appends a
#date/time stamp to the log file name.
Start-Recording;
##############################################################################
################################# Variables ##################################
##############################################################################
# === DEFINE VARIABLES HERE ===
$logFile = ".\Clear-SPConfigCache" + "-" + (Get-Date -Format yyyyMMdd-HHmmss) + ".log"
$cacheFolder = "";
##############################################################################
################################## Functions #################################
##############################################################################
# === DEFINE FUNCTIONS HERE ===
#Log output to screen and log file.
function Log($msg)
{
$t = Get-Date -Format yyyy/MM/dd_HH:mm:ss
Write-Host $t $msg
$t + " " + $msg | Out-File -FilePath $logFile -Append
}
##############################################################################
####################### Ensure script running as Admin #######################
##############################################################################
if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") -eq $false)
{
Write-Host "WARNING! Script is NOT executing in Admin mode. Terminating script." -ForegroundColor Yellow;
Stop-Recording;
Exit(403);
}
##############################################################################
#################################### Main ####################################
##############################################################################
#Stop timer jobs.
Stop-Service SPTimerV4;
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
#Iterate the config folder to find the cache folder.
foreach ($folder in $folders)
{
$items = Get-ChildItem $folder.FullName -Recurse;
foreach ($item in $items)
{
if ($item.Name.ToLower() -eq "cache.ini")
{
$cacheFolder = $folder.FullName;
break; #Folder found now breakout of the loop.
}
}
}
#Get all files in the cache folder.
$cacheFolderItems = Get-ChildItem $cacheFolder -Recurse;
#Delete only the .xml files in the cache folder.
foreach ($cacheFolderItem in $cacheFolderItems)
{
if ($cacheFolderItem -like "*.xml")
{
$cacheFolderItem.Delete();
}
}
#Now delete the content of the cache.ini file.
$cacheFile = Get-Content $cacheFolder\cache.ini;
$cacheFile = 1;
Set-Content $cacheFile -Path $cacheFolder\cache.ini;
#Ensure the operator repeats the process on all SharePoint servers.
Read-Host "Please run this script on all your SharePoint Servers BEFORE pressing ENTER!";
#Restart timer jobs.
Start-Service SPTimerV4;
##############################################################################
#################################### End #####################################
##############################################################################
# Stop recording the transcript.
Stop-Recording;
Enjoy
C
21 November 2016
How do I validate verb validity in Powershell?
So you're about to write a new Powershell cmdlet or script. What verbs can you use in the name? Everyone knows you can just do a quick
Get-Verb
Which would dump out something like this:
Verb Group
---- -----
Add Common
Clear Common
Close Common
Copy Common
Enter Common
Exit Common
Find Common
Format Common
Get Common
Hide Common
Join Common
Lock Common
Move Common
New Common
Open Common
Optimize Common
Pop Common
Push Common
Redo Common
Remove Common
Rename Common
Reset Common
Resize Common
Search Common
Select Common
Set Common
Show Common
Skip Common
Split Common
Step Common
Switch Common
Undo Common
Unlock Common
Watch Common
Backup Data
Checkpoint Data
Compare Data
Compress Data
Convert Data
ConvertFrom Data
ConvertTo Data
Dismount Data
Edit Data
Expand Data
Export Data
Group Data
Import Data
Initialize Data
Limit Data
Merge Data
Mount Data
Out Data
Publish Data
Restore Data
Save Data
Sync Data
Unpublish Data
Update Data
Approve Lifecycle
Assert Lifecycle
Complete Lifecycle
Confirm Lifecycle
Deny Lifecycle
Disable Lifecycle
Enable Lifecycle
Install Lifecycle
Invoke Lifecycle
Register Lifecycle
Request Lifecycle
Restart Lifecycle
Resume Lifecycle
Start Lifecycle
Stop Lifecycle
Submit Lifecycle
Suspend Lifecycle
Uninstall Lifecycle
Unregister Lifecycle
Wait Lifecycle
Debug Diagnostic
Measure Diagnostic
Ping Diagnostic
Repair Diagnostic
Resolve Diagnostic
Test Diagnostic
Trace Diagnostic
Connect Communications
Disconnect Communications
Read Communications
Receive Communications
Send Communications
Write Communications
Block Security
Grant Security
Protect Security
Revoke Security
Unblock Security
Unprotect Security
Use Other
Now you COULD painstakingly go through the mass of verbs... oh right, they're NOT in alphabetical order!!! Well, that's not entirely true. It is in alphabetical order by GROUP. Who gives a damn about Group?!? Ugh.
OK, so we could also just pipe the output to the sort command thus:
Get-Verb | sort Verb
That will result in properly sorted output which would make it easier to locate (or not) the intended verb in the list thereby determining if the verb is valid for use according to best practice guidance. :-)
But all that is a terribly manual process and as anyone who knows me will tell you, once I have to repeat a tedious process for a second or third time, I look for a way to automate it.
That's exactly what I did here too. Presenting...
Get-ValidVerb
This is my little function to do the above quickly and easily. It can easily be compiled into a module that's loaded in your profile so you'll always have access to it. Here's the code:
The script logic is easy.
Get-Verb
Which would dump out something like this:
Verb Group
---- -----
Add Common
Clear Common
Close Common
Copy Common
Enter Common
Exit Common
Find Common
Format Common
Get Common
Hide Common
Join Common
Lock Common
Move Common
New Common
Open Common
Optimize Common
Pop Common
Push Common
Redo Common
Remove Common
Rename Common
Reset Common
Resize Common
Search Common
Select Common
Set Common
Show Common
Skip Common
Split Common
Step Common
Switch Common
Undo Common
Unlock Common
Watch Common
Backup Data
Checkpoint Data
Compare Data
Compress Data
Convert Data
ConvertFrom Data
ConvertTo Data
Dismount Data
Edit Data
Expand Data
Export Data
Group Data
Import Data
Initialize Data
Limit Data
Merge Data
Mount Data
Out Data
Publish Data
Restore Data
Save Data
Sync Data
Unpublish Data
Update Data
Approve Lifecycle
Assert Lifecycle
Complete Lifecycle
Confirm Lifecycle
Deny Lifecycle
Disable Lifecycle
Enable Lifecycle
Install Lifecycle
Invoke Lifecycle
Register Lifecycle
Request Lifecycle
Restart Lifecycle
Resume Lifecycle
Start Lifecycle
Stop Lifecycle
Submit Lifecycle
Suspend Lifecycle
Uninstall Lifecycle
Unregister Lifecycle
Wait Lifecycle
Debug Diagnostic
Measure Diagnostic
Ping Diagnostic
Repair Diagnostic
Resolve Diagnostic
Test Diagnostic
Trace Diagnostic
Connect Communications
Disconnect Communications
Read Communications
Receive Communications
Send Communications
Write Communications
Block Security
Grant Security
Protect Security
Revoke Security
Unblock Security
Unprotect Security
Use Other
Now you COULD painstakingly go through the mass of verbs... oh right, they're NOT in alphabetical order!!! Well, that's not entirely true. It is in alphabetical order by GROUP. Who gives a damn about Group?!? Ugh.
OK, so we could also just pipe the output to the sort command thus:
Get-Verb | sort Verb
That will result in properly sorted output which would make it easier to locate (or not) the intended verb in the list thereby determining if the verb is valid for use according to best practice guidance. :-)
But all that is a terribly manual process and as anyone who knows me will tell you, once I have to repeat a tedious process for a second or third time, I look for a way to automate it.
That's exactly what I did here too. Presenting...
Get-ValidVerb
This is my little function to do the above quickly and easily. It can easily be compiled into a module that's loaded in your profile so you'll always have access to it. Here's the code:
function Get-ValidVerb([string] $verbToCheck)
{
$verbs = Get-Verb | sort Verb;
$list = New-Object -TypeName System.Collections.Generic.List[string];
foreach ($verb in $verbs)
{
$list.Add([string]$verb.Verb.ToLower());
}
return $list.Contains($verbToCheck.ToLower());
}
The script logic is easy.
- The script simply takes a single string argument containing the verb to check for validity.
- In line 3 we capture the output from our (Get-Verb | sort Verb) command to a variable.
- In line 4 we create a .NET List
object that contains strings. - In line 5 we iterate through all items in the dumped list.
- In line 7 we use the .Add() method of the List class to add only the Verb of the item (remember, it has a Group column too) to the list. I added another piece of logic here in that I convert the verb to lowercase with .ToLower() after casting it as a [string] type. This is done in order to allow the next bit of logic...
- Finally in line 9, we leverage the .Contains() method of the List class to check if the verb we're checking, is contained in the list. You'll notice that we cast this verb to check to lower case as well. By casting both the list and the verb to check to lower case, we get a case insensitive comparison. This prevents the problem where Get-ValidVerb "get" will return False because of case different in the G.
Enjoy
C
24 October 2016
RIP Oscar (2003-2016)
He was my good boy, my companion for 14 years. He never asked for much except for some loving belly rubs and the occasional ball to chase down the hall. He was no saint, forcing me to move our gutters in front of the back yard fence. There was not a gutter safe when Oscar thought there might be a chipmunk hiding in there! He was no saint, but he was my good boy.
At times he could let out the stinkiest gas you've ever smelled, but have him sleeping on your lap and you let one out... he'd look at you all disgusted and then hop down and walk away in a manner of disgust that only Oscar could pull off.
He was always with me, ever present. Our morning routine was "Let's go to work boy!" and he'd trot along with me down to the basement and lay on his pillow next to my desk all day long.
Like so many things in life, his time was too short. We laid him to rest yesterday morning and the grief still wells up behind my eyes frequently. I'm going to miss him so much, my good boy.
Thank you Oscar.
Thank you my good boy for 14 great years of selfless love and joy.
Oscar having ice cream.

Oscar belly deep in the basement flood.

Ready to work dad!

I'm exhausted!

I have no idea where that came from dad.

Hey dad, you stopped scratching my belly.

I love my Ouma!

Boy I love my naps.

Ahhh, the fruits of my labor...

Whacha talkin 'bout dad... hole, what hole? You can't prove a thing!

Let me at 'em dad! I'll get that chipmunk!
https://goo.gl/photos/kosNBQUewRYkzKbk7
Of course, his #1 favorite was to kill squeaky toys!
https://goo.gl/photos/pc79D6kyeMPZCY3A6
Thank you my good boy.
Thank you for 14 wonderful years.
THANK YOU!!!
At times he could let out the stinkiest gas you've ever smelled, but have him sleeping on your lap and you let one out... he'd look at you all disgusted and then hop down and walk away in a manner of disgust that only Oscar could pull off.
He was always with me, ever present. Our morning routine was "Let's go to work boy!" and he'd trot along with me down to the basement and lay on his pillow next to my desk all day long.
Like so many things in life, his time was too short. We laid him to rest yesterday morning and the grief still wells up behind my eyes frequently. I'm going to miss him so much, my good boy.
Thank you Oscar.
Thank you my good boy for 14 great years of selfless love and joy.
Oscar having ice cream.
Oscar belly deep in the basement flood.
Ready to work dad!
I'm exhausted!
I have no idea where that came from dad.
Hey dad, you stopped scratching my belly.
I love my Ouma!
Boy I love my naps.
Ahhh, the fruits of my labor...
Whacha talkin 'bout dad... hole, what hole? You can't prove a thing!
Let me at 'em dad! I'll get that chipmunk!
https://goo.gl/photos/kosNBQUewRYkzKbk7
Of course, his #1 favorite was to kill squeaky toys!
https://goo.gl/photos/pc79D6kyeMPZCY3A6
Thank you my good boy.
Thank you for 14 wonderful years.
THANK YOU!!!
17 October 2016
Powershell - Super commands [Invoke-WebRequest]
If you've been playing around with Powershell modules, you've undoubtedly run into the problem of keeping your modules, deployed all over the place on multiple servers, up to date with the latest version. Powershell scripts and modules don't normally fall under traditional application life-cycle management (ALM) processes, so unless you/your organization apply targeted and specific effort toward managing these objects via ALM, you know what a pain mismatched versions can be. We can save the debate over ALM for another day, but the simple fact is, that keeping scripts and modules updated can become tedious.
In my world, I've addressed this problem through the use of an updater module and the very powerful cmdlet called "Invoke-WebRequest".
Invoke-WebRequest is documented here:
https://msdn.microsoft.com/en-us/powershell/reference/4.0/microsoft.powershell.utility/invoke-webrequest
I built a command line app to generate my Powershell script body with all the components I normally use. Part of these components is the loading of the updater module. Once the script has checked that it's running with admin rights and the updater module is loaded, the method in the updater module is called to ensure that the main module is up to date with the latest version. The updater module simply makes a call to Invoke-WebRequest like this:
C:\> Invoke-WebRequest -Uri http://www.sharepointmvp.net/ulsviewer.zip -OutFile C:\data\UlsViewer.zip
The above example simply pulls a zipped copy of ULSViewer down from the internet, so you can test it for yourself. In my case it looks something like this:
C:\> Invoke-WebRequest -Uri http://master-server/Utils.psm1 -OutFile C:\Program Files\WindowsPowerShell\Modules\Utils.psm1
In my world, I've addressed this problem through the use of an updater module and the very powerful cmdlet called "Invoke-WebRequest".
Invoke-WebRequest is documented here:
https://msdn.microsoft.com/en-us/powershell/reference/4.0/microsoft.powershell.utility/invoke-webrequest
I built a command line app to generate my Powershell script body with all the components I normally use. Part of these components is the loading of the updater module. Once the script has checked that it's running with admin rights and the updater module is loaded, the method in the updater module is called to ensure that the main module is up to date with the latest version. The updater module simply makes a call to Invoke-WebRequest like this:
C:\> Invoke-WebRequest -Uri http://www.sharepointmvp.net/ulsviewer.zip -OutFile C:\data\UlsViewer.zip
The above example simply pulls a zipped copy of ULSViewer down from the internet, so you can test it for yourself. In my case it looks something like this:
C:\> Invoke-WebRequest -Uri http://master-server/Utils.psm1 -OutFile C:\Program Files\WindowsPowerShell\Modules\Utils.psm1
This will update the module which is then loaded into the script to provide all the latest features of the script. Now it's important to understand the potential security risk of doing this. The master-server location of the module has to be well protected and tightly controlled. Failure to do so, could result in someone planting some malicious script code into your module and then distributing it to all your servers. Remember that convenience and security are polar opposites. When you increase one, you necessarily decrease the other.
Nevertheless, through this implementation, I am able to manage a central source module for my helper methods that is then re-used in all my scripts. Fixing a bug once, fixes it everywhere. Conversely, breaking a method in the module once, also breaks it everywhere. :-P
I'm sure you can come up with many more useful ways of using Invoke-WebRequest. Let me know in comments about some of your favorite ways to leverage this powerful cmdlet.
Later
C
C
Subscribe to:
Posts (Atom)
SharePoint Remote Event Receivers are DEAD!!!
Well, the time has finally come. It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...
-
Ever wondered what the new SharePoint Online URLs are all about? Take for example https://cjvandyk.sharepoint.us/:x:/r/sites/Site1... What ...
-
Have you ever started creating a list view in SharePoint and because you're experimenting, you chose to make it a "Private" vi...
-
The Microsoft Authentication Library (MSAL) is a powerful library designed to simplify the authentication process for applications that conn...