Debian Codegraph @

lib/ansible/module_utils/powershell/Ansible.ModuleUtils.FileUtil.psm1

raw
1 # Copyright (c) 2017 Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 <#
5 Test-Path/Get-Item cannot find/return info on files that are locked like
6 C:\pagefile.sys. These 2 functions are designed to work with these files and
7 provide similar functionality with the normal cmdlets with as minimal overhead
8 as possible. They work by using Get-ChildItem with a filter and return the
9 result from that.
10 #>
11
12 Function Test-AnsiblePath {
13 [CmdletBinding()]
14 Param(
15 [Parameter(Mandatory = $true)][string]$Path
16 )
17
18 # First check what the provider is based on the drive or PSPath provided.
19 $provider = $drive = $null
20 try {
21 $null = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path, [ref]$provider, [ref]$drive)
22 }
23 catch [System.Management.Automation.DriveNotFoundException] {
24 # If the drive doesn't exist, the path cannot exist in any context to PowerShell.
25 return $false
26 }
27
28 # A UNC path is always seen as the current provider location so check if it
29 # starts with \\ and treat it as a FileSystem path.
30 if ($provider.Name -eq "FileSystem" -or $Path.StartsWith("\\")) {
31 try {
32 $file_attributes = [System.IO.File]::GetAttributes($Path)
33 }
34 catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
35 return $false
36 }
37
38 return [int]$file_attributes -ne -1
39 }
40 else {
41 # Otherwise just fallback to Test-Path for the other providers.
42 return Test-Path -Path $Path
43 }
44 }
45
46 Function Get-AnsibleItem {
47 [CmdletBinding()]
48 Param(
49 [Parameter(Mandatory = $true)][string]$Path
50 )
51 # Replacement for Get-Item
52 try {
53 $file_attributes = [System.IO.File]::GetAttributes($Path)
54 }
55 catch {
56 # if -ErrorAction SilentlyCotinue is set on the cmdlet and we failed to
57 # get the attributes, just return $null, otherwise throw the error
58 if ($ErrorActionPreference -ne "SilentlyContinue") {
59 throw $_
60 }
61 return $null
62 }
63 if ([Int32]$file_attributes -eq -1) {
64 throw New-Object -TypeName System.Management.Automation.ItemNotFoundException -ArgumentList "Cannot find path '$Path' because it does not exist."
65 }
66 elseif ($file_attributes.HasFlag([System.IO.FileAttributes]::Directory)) {
67 return New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $Path
68 }
69 else {
70 return New-Object -TypeName System.IO.FileInfo -ArgumentList $Path
71 }
72 }
73
74 Export-ModuleMember -Function Test-AnsiblePath, Get-AnsibleItem