Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_shortcut.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2016, Dag Wieers (@dagwieers) <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 # Based on: http://powershellblogger.com/2016/01/create-shortcuts-lnk-or-url-files-with-powershell/
7
8 #AnsibleRequires -CSharpUtil Ansible.Basic
9 #Requires -Module Ansible.ModuleUtils.AddType
10
11 $spec = @{
12 options = @{
13 src = @{ type = 'str' }
14 dest = @{ type = 'path'; required = $true }
15 state = @{ type = 'str'; default = 'present'; choices = @( 'absent', 'present' ) }
16 arguments = @{ type = 'str'; aliases = @( 'args' ) }
17 directory = @{ type = 'path' }
18 hotkey = @{ type = 'str'; no_log = $false }
19 icon = @{ type = 'path' }
20 description = @{ type = 'str' }
21 windowstyle = @{ type = 'str'; choices = @( 'maximized', 'minimized', 'normal' ) }
22 run_as_admin = @{ type = 'bool'; default = $false }
23 }
24 supports_check_mode = $true
25 }
26
27 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
28
29 $src = $module.Params.src
30 $dest = $module.Params.dest
31 $state = $module.Params.state
32 $arguments = $module.Params.arguments # NOTE: Variable $args is a special variable
33 $directory = $module.Params.directory
34 $hotkey = $module.Params.hotkey
35 $icon = $module.Params.icon
36 $description = $module.Params.description
37 $windowstyle = $module.Params.windowstyle
38 $run_as_admin = $module.Params.run_as_admin
39
40 # Expand environment variables on non-path types
41 if ($null -ne $src) {
42 $src = [System.Environment]::ExpandEnvironmentVariables($src)
43 }
44 if ($null -ne $arguments) {
45 $arguments = [System.Environment]::ExpandEnvironmentVariables($arguments)
46 }
47 if ($null -ne $description) {
48 $description = [System.Environment]::ExpandEnvironmentVariables($description)
49 }
50
51 $module.Result.changed = $false
52 $module.Result.dest = $dest
53 $module.Result.state = $state
54
55 # TODO: look at consolidating other COM actions into the C# class for future compatibility
56 Add-CSharpType -AnsibleModule $module -References @'
57 using System;
58 using System.Runtime.InteropServices;
59 using System.Runtime.InteropServices.ComTypes;
60 using System.Text;
61
62 namespace Ansible.Shortcut
63 {
64 [ComImport()]
65 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
66 [Guid("000214F9-0000-0000-C000-000000000046")]
67 internal interface IShellLinkW
68 {
69 // We only care about GetPath and GetIDList, omit the other methods for now
70 void GetPath(StringBuilder pszFile, int cch, IntPtr pfd, UInt32 fFlags);
71 void GetIDList(out IntPtr ppidl);
72 }
73
74 [ComImport()]
75 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
76 [Guid("45E2b4AE-B1C3-11D0-B92F-00A0C90312E1")]
77 internal interface IShellLinkDataList
78 {
79 void AddDataBlock(IntPtr pDataBlock);
80 void CopyDataBlock(uint dwSig, out IntPtr ppDataBlock);
81 void RemoveDataBlock(uint dwSig);
82 void GetFlags(out ShellLinkFlags dwFlags);
83 void SetFlags(ShellLinkFlags dwFlags);
84 }
85
86 internal class NativeHelpers
87 {
88 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
89 public struct SHFILEINFO
90 {
91 public IntPtr hIcon;
92 public int iIcon;
93 public UInt32 dwAttributes;
94 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)] public char[] szDisplayName;
95 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)] public char[] szTypeName;
96 }
97 }
98
99 internal class NativeMethods
100 {
101 [DllImport("shell32.dll")]
102 public static extern void ILFree(
103 IntPtr pidl);
104
105 [DllImport("shell32.dll")]
106 public static extern IntPtr SHGetFileInfoW(
107 IntPtr pszPath,
108 UInt32 dwFileAttributes,
109 ref NativeHelpers.SHFILEINFO psfi,
110 int sbFileInfo,
111 UInt32 uFlags);
112
113 [DllImport("shell32.dll")]
114 public static extern int SHParseDisplayName(
115 [MarshalAs(UnmanagedType.LPWStr)] string pszName,
116 IntPtr pbc,
117 out IntPtr ppidl,
118 UInt32 sfagoIn,
119 out UInt32 psfgaoOut);
120 }
121
122 [System.Flags]
123 public enum ShellLinkFlags : uint
124 {
125 Default = 0x00000000,
126 HasIdList = 0x00000001,
127 HasLinkInfo = 0x00000002,
128 HasName = 0x00000004,
129 HasRelPath = 0x00000008,
130 HasWorkingDir = 0x00000010,
131 HasArgs = 0x00000020,
132 HasIconLocation = 0x00000040,
133 Unicode = 0x00000080,
134 ForceNoLinkInfo = 0x00000100,
135 HasExpSz = 0x00000200,
136 RunInSeparate = 0x00000400,
137 HasLogo3Id = 0x00000800,
138 HasDarwinId = 0x00001000,
139 RunAsUser = 0x00002000,
140 HasExpIconSz = 0x00004000,
141 NoPidlAlias = 0x00008000,
142 ForceUncName = 0x00010000,
143 RunWithShimLayer = 0x00020000,
144 ForceNoLinkTrack = 0x00040000,
145 EnableTargetMetadata = 0x00080000,
146 DisableLinkPathTracking = 0x00100000,
147 DisableKnownFolderRelativeTracking = 0x00200000,
148 NoKfAlias = 0x00400000,
149 AllowLinkToLink = 0x00800000,
150 UnAliasOnSave = 0x01000000,
151 PreferEnvironmentPath = 0x02000000,
152 KeepLocalIdListForUncTarget = 0x04000000,
153 PersistVolumeIdToRelative = 0x08000000,
154 Valid = 0x0FFFF7FF,
155 Reserved = 0x80000000
156 }
157
158 public class ShellLink
159 {
160 private static Guid CLSID_ShellLink = new Guid("00021401-0000-0000-C000-000000000046");
161
162 public static ShellLinkFlags GetFlags(string path)
163 {
164 IShellLinkW link = InitialiseObj(path);
165 ShellLinkFlags dwFlags;
166 ((IShellLinkDataList)link).GetFlags(out dwFlags);
167 return dwFlags;
168 }
169
170 public static void SetFlags(string path, ShellLinkFlags flags)
171 {
172 IShellLinkW link = InitialiseObj(path);
173 ((IShellLinkDataList)link).SetFlags(flags);
174 ((IPersistFile)link).Save(null, false);
175 }
176
177 public static string GetTargetPath(string path)
178 {
179 IShellLinkW link = InitialiseObj(path);
180
181 StringBuilder pathSb = new StringBuilder(260);
182 link.GetPath(pathSb, pathSb.Capacity, IntPtr.Zero, 0);
183 string linkPath = pathSb.ToString();
184
185 // If the path wasn't set, try and get the path from the ItemIDList
186 ShellLinkFlags flags = GetFlags(path);
187 if (String.IsNullOrEmpty(linkPath) && ((uint)flags & (uint)ShellLinkFlags.HasIdList) == (uint)ShellLinkFlags.HasIdList)
188 {
189 IntPtr idList = IntPtr.Zero;
190 try
191 {
192 link.GetIDList(out idList);
193 linkPath = GetDisplayNameFromPidl(idList);
194 }
195 finally
196 {
197 NativeMethods.ILFree(idList);
198 }
199 }
200 return linkPath;
201 }
202
203 public static string GetDisplayNameFromPath(string path)
204 {
205 UInt32 sfgaoOut;
206 IntPtr pidl = IntPtr.Zero;
207 try
208 {
209 int res = NativeMethods.SHParseDisplayName(path, IntPtr.Zero, out pidl, 0, out sfgaoOut);
210 Marshal.ThrowExceptionForHR(res);
211 return GetDisplayNameFromPidl(pidl);
212 }
213 finally
214 {
215 NativeMethods.ILFree(pidl);
216 }
217 }
218
219 private static string GetDisplayNameFromPidl(IntPtr pidl)
220 {
221 NativeHelpers.SHFILEINFO shFileInfo = new NativeHelpers.SHFILEINFO();
222 UInt32 uFlags = 0x000000208; // SHGFI_DISPLAYNAME | SHGFI_PIDL
223 NativeMethods.SHGetFileInfoW(pidl, 0, ref shFileInfo, Marshal.SizeOf(typeof(NativeHelpers.SHFILEINFO)), uFlags);
224 return new string(shFileInfo.szDisplayName).TrimEnd('\0');
225 }
226
227 private static IShellLinkW InitialiseObj(string path)
228 {
229 IShellLinkW link = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_ShellLink)) as IShellLinkW;
230 ((IPersistFile)link).Load(path, 0);
231 return link;
232 }
233 }
234 }
235 '@
236
237 # Convert from window style name to window style id
238 $windowstyles = @{
239 normal = 1
240 maximized = 3
241 minimized = 7
242 }
243
244 # Convert from window style id to window style name
245 $windowstyleids = @( "", "normal", "", "maximized", "", "", "", "minimized" )
246
247 If ($state -eq "absent") {
248 If (Test-Path -LiteralPath $dest) {
249 # If the shortcut exists, try to remove it
250 Try {
251 Remove-Item -LiteralPath $dest -WhatIf:$module.CheckMode
252 }
253 Catch {
254 # Report removal failure
255 $module.FailJson("Failed to remove shortcut '$dest'. ($($_.Exception.Message))", $_)
256 }
257 # Report removal success
258 $module.Result.changed = $true
259 }
260 Else {
261 # Nothing to report, everything is fine already
262 }
263 }
264 ElseIf ($state -eq "present") {
265 # Create an in-memory object based on the existing shortcut (if any)
266 $Shell = New-Object -ComObject ("WScript.Shell")
267 $ShortCut = $Shell.CreateShortcut($dest)
268
269 # Compare existing values with new values, report as changed if required
270
271 If ($null -ne $src) {
272 # Windows translates executables to absolute path, so do we
273 If (Get-Command -Name $src -Type Application -ErrorAction SilentlyContinue) {
274 $src = (Get-Command -Name $src -Type Application).Definition
275 }
276 If (-not (Test-Path -LiteralPath $src -IsValid)) {
277 If (-not (Split-Path -Path $src -IsAbsolute)) {
278 $module.FailJson("Source '$src' is not found in PATH and not a valid or absolute path.")
279 }
280 }
281 }
282
283 # Determine if we have a WshShortcut or WshUrlShortcut by checking the Arguments property
284 # A WshUrlShortcut objects only consists of a TargetPath property
285
286 $file_shortcut = $false
287 If (Get-Member -InputObject $ShortCut -Name Arguments) {
288 # File ShortCut, compare multiple properties
289 $file_shortcut = $true
290
291 $target_path = $ShortCut.TargetPath
292 If (($null -ne $src) -and ($ShortCut.TargetPath -ne $src)) {
293 if ((Test-Path -LiteralPath $dest) -and (-not $ShortCut.TargetPath)) {
294 # If the shortcut already exists but not on the COM object, we
295 # are dealing with a shell path like 'shell:RecycleBinFolder'.
296 $expanded_src = [Ansible.Shortcut.ShellLink]::GetDisplayNameFromPath($src)
297 $actual_src = [Ansible.Shortcut.ShellLink]::GetTargetPath($dest)
298 if ($expanded_src -ne $actual_src) {
299 $module.Result.changed = $true
300 $ShortCut.TargetPath = $src
301 }
302 }
303 else {
304 $module.Result.changed = $true
305 $ShortCut.TargetPath = $src
306 }
307 $target_path = $src
308 }
309
310 # This is a full-featured application shortcut !
311 If (($null -ne $arguments) -and ($ShortCut.Arguments -ne $arguments)) {
312 $module.Result.changed = $true
313 $ShortCut.Arguments = $arguments
314 }
315 $module.Result.args = $ShortCut.Arguments
316
317 If (($null -ne $directory) -and ($ShortCut.WorkingDirectory -ne $directory)) {
318 $module.Result.changed = $true
319 $ShortCut.WorkingDirectory = $directory
320 }
321 $module.Result.directory = $ShortCut.WorkingDirectory
322
323 # FIXME: Not all values are accepted here ! Improve docs too.
324 If (($null -ne $hotkey) -and ($ShortCut.Hotkey -ne $hotkey)) {
325 $module.Result.changed = $true
326 $ShortCut.Hotkey = $hotkey
327 }
328 $module.Result.hotkey = $ShortCut.Hotkey
329
330 If (($null -ne $icon) -and ($ShortCut.IconLocation -ne $icon)) {
331 $module.Result.changed = $true
332 $ShortCut.IconLocation = $icon
333 }
334 $module.Result.icon = $ShortCut.IconLocation
335
336 If (($null -ne $description) -and ($ShortCut.Description -ne $description)) {
337 $module.Result.changed = $true
338 $ShortCut.Description = $description
339 }
340 $module.Result.description = $ShortCut.Description
341
342 If (($null -ne $windowstyle) -and ($ShortCut.WindowStyle -ne $windowstyles.$windowstyle)) {
343 $module.Result.changed = $true
344 $ShortCut.WindowStyle = $windowstyles.$windowstyle
345 }
346 $module.Result.windowstyle = $windowstyleids[$ShortCut.WindowStyle]
347 }
348 else {
349 # URL Shortcut, just compare the TargetPath
350 if (($null -ne $src) -and ($ShortCut.TargetPath -ne $src)) {
351 $module.Result.changed = $true
352 $ShortCut.TargetPath = $src
353 }
354 $target_path = $ShortCut.TargetPath
355 }
356 $module.Result.src = $target_path
357
358 If (($module.Result.changed -eq $true) -and ($module.CheckMode -ne $true)) {
359 Try {
360 $ShortCut.Save()
361 }
362 Catch {
363 $module.FailJson("Failed to create shortcut '$dest'. ($($_.Exception.Message))", $_)
364 }
365 }
366
367 if ((Test-Path -LiteralPath $dest) -and $file_shortcut) {
368 # Only control the run_as_admin flag if using a File Shortcut
369 $flags = [Ansible.Shortcut.ShellLink]::GetFlags($dest)
370 if ($run_as_admin -and (-not $flags.HasFlag([Ansible.Shortcut.ShellLinkFlags]::RunAsUser))) {
371 [Ansible.Shortcut.ShellLink]::SetFlags($dest, ($flags -bor [Ansible.Shortcut.ShellLinkFlags]::RunAsUser))
372 $module.Result.changed = $true
373 }
374 elseif (-not $run_as_admin -and ($flags.HasFlag([Ansible.Shortcut.ShellLinkFlags]::RunAsUser))) {
375 [Ansible.Shortcut.ShellLink]::SetFlags($dest, ($flags -bxor [Ansible.Shortcut.ShellLinkFlags]::RunAsUser))
376 $module.Result.changed = $true
377 }
378 }
379 }
380
381 $module.ExitJson()