It looks like a recent windows update has broken some functionality I was using to recycle IIS6 application pools, as this has been working for months up to today.
Exception calling "Recycle" : "Win32: The object identifier does not representException calling "Recycle" : "Win32: The object identifier does not represent a valid object.
the function I was using to recycle the application pools was:
function recycle-pool($strServerName)
{
$objWMI = [WmiSearcher] "Select * From IIsApplicationPool"
$objWMI.Scope.Path = "\\" + $strServerName + "\root\microsoftiisv2"
$objWMI.Scope.Options.Authentication = 6
$pools = $objWMI.Get()
foreach ($pool in $pools)
{
$pool.recycle()
if (!$?)
{
Write-Host $pool.name " - ERROR"
}
else
{
Write-Host $pool.name " - Recycled"
}
}
Any idea on what the problem is and how I should approach this?
The original question was for IIS6, but I ran into something similar using the WebAdministration Module's Restart-WebAppPool on Windows 2012. So I dropped back to calling AppCMD, and that worked fine:
& $env:windir\system32\inetsrv\appcmd recycle apppool "YOURAPPPOOLNAMEHERE"
Sometimes, you don't have to over-engineer the solution. Hope that helps others some day.
One of the application pools was stopped, which was causing the error. The other application pools were recycling fine. The code above is ok to use for anyone else.
You can try to recycle with ADSI:
$server = "IIsServerName"
$iis = [adsi]"IIS://$server/W3SVC/AppPools"
$iis.psbase.children | foreach {
$pool = [adsi]($_.psbase.path)
$pool.psbase.invoke("recycle")
}
Related
Using Octopus Deploy to deploy a simple API.
The first step of our deployment process is to generate an HTML report with the delta of the scripts run vs the scripts required to run. I used this tutorial to create the step.
The relevant code in my console application is:
var reportLocationSection = appConfiguration.GetSection(previewReportCmdLineFlag);
if (reportLocationSection.Value is not null)
{
// Generate a preview file so Octopus Deploy can generate an artifact for approvals
try
{
var report = reportLocationSection.Value;
var fullReportPath = Path.Combine(report, deltaReportName);
Console.WriteLine($"Generating upgrade report at {fullReportPath}");
upgrader.GenerateUpgradeHtmlReport(fullReportPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return operationError;
}
}
The Powershell which I am using in the script step is:
# Get the extracted path for the package
$packagePath = $OctopusParameters["Octopus.Action.Package[DatabaseUpdater].ExtractedPath"]
$connectionString = $OctopusParameters["Project.Database.ConnectionString"]
$reportPath = $OctopusParameters["Project.HtmlReport.Location"]
Write-Host "Report Path: $($reportPath)"
$exeToRun = "$($packagePath)\DatabaseUpdater.exe"
$generatedReport = "$($reportPath)\UpgradeReport.html"
Write-Host "Generated Report: $($generatedReport)"
if ((test-path $reportPath) -eq $false){
New-Item "Creating new directory..."
} else {
New-Item "Directory already exists."
}
# Run this .NET app, passing in the Connection String and a flag
# which tells the app to create a report, but not update the database
& $exeToRun --connectionString="$($connectionString)" --previewReportPath="$($reportPath)"
New-OctopusArtifact -Path "$($generatedReport)"
The error reported by Octopus is:
'Could not find file 'C:\DeltaReports\Some API\2.9.15-DbUp-Test-9\UpgradeReport.html'.'
I'm guessing that is being thrown when this powershell line is hit: New-OctopusArtifact ...
And that seems to indicate that the report was never created.
I've used a bit of logging to log out certain variables and the values look sound:
Report Path: C:\DeltaReports\Some API\2.9.15-DbUp-Test-9
Generated Report: C:\DeltaReports\Some API\2.9.15-DbUp-Test-9\UpgradeReport.html
Generating upgrade report at C:\DeltaReports\Some API\2.9.15-DbUp-Test-9\UpgradeReport.html
As you can see in the C#, the relevant code is wrapped in a try/catch block, but I'm not sure whether the error is being written out there or at a later point by Octopus (I'd need to do a pull request to add a marker in the code).
Can anyone see a way forward win resolving this? Has anyone else encountered this?
Cheers
I recently redid some of the work from that article for this video up on YouTube. I did run into some issues with the .SQL files not being included in the assembly. I think it was after I upgraded to .NET 6. But that might be a coincidence.
Anyway, because the files weren't being included in the assembly, when I ran the command line app via Octopus, it wouldn't properly generate the file for me. I ended up configuring the project to copy the .SQL files to a folder in the output directory instead of embedding them in the assembly. You can view a sample package here.
One thing that helped me is running the app in a debugger with the same parameters just to make sure it was actually generating the file. I'm sure you already thought of that, but I'd be remiss if I forgot to include it in my answer. :)
FWIW, this is my updated scripts.
First, the Octopus Script:
$packagePath = $OctopusParameters["Octopus.Action.Package[Trident.Database].ExtractedPath"]
$connectionString = $OctopusParameters["Project.Connection.String"]
$environmentName = $OctopusParameters["Octopus.Environment.Name"]
$reportPath = $OctopusParameters["Project.Database.Report.Path"]
cd $packagePath
$appToRun = ".\Octopus.Trident.Database.DbUp"
$generatedReport = "$reportPath\UpgradeReport.html"
& $appToRun --ConnectionString="$connectionString" --PreviewReportPath="$reportPath"
New-OctopusArtifact -Path "$generatedReport" -Name "$environmentName.UpgradeReport.html"
My C# code can be found here but for ease of use, you can see it all here (I'm not proud of how I parse the parameters).
static void Main(string[] args)
{
var connectionString = args.FirstOrDefault(x => x.StartsWith("--ConnectionString", StringComparison.OrdinalIgnoreCase));
connectionString = connectionString.Substring(connectionString.IndexOf("=") + 1).Replace(#"""", string.Empty);
var executingPath = Assembly.GetExecutingAssembly().Location.Replace("Octopus.Trident.Database.DbUp", "").Replace(".dll", "").Replace(".exe", "");
Console.WriteLine($"The execution location is {executingPath}");
var deploymentScriptPath = Path.Combine(executingPath, "DeploymentScripts");
Console.WriteLine($"The deployment script path is located at {deploymentScriptPath}");
var postDeploymentScriptsPath = Path.Combine(executingPath, "PostDeploymentScripts");
Console.WriteLine($"The deployment script path is located at {postDeploymentScriptsPath}");
var upgradeEngineBuilder = DeployChanges.To
.SqlDatabase(connectionString, null)
.WithScriptsFromFileSystem(deploymentScriptPath, new SqlScriptOptions { ScriptType = ScriptType.RunOnce, RunGroupOrder = 1 })
.WithScriptsFromFileSystem(postDeploymentScriptsPath, new SqlScriptOptions { ScriptType = ScriptType.RunAlways, RunGroupOrder = 2 })
.WithTransactionPerScript()
.LogToConsole();
var upgrader = upgradeEngineBuilder.Build();
Console.WriteLine("Is upgrade required: " + upgrader.IsUpgradeRequired());
if (args.Any(a => a.StartsWith("--PreviewReportPath", StringComparison.InvariantCultureIgnoreCase)))
{
// Generate a preview file so Octopus Deploy can generate an artifact for approvals
var report = args.FirstOrDefault(x => x.StartsWith("--PreviewReportPath", StringComparison.OrdinalIgnoreCase));
report = report.Substring(report.IndexOf("=") + 1).Replace(#"""", string.Empty);
if (Directory.Exists(report) == false)
{
Directory.CreateDirectory(report);
}
var fullReportPath = Path.Combine(report, "UpgradeReport.html");
if (File.Exists(fullReportPath) == true)
{
File.Delete(fullReportPath);
}
Console.WriteLine($"Generating the report at {fullReportPath}");
upgrader.GenerateUpgradeHtmlReport(fullReportPath);
}
else
{
var result = upgrader.PerformUpgrade();
// Display the result
if (result.Successful)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Success!");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(result.Error);
Console.WriteLine("Failed!");
}
}
}
I hope that helps!
After long and detailed investigation, we discovered the answer was quite obvious.
We assumed the existing deploy process configuration was sound. Because we never had a problem with it (until now). As it transpires, there was a problem which led to the Development deployments being deployed twice.
Hence, the errors like the one above and others which talked about file handles being held by another process.
It was actually obvious in hindsight, but we were blind to it as we thought the existing process was sound 😣
I've been working on a solution to monitor and respond to certain windows services stopping, and I could really use a few hundred extra sets of eyes on this. I'm setting up the WMI subscription in Powershell and the subscription seems to do it's job, but I'm not getting the expected output using the CommandLineTemplate. I'm trying to push the service name, current state, and previous state to a powershell script or executable (same PS script but compiled) but I only get part of the first variable before it cuts off. I've tried formatting the commandlinetemplate multiple different ways, escaping the variables with single/double/escaped quotes, and tried re-ordering the variables, but it always seems to be part of the first and nothing else gets passed. For testing I'm just trying to grab the variables and write them to a log before I move on to the more fun stuff.
Subscription Code:
$instanceFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()
$instanceFilter.QueryLanguage = "WQL"
$instanceFilter.Query = "select * from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service' AND targetInstance.Name LIKE 'ServiceNamex.%'"
$instanceFilter.Name = "ServiceFilter"
$instanceFilter.EventNamespace = 'root\cimv2'
$result = $instanceFilter.Put()
$newFilter = $result.Path
#Creating a new event consumer
$instanceConsumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance()
$instanceConsumer.Name = 'ServiceConsumer'
$instanceConsumer.CommandLineTemplate = "C:\Tools\ServiceMonitor.exe `"%TargetInstance.Name%`" `"%TargetInstance.State%`" `"%PreviousInstance.State%`""
$instanceConsumer.ExecutablePath = "C:\Tools\ServiceMonitor.exe"
$result = $instanceConsumer.Put()
$newConsumer = $result.Path
#Bind filter and consumer
$instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()
$instanceBinding.Filter = $newFilter
$instanceBinding.Consumer = $newConsumer
$result = $instanceBinding.Put()
$newBinding = $result.Path
Target Code (PS1/EXE):
[CmdletBinding()]
param (
[parameter(Position=0)][string]$serviceName = "Error",
[parameter(Position=1)][string]$currentState = "Error",
[parameter(Position=2)][string]$previousState = "Error"
)
Add-Content -path "C:\temp\service.log" -value "$(Get-Date) - The state of $serviceName on $env:Computername has changed from $previousState to $currentState."
If ($currentState -eq "Stopped")
{
Add-Content -path "C:\temp\service.log" -value "$(Get-Date) - Attempting to restart $serviceName."
Start-Service -DisplayName $serviceName
}
Example Output for ServiceNamex.Funct.QA.12 stopping and starting:
10/30/2019 03:52:11 - The state of ServiceNamex.Funct.QA. has changed to Error.
10/30/2019 03:52:16 - The state of ServiceNamex.Funct.QA. has changed to Error.
Chris, It looks like the issue lies in the variables that you're getting from the first script. I'm not sure where you're getting those variables from. The ServiceMonitor.exe application isn't a PS script and I don't see where the subscription calls out to ServiceMonitor.ps1
Just copying your PS lines into a ServiceMonitor.ps1 file, I was able to run the following command and get the subsequent log information.
.\ServiceMonitor.ps1 TestService Running Stopped
11/01/2019 11:01:24 - The state of TestService on 7D25PX1 has changed from Stopped to Running.
11/01/2019 11:13:11 - The state of TestService on 7D25PX1 has changed from Stopped to Running.
11/01/2019 11:13:44 - The state of TestService on 7D25PX1 has changed from Stopped to Running.
Hopefully that helps to at least point you in the right direction. Feel free to respond with more information and I'll be happy to update the post.
I am using PowerShell Pro Tools to create a GUI application that consists of all the common scripts I would run on a clients server:
main.ps1
main.ps1 loads a ServerConnection form on load:
The code behind this is pretty basic, it just gets the database name and server address for an SQL server:
$btnConfirm_Click = {
$ServerConnectForm.Close();
}
$btnTest_Click = {
## Set database connection variables [global]
$Global:databaseName = $cmbDatabaseName.Text;
$Global:serverAddress = $txtServerAddress.Text;
## Check db connection
$testResult = Invoke-SqlCmd -serverInstance $serverAddress -Database $databaseName -Query "SELECT TOP 1 SettingName FROM Settings";
## Write results to user
if ( $testResult -ne $null ) {
$lblTestResult.ForeColor = "#2acc18";
$lblTestResult.Text = "Test connection successfull";
<# If test connection success enable confirm button #>
$btnConfirm.Enabled = $true;
}
else {
$lblTestResult.ForeColor = "#d61111";
$lblTestResult.Text = "Test connection failed";
}
}
$txtServerAddress_Leave = {
## Get TRIS database list
$databaseList = Invoke-Sqlcmd -ServerInstance $txtServerAddress.Text -Query "
SELECT name FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE' THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[settings]', 'U') END IS NOT NULL
"
## Clear combo box
$cmbDatabaseName.Items.Clear();
## Add to combo box
foreach ($database in $databaseList) {
$cmbDatabaseName.Items.Add($database.ItemArray[0]);
}
}
. (Join-Path $PSScriptRoot 'main.designer.ps1')
$MainForm.ShowDialog()
The problem is that when I either compile this into an executable or run main.ps1 directly from the project folder, none of the code outside of main.ps1 works. The form will show up but I cannot find a way to get the code behind the form to work. For example in the ServerConnection form, adding a server address does not populate the database names and the test connection button does nothing.
Running from within Visual Studio works as intended.
Any help on this would be greatly appreciated.
EDIT :: Show the server connection form call in main.ps1
MainForm_Load
$MainForm_Load = {
## Launch server connection form
. (Join-Path $PSScriptRoot 'ServerConnect.designer.ps1');
$ServerConnectForm.ShowDialog();
## Call prereq analysis
PrereqAnalysis
}
It might be an issue with the scoping of your code.
If code outside the current scope of a session depends on said session, it will not work.
You could try setting the scope of variables and functions to global while you troubleshoot to see if it makes a difference, then change it back until you find where the scope goes wrong.
Microsoft have a good MSDoc page about Powershell scopes
I have a few scripts that create multiple instances of PSDrive to remote instances. I want to make certain that each instance of PSDrive created is cleaned up.
I have a Powershell module like the following. This is a simplified version of what I actually run:
function Connect-PSDrive {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
$Root,
[String]
$Name = [Guid]::NewGuid().ToString(),
[ValidateSet("Registry","Alias","Environment","FileSystem","Function","Variable","Certificate","WSMan")]
[String]
$PSProvider = "FileSystem",
[Switch]
$Persist = $false,
[System.Management.Automation.PSCredential]
$Credential
)
$parameters = #{
Root = $Root;
Name = $Name;
PSProvider = $PSProvider;
Persist = $Persist;
}
$drive = $script:drives | Where-Object {
($_.Name -eq $Name) -or ($_.Root -eq $Root)
}
if (!$drive) {
if ($Credential) {
$parameters.Add("Credential", $Credential)
}
$script:drives += #(New-PSDrive #parameters)
if (Get-PSDrive | Where-Object { $_.Name -eq $Name }) {
Write-Host "The drive '$Name' was created successfully."
}
}
}
function Disconnect-PSDrives {
[CmdletBinding()]
param ()
$script:drives | Remove-PSDrive -Force
}
Each time I invoke the function Connect-PSDrive, I can see that a new drive is successfully created and a reference is added to $script:drives. At the end of the calling script, I have a finally block that invokes Disconnect-PSDrives and this fails with the following exception.
Remove-PSDrive : Cannot find drive. A drive with the name 'mydrive' does not exist.
At C:\git\ops\release-scripts\PSModules\PSDriveWrapper\PSDriveWrapper.psm1:132 char:22
+ $script:drives | Remove-PSDrive -Force
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (mydrive:String) [Remove-PSDrive], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemovePSDriveCommand
I want to know why references to the PSDrive objects I created are available in $script:drives, and yet Remove-PSDrive fails to locate the objects.
I also want to know how I can manage these PSDrive instances without needing to return each instance to the calling script such that Disconnect-PSDrives works.
A few extra notes:
I'm creating these drives with the Persist flag as false.
Running these multiple times errors with too many multiple connections being made to a machine. This is why I think that connections are not being cleaned up. If my assumption is wrong, please kindly explain why connections are cleaned up.
I am a little surprised that it cannot remove from the object reference; but I assume that your issue is with scope. PSDrives are local scope by default so when your function exits, they are no longer visible. Use the -Scope parameter for New-PSDrive and you will likely be successful. (As a side note: during Disconnect-PSDrives you will likely want to clear the list in case of multiple calls.)
That being said, you should never need to clean up the PSDrives like you are doing. Likely the reason you are experiencing too many connections is, once again, a scoping issue (that is, they still exist but you no longer see them). Try running it multiple times where you close PowerShell and start a new instance each time--you will no longer see too many connections. Why? Because PowerShell cleans up all non-persistent drives at the end of your session. You do not need to clean up the drives between sessions/instances; and within an session/instance (assuming you have proper scoping) you can re-use the drives so there is no need to create duplicates; ergo, you should never really need this functionality. That being said, I might assume you have some niche use case for this?
Apparently Microsoft has (sort of) replaced the "Favorites" Windows explorer item with the Quick Access item. But I haven't been able to find a way to programmatically add folders to it (neither on Google not MSDN). Is there no way to do this yet?
There is a simple way to do it in powershell (at least) :
$o = new-object -com shell.application
$o.Namespace('c:\My Folder').Self.InvokeVerb("pintohome")
Hope it helps.
Yohan Ney's answer for pinning an item is correct. To unpin an item you can do this:
$QuickAccess = New-Object -ComObject shell.application
($QuickAccess.Namespace("shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}").Items() | where {$_.Path -eq "C:\Temp"}).InvokeVerb("unpinfromhome")
Here's a script I wrote to make pin/unpin a little easier:
https://gallery.technet.microsoft.com/Set-QuickAccess-117e9a89
Maybe it will help someone until MS releases an API.
I ran procmon and it seems that these registry keys are involved
Pin to Quick access:
HKEY_CLASSES_ROOT\Folder\shell\pintohome
When unpin:
HKEY_CLASSES_ROOT\PinnedFrequentPlace\shell\unpinfromhome\command
Also this resource is used when pinning: (EDIT1: can't find it any longer..)
AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\{SOME_SORT_OF_GUID}.automaticDestinations-ms
You can try opening it with 7-zip, there are several files in there which fit the destination
EDIT2: I found running this in the 'Run' opens up Quick access:
shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}
I got an answer here:
Windows 10 - Programmatically use Quick Access
Apparently, it's not possible yet, but a proposition for such an API has been made.
I like Johan's answer but I added a little bit to make not remove some of the items that were already in there. I had a ton pinned in there by accident I must have selected pin folder or something to quick access.
$QuickAccess = New-Object -ComObject shell.application
$okItems = #("Desktop","Downloads","Documents","Pictures","iCloud Photos","iCloud Drive","PhpstormProjects","Wallpapers 5","Videos", "Schedules for testing")
($QuickAccess.Namespace("shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}").Items() | where {$_.name -notin $okItems}).InvokeVerb("unpinfromhome");
Building on what others have said... This allows you to remove all pinned folders (not just all/recent folders/items):
$o = new-object -com shell.application
$($o.Namespace("shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}").Items() | where { $_.IsFolder -eq "True" -and ($($_.Verbs() | Where-Object {$_.Name -in "Unpin from Quick access"}) -ne $null)}).InvokeVerb("unpinfromhome")
I needed this so I could backup / restore my list of Quick Access links quickly. So I put this at the top of my script (to remove all pinned items, then the rest of the script re-adds them. This ensures the order is correct.
And yes, I'm sure there's a better syntax for the above code.
EDIT: After further investigation, I have realized Quick Access contains two "sections". One is Pinned Items, and the other is Frequent Folders. For some reason, Music and Videos come by default on the second section (at least in 1909), unlike the rest (Desktop/Downloads/Documents/Pictures). So the verb to invoke changes from unpinfromhome to removefromhome (defined in HKEY_CLASSES_ROOT\FrequentPlace, CLSID: {b918dbc4-162c-43e5-85bf-19059a776e9e}). In PowerShell:
$Unpin = #("$env:USERPROFILE\Videos","$env:USERPROFILE\Music")
$qa = New-Object -ComObject shell.application
$ob = $qa.Namespace('shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}').Items() | ? {$_.Path -in $Unpin}
$ob.InvokeVerb('removefromhome')
In Windows 1909, you can't unpin the Music or Videos links from Quick Access with the proposed PowerShell solution. It seems they're special because they don't include the "pin" icon, unlike the rest.
The solution is to pin and unpin them. I don't know much about the Windows API or PowerShell so there may be a less convoluted way.
$Unpin = #("$env:USERPROFILE\Videos","$env:USERPROFILE\Music")
$qa = New-Object -ComObject shell.application
ForEach ($dir in $Unpin) { $qa.Namespace($dir).Self.InvokeVerb('pintohome') }
$ob = $qa.Namespace('shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}').Items() | ? {$_.Path -in $Unpin}
$ob.InvokeVerb('unpinfromhome')
Another way is renaming f01b4d95cf55d32a.automaticDestinations-ms, then logging off/rebooting so that it's recreated. But I don't know if it has side effects. Batch script:
:: f01b4d95cf55d32a => Frequent Folders
:: 5f7b5f1e01b83767 => Recent Files
rename "%APPDATA%\Microsoft\Windows\Recent\AutomaticDestinations\f01b4d95cf55d32a.automaticDestinations-ms" f01b4d95cf55d32a.automaticDestinations-ms.bak
void PinToHome(const std::wstring& folder)
{
ShellExecute(0, L"pintohome", folder.c_str(), L"", L"", SW_HIDE);
}
that was the easy part, still unable to do an unpinfromhome
I was able to get this to work in C# using shell32 based on the information in this post and some info on shell32 from this post https://stackoverflow.com/a/19035049
You need to add a reference to "Microsoft Shell Controls and Automation".
This will add a link
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
Object shell = Activator.CreateInstance(shellAppType);
Shell32.Folder2 f = (Shell32.Folder2)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { "C:\\temp" });
f.Self.InvokeVerb("pintohome");
This will remove a link by name
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
Object shell = Activator.CreateInstance(shellAppType);
Shell32.Folder2 f2 = (Shell32.Folder2)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { "shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}" });
Console.WriteLine("item count: " + f2.Items().Count);
foreach (FolderItem fi in f2.Items())
{
Console.WriteLine(fi.Name);
if (fi.Name == "temp")
{
((FolderItem)fi).InvokeVerb("unpinfromhome");
}
}
For those that work with .NET Core:
Sadly, you cannot include a reference to "Microsoft Shell Controls and Automation" in the build-process.
But you can instead use dynamic, and omit the reference:
public static void PinToQuickAccess(string folder)
{
// You need to include "Microsoft Shell Controls and Automation" reference
// Cannot include reference in .NET Core
System.Type shellAppType = System.Type.GetTypeFromProgID("Shell.Application");
object shell = System.Activator.CreateInstance(shellAppType);
// Shell32.Folder2 f = (Shell32.Folder2)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folder });
dynamic f = shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folder });
f.Self.InvokeVerb("pintohome");
}
And to unpin:
public static void UnpinFromQuickAccess(string folder)
{
// You need to include "Microsoft Shell Controls and Automation" reference
System.Type shellAppType = System.Type.GetTypeFromProgID("Shell.Application");
object shell = System.Activator.CreateInstance(shellAppType);
// Shell32.Folder2 f2 = (Shell32.Folder2)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { "shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}" });
dynamic f2 = shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { "shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}" });
foreach (dynamic fi in f2.Items())
{
if (string.Equals(fi.Path, folder))
{
fi.InvokeVerb("unpinfromhome");
}
}
}