Get commands behind windows explorer context menu verbs - c#

I would like to get the list of windows explorer context menu entitites (verbs) and commands behind it. Something like this:
Open with notepad++ | C:\Program Files\NOtepad++\NppShell_06.dll
Add to archive | C:\Program Files\WinRAR\rarext.dll
Play with VLC | "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"
--started-from-file --no-playlist-enqueue "%1"
and so on.
I've wrote PS script to get all commands from context menu (all the same I can do via C#):
$ErrorActionPreference= 'silentlycontinue'
Set-Location -LiteralPath HKLM:\SOFTWARE\Classes\*\shellex\ContextMenuHandlers;
$o = Get-ChildItem -LiteralPath HKLM:\SOFTWARE\Classes\*\shellex\ContextMenuHandlers;
foreach($obj in $o)
{
$prop = (Get-ItemProperty $obj.PSChildName).'(default)';
"-------------------------------------------------------------";
try
{
$obj.PSChildName;
$sub = (Get-Item -LiteralPath ("HKLM:\SOFTWARE\Classes\CLSID\" + $prop.ToString())).GetSubKeyNames();
foreach($s in $sub)
{
(Get-ItemProperty -LiteralPath ("HKLM:\SOFTWARE\Classes\CLSID\" + $prop.ToString() + "\" + $s)).'(default)';
}
}
catch
{}
}
Output:
-------------------------------------------------------------
ANotepad++64
C:\Program Files\Notepad++\NppShell_06.dll
-------------------------------------------------------------
EPP
C:\Program Files\Windows Defender\shellext.dll
10.0.14393.1198
-------------------------------------------------------------
Open With
C:\Windows\system32\shell32.dll
-------------------------------------------------------------
WinRAR
C:\Program Files\WinRAR\rarext.dll
........
There is script to get verbs for specific file:
$o = new-object -com Shell.Application
$folder = $o.NameSpace("C:\Users\User\Documents")
$file=$folder.ParseName("file.txt")
$file.Verbs() | select *
Output:
Application Parent Name
&Open
&Print
&Edit
Edit with &Notepad++
Check with Windows Defender...
&Add to archive...
Add &to "file.rar"
Compress and email...
Compress to "file.rar" and email
.....
So, I do not know how to combine these solutions. Is there some command/elegant way to do what I want?

Related

Getting the Keyboard Layout in WPF C#

I need to get the Current Windows Keyboard Layout for my WPF application to map each key correctly and handle AZERTY as well as QWERTY and QWERTZ (and so on...)
I noticed a problem since I am working with a French layout (azerty) but my windows is displayed in English.
I tried various methods to get the layout correctly but without results :
var test1 = InputLanguageManager.Current.CurrentInputLanguage;
and
var test2 = CultureInfo.CurrentCulture;
I tried by having ENG language with AZERTY layout, ENG language with QWERTY layout and FRA language with AZERTY layout but the output from my tests were always different. I could get the language displayed correctly (en-GB) but not the layout.
The following PowerShell1 script declares Get-KeyboardLayoutForPid function which reliably gets the Current Windows Keyboard Layout for any process2.
if ( $null -eq ('Win32Functions.KeyboardLayout' -as [type]) ) {
Add-Type -MemberDefinition #'
[DllImport("user32.dll")]
public static extern IntPtr GetKeyboardLayout(uint thread);
'# -Name KeyboardLayout -Namespace Win32Functions
}
Function Get-KeyboardLayoutForPid {
[cmdletbinding()]
Param (
[parameter(Mandatory=$False, ValueFromPipeline=$False)]
[int]$Id = $PID,
# used formerly for debugging
[parameter(Mandatory=$False, DontShow=$True)]
[switch]$Raw
)
$InstalledInputLanguages = [System.Windows.Forms.InputLanguage]::InstalledInputLanguages
$CurrentInputLanguage = [System.Windows.Forms.InputLanguage]::DefaultInputLanguage # CurrentInputLanguage
$CurrentInputLanguageHKL = $CurrentInputLanguage.Handle # just an assumption
### Write-Verbose ('CurrentInputLanguage: {0}, 0x{1:X8} ({2}), {3}' -f $CurrentInputLanguage.Culture, ($CurrentInputLanguageHKL -band 0xffffffff), $CurrentInputLanguageHKL, $CurrentInputLanguage.LayoutName)
Function GetRealLayoutName ( [IntPtr]$HKL ) {
$regBase = 'Registry::' +
'HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layouts'
$LayoutHex = '{0:x8}' -f ($hkl -band 0xFFFFFFFF)
if ( ($hkl -band 0xFFFFFFFF) -lt 0 ) {
$auxKeyb = Get-ChildItem -Path $regBase |
Where-Object {
$_.Property -contains 'Layout Id' -and
(Get-ItemPropertyValue -Path "Registry::$($_.Name)" `
-Name 'Layout Id' `
-ErrorAction SilentlyContinue
) -eq $LayoutHex.Substring(2,2).PadLeft(4,'0')
} | Select-Object -ExpandProperty PSChildName
} else {
$auxKeyb = $LayoutHex.Substring(0,4).PadLeft(8,'0')
}
$KbdLayoutName = Get-ItemPropertyValue -Path (
Join-Path -Path $regBase -ChildPath $auxKeyb
) -ErrorAction SilentlyContinue -Name 'Layout Text'
$KbdLayoutName
# Another option: grab localized string from 'Layout Display Name'
} # Function GetRealLayoutName
Function GetKbdLayoutForPid {
Param (
[parameter(Mandatory=$True, ValueFromPipeline=$False)]
[int]$Id,
[parameter(Mandatory=$False, DontShow=$True)]
[string]$Parent = ''
)
$Processes = Get-Process -Id $Id
$Weirds = #('powershell_ise','explorer') # not implemented yet
$allLayouts = foreach ( $Proces in $Processes ) {
$LayoutsExtra = [ordered]#{}
$auxKLIDs = #( for ( $i=0; $i -lt $Proces.Threads.Count; $i++ ) {
$thread = $Proces.Threads[$i]
## The return value is the input locale identifier for the thread:
$LayoutInt = [Win32Functions.KeyboardLayout]::GetKeyboardLayout( $thread.Id )
$LayoutsExtra[$LayoutInt] = $thread.Id
})
Write-Verbose ('{0,6} ({1,6}) {2}: {3}' -f $Proces.Id, $Parent,
$Proces.ProcessName, (($LayoutsExtra.Keys |
Select-Object -Property #{ N='Handl';E={('{0:x8}' -f ($_ -band 0xffffffff))}} |
Select-Object -ExpandProperty Handl) -join ', '))
foreach ( $auxHandle in $LayoutsExtra.Keys ) {
$InstalledInputLanguages | Where-Object { $_.Handle -eq $auxHandle }
}
$ConHost = Get-WmiObject Win32_Process -Filter "Name = 'conhost.exe'"
$isConsoleApp = $ConHost | Where-Object { $_.ParentProcessId -eq $Proces.Id }
if ( $null -ne $isConsoleApp ) {
GetKbdLayoutForPid -Id ($isConsoleApp.ProcessId) -Parent ($Proces.Id -as [string])
}
}
if ( $null -eq $allLayouts ) {
# Write-Verbose ('{0,6} ({1,6}) {2}: {3}' -f $Proces.Id, $Parent, $Proces.ProcessName, '')
} else {
$allLayouts
}
} # GetKbdLayoutForPid
$allLayoutsRaw = GetKbdLayoutForPid -Id $Id
if ( $null -ne $allLayoutsRaw ) {
if ( ([bool]$PSBoundParameters['Raw']) ) {
$allLayoutsRaw
} else {
$retLayouts = $allLayoutsRaw |
Sort-Object -Property Handle -Unique |
Where-Object { $_.Handle -ne $CurrentInputLanguageHKL }
if ( $null -eq $retLayouts ) { $retLayouts = $CurrentInputLanguage }
$RealLayoutName = $retLayouts.Handle |
ForEach-Object { GetRealLayoutName -HKL $_ }
$ProcessAux = Get-Process -Id $Id
$retLayouts | Add-Member -MemberType NoteProperty -Name 'ProcessId' -Value "$Id"
$retLayouts | Add-Member -MemberType NoteProperty -Name 'ProcessName' -Value ($ProcessAux | Select-Object -ExpandProperty ProcessName )
# $retLayouts | Add-Member -MemberType NoteProperty -Name 'WindowTitle' -Value ($ProcessAux | Select-Object -ExpandProperty MainWindowTitle )
$retLayouts | Add-Member -MemberType NoteProperty -Name 'RealLayoutName' -Value ($RealLayoutName -join ';')
$retLayouts
}
}
<#
.Synopsis
Get the current Windows Keyboard Layout for a process.
.Description
Gets the current Windows Keyboard Layout for a process. Identify the process
using -Id parameter.
.Parameter Id
A process Id, e.g.
- Id property of System.Diagnostics.Process instance (Get-Process), or
- ProcessId property (an instance of the Win32_Process WMI class), or
- PID property from "TaskList.exe /FO CSV", …
.Parameter Raw
Parameter -Raw is used merely for debugging.
.Example
Get-KeyboardLayoutForPid
This example shows output for the current process (-Id $PID).
Note that properties RealLayoutName and LayoutName could differ (the latter is wrong; a bug in [System.Windows.Forms.InputLanguage] implementation?)
ProcessId : 2528
ProcessName : powershell
RealLayoutName : United States-International
Culture : cs-CZ
Handle : -268368891
LayoutName : US
.Example
. D:\PShell\tests\Get-KeyboardLayoutForPid.ps1 # activate the function
Get-Process -Name * |
ForEach-Object { Get-KeyboardLayoutForPid -Id $_.Id -Verbose }
This example shows output for each currently running process, unfortunately
even (likely unusable) info about utility/service processes.
The output itself can be empty for most processes, but the verbose stream
shows (hopefully worthwhile) info where current keboard layout is held.
Note different placement of the current keboard layout ID:
- console application (cmd, powershell, ubuntu): conhost
- combined GUI/console app (powershell_ise) : the app itself
- classic GUI apps (notepad, notepad++, …) : the app itself
- advanced GUI apps (iexplore) : Id ≘ tab
- "modern" GUI apps (MicrosoftEdge*) : Id ≟ tab (unclear)
- combined GUI/service app (explorer) : indiscernible
- etc… (this list is incomplete).
For instance, iexplore.exe creates a separate process for each open window
or tab, so their identifying and assigning input languages is an easy task.
On the other side, explorer.exe creates the only process, regardless of
open visible window(s), so they are indistinguishable by techniques used here…
.Example
gps -Name explorer | % { Get-KeyboardLayoutForPid -Id $_.Id } | ft -au
This example shows where the function could fail in a language multifarious environment:
ProcessId ProcessName RealLayoutName Culture Handle LayoutName
--------- ----------- -------------- ------- ------ ----------
5344 explorer Greek (220);US el-GR -266992632 Greek (220)
5344 explorer Greek (220);US cs-CZ 67699717 US
- scenario:
open three different file explorer windows and set their input languages
as follows (their order does not matter):
- 1st window: let default input language (e.g. Czech, in my case),
- 2nd window: set different input language (e.g. US English),
- 3rd window: set different input language (e.g. Greek).
- output:
an array (and note that default input language window isn't listed).
.Inputs
No object can be piped to the function. Use -Id pameter instead,
named or positional.
.Outputs
[System.Windows.Forms.InputLanguage] extended as follows:
note the <…> placeholder
Get-KeyboardLayoutForPid | Get-Member -MemberType Properties
TypeName: System.Windows.Forms.InputLanguage
Name MemberType Definition
---- ---------- ----------
ProcessId NoteProperty string ProcessId=<…>
ProcessName NoteProperty System.String ProcessName=powershell
RealLayoutName NoteProperty string RealLayoutName=<…>
Culture Property cultureinfo Culture {get;}
Handle Property System.IntPtr Handle {get;}
LayoutName Property string LayoutName {get;}
.Notes
To add the `Get-KeyboardLayoutForPid` function to the current scope,
run the script using `.` dot sourcing operator, e.g. as
. D:\PShell\tests\Get-KeyboardLayoutForPid.ps1
Auhor: https://stackoverflow.com/users/3439404/josefz
Created: 2019-11-24
Revisions:
.Link
.Component
P/Invoke
<##>
} # Function Get-KeyboardLayoutForPid
if ( -not ('System.Windows.Forms.InputLanguage' -as [type]) ) {
Add-Type -AssemblyName System.Windows.Forms
}
The Get-KeyboardLayoutForPid function contains a Comment-Based Help placed at the end of its body. I hope that its principle is implementable in C# easy.
The main idea of my approach:
Suppose that the current keyboard layout (CurrentInputLanguage) for a given process is the (user-dependant) default one (DefaultInputLanguage).
Collect keyboard layouts associated with every thread of given process (allLayoutsRaw). Note this trick for a console application: collect keyboard layouts associated with every thread of child conhost process as well.
If there is a keyboard layout different from DefaultInputLanguage in the allLayoutsRaw collection then it's the sought-after one (retLayouts).
1 Does not work in PowerShell Core (pwsh.exe).
2 Might fail for explorer process in a language multifarious environment, see an example of failing scenario in the Comment-Based help.
I am not sure of the ask - whether you want to know the current keyboard layout or you want to set the keyboard layout.
In both cases, InputLanguageManager should help.
You can try setting input language manager to appropriate cultureInfo object.
This should change the keyboard layout for your WPF application
InputLanguageManager.Current.CurrentInputLanguage = new CultureInfo("fr-FR");

Check every computer in network if specific service runs

For a software update, I need to know if a specific service runs on all computers. And if not, I need to start this service on the missing devices.
Is there a possibility to realize this in C# or PowerShell?
In PowerShell you'd use the *-Service cmdlets. Get-Service can query services on remote hosts via its -ComputerName parameter. The returned services can then be filtered and piped into Start-Service:
$servers = 'FOO', 'BAR', 'BAZ', ...
Get-Service -ComputerName $servers -Name 'svcname' |
? { $_.Status -eq 'Stopped' } |
Start-Service
How to find computers running a particular service has already been answered here:
how to get a pc list that have a service running on each pc?
you should then be able to run Start-Service -Name <Service Name>
I ended up with a mix of all suggestions here and wrote a powershell script.
Any improvements are much appreciated.
$strFilter = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.SearchScope = "Subtree"
$objSearcher.PageSize = 1000
$objSearcher.Filter = "(objectCategory=$strFilter)"
$colResults = $objSearcher.FindAll()
$counter = 0
foreach ($i in $colResults)
{
$objComputer = $i.GetDirectoryEntry()
if (Test-Connection -Computername $objComputer.Name -BufferSize 16 -Count 1 -Quiet) {
Get-Service -ComputerName $objComputer.Name -Name 'svcname' | ? { $_.Status -eq 'Stopped' } | Start-Service
}
$counter++
Write-Host "finished " + $counter
}

Accessing Sharepoint document library list using Windows PowerShell script

Task: I need to loop thru all files on Sharepoint site and download them to local folder.
Script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$s = Get-SPSite “https://abc.abctools.consumer.abc.net/sites/rtc/report/SitePages/Forms/AllPages.aspx”
$files = $s.RootWeb.GetFolder("Shared Documents").Files
foreach ($file in $files) {
Write-host $file.Name
$b = $file.OpenBinary()
$fs = New-Object System.IO.FileStream(("C:\SP Document Library files\"+$file.Name), [System.IO.FileMode]::Create)
$bw = New-Object System.IO.BinaryWriter($fs)
$bw.Write($b)
$bw.Close()
}
Errors: I get when i try to run/execute above script.
1. "You cannot call a method on a null-valued expression."
New-Object: Exception calling ".ctor" with "2" agrument(s): "Could not find a part of the path 'C:\SP Document Library files\'
New-Object: Constructor not found. Cannot find an appropriate constructor for the type system.IO.BinaryWrite.
The term 'Get-SPSite' is not recognized as a cmdlet, function, operable program or script file. verify the term and try again.
Response on Error #2: I have created the folder & named "SP Document Library files" so that path is correct C:\SP Document Library files not sure why i see that msg.
Library files (.csv,.xls) exists in a folder.
Folder name : 2014-01-31.
1. What to do to in order resolve above error message(s).
2. I'm not sure if i need to use whole sharepoint url or part of it.Educate me on that.
Thanks!!
Try by giving ReadWrite FileAccess.
And you can get the root web directly if you know the Url instead of using SPSite.
Here's my script I use and has always worked
$siteUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc”'
$listUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc/Shared Documents”'
$folderPath = 'C:\\....'
$web = Get-SPWeb -Identity $siteUrl
$list = $web.GetList($listUrl)
$items = $list.Items
ForEach ($item in $items)
{
$binary = $item.File.OpenBinary();
$folderPathToSave = $folderPath + "\\" + $item.Name;
if ($binary -ne $null)
{
$stream = New-Object System.IO.FileStream($folderPathToSave,[System.IO.FileMode]::Create,[System.IO.FileAccess]::ReadWrite);
$writer = New-Object System.IO.BinaryWriter($stream);
$writer.Write($binary);
$writer.Close();
}
}
$web.Dispose()
The original post:
http://naimmurati.wordpress.com/2012/06/07/backup-documents-from-document-library-with-powershell-script/

Powershell command to read EventLog

I am reading a event log using a Powershell command like the 1 below:
get-winevent -Path "C:\Test.evtx" -oldest | convertto-xml -as Stream > "C:\Test.xml"
As you can see, I am storing the result in a XML file for later reading.
For few events in the event log, I need a special query as follows:
$evtWithoutMsg = get-winevent -Path "C:\Test.evtx" | Where-Object {($_.RecordId -eq 53593)}
$xmlThing = [xml]$evtWithoutMsg.toxml()
$msg = $xmlThing.Event.EventData.Data
$msg
My question is can I have this '$xmlThing.Event.EventData.Data' as a new node or something in the xml file output (test.xml) of the initial command?

specify build action of content - Nuget

What is the simplest way to tell Nuget package to add all css files as an embedded resource (ie build action is embedded resource).
I am trying to do it through install.ps1 in the tools folder but still cant get anywhere
Note: I am creating the package from the directory structure(tools\content\lib)
This is my install.ps1 which does not work.
param($installPath, $toolsPath, $package, $project)
$MsbNS = #{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'}
function EmbeddContent($ProjectLink, [string]$XPath)
{
$nodes = #(Select-Xml $XPath $ProjectLink -Namespace $MsbNS | Foreach {$_.Node})
foreach ($node in $nodes)
{
if($node.Include.StartsWith("Content\css"))
{
$cet = $node.ownerdocument.CreateElement("EmbeddedResource")
$cet.setAttribute("Include", $node.Include)
$parent = $node.ParentNode
[void]$parent.RemoveChild($node)
[void]$parent.Appendchild($cet)
}
}
}
$project.Save()
$fileLocation = $project.FileName
$dte.ExecuteCommand("Project.UnloadProject");
$proj = [xml](gc $fileLocation)
Embeddcontent $fileLocation '//msb:Project/msb:ItemGroup/msb:Content'
$proj.Save($fileLocation)
Help Please ..
You can use DTE instead of messing with xml to change the BuildAction. From http://nuget.codeplex.com/discussions/227696:
$item = $project.ProjectItems | where-object {$_.Name -eq "ReleaseNotes.txt"}
$item.Properties.Item("BuildAction").Value = [int]3
This link shows the enumeration values:
http://msdn.microsoft.com/en-us/library/aa983962(VS.71).aspx

Categories