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 
Test-AnsiblePath()12 Function Test-AnsiblePath {
13     [CmdletBinding()]
14     Param(
15         [Parameter(Mandatory=$true)][string]$Path
16     )
17     # Replacement for Test-Path
18     try {
19         $file_attributes = [System.IO.File]::GetAttributes($Path)
20     } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
21         return $false
22     } catch [NotSupportedException] {
23         # When testing a path like Cert:\LocalMachine\My, System.IO.File will
24         # not work, we just revert back to using Test-Path for this
25         return Test-Path -Path $Path
26     }
27 
28     if ([Int32]$file_attributes -eq -1) {
29         return $false
30     } else {
31         return $true
32     }
33 }
34 
Get-AnsibleItemnull35 Function Get-AnsibleItem {
36     [CmdletBinding()]
37     Param(
38         [Parameter(Mandatory=$true)][string]$Path
39     )
40     # Replacement for Get-Item
41     try {
42         $file_attributes = [System.IO.File]::GetAttributes($Path)
43     } catch {
44         # if -ErrorAction SilentlyCotinue is set on the cmdlet and we failed to
45         # get the attributes, just return $null, otherwise throw the error
46         if ($ErrorActionPreference -ne "SilentlyContinue") {
47             throw $_
48         }
49         return $null
50     }
51     if ([Int32]$file_attributes -eq -1) {
52         throw New-Object -TypeName System.Management.Automation.ItemNotFoundException -ArgumentList "Cannot find path '$Path' because it does not exist."
53     } elseif ($file_attributes.HasFlag([System.IO.FileAttributes]::Directory)) {
54         return New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $Path
55     } else {
56         return New-Object -TypeName System.IO.FileInfo -ArgumentList $Path
57     }
58 }
59 
60 Export-ModuleMember -Function Test-AnsiblePath, Get-AnsibleItem
61