Debian Codegraph @

test/support/windows-integration/plugins/modules/win_tempfile.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2017, 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 #AnsibleRequires -CSharpUtil Ansible.Basic
7
8 Function New-TempFile {
9 Param ([string]$path, [string]$prefix, [string]$suffix, [string]$type, [bool]$checkmode)
10 $temppath = $null
11 $curerror = $null
12 $attempt = 0
13
14 # Since we don't know if the file already exists, we try 5 times with a random name
15 do {
16 $attempt += 1
17 $randomname = [System.IO.Path]::GetRandomFileName()
18 $temppath = (Join-Path -Path $path -ChildPath "$prefix$randomname$suffix")
19 Try {
20 $file = New-Item -Path $temppath -ItemType $type -WhatIf:$checkmode
21 # Makes sure we get the full absolute path of the created temp file and not a relative or DOS 8.3 dir
22 if (-not $checkmode) {
23 $temppath = $file.FullName
24 } else {
25 # Just rely on GetFulLpath for check mode
26 $temppath = [System.IO.Path]::GetFullPath($temppath)
27 }
28 } Catch {
29 $temppath = $null
30 $curerror = $_
31 }
32 } until (($null -ne $temppath) -or ($attempt -ge 5))
33
34 # If it fails 5 times, something is wrong and we have to report the details
35 if ($null -eq $temppath) {
36 $module.FailJson("No random temporary file worked in $attempt attempts. Error: $($curerror.Exception.Message)", $curerror)
37 }
38
39 return $temppath.ToString()
40 }
41
42 $spec = @{
43 options = @{
44 path = @{ type='path'; default='%TEMP%'; aliases=@( 'dest' ) }
45 state = @{ type='str'; default='file'; choices=@( 'directory', 'file') }
46 prefix = @{ type='str'; default='ansible.' }
47 suffix = @{ type='str' }
48 }
49 supports_check_mode = $true
50 }
51
52 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
53
54 $path = $module.Params.path
55 $state = $module.Params.state
56 $prefix = $module.Params.prefix
57 $suffix = $module.Params.suffix
58
59 # Expand environment variables on non-path types
60 if ($null -ne $prefix) {
61 $prefix = [System.Environment]::ExpandEnvironmentVariables($prefix)
62 }
63 if ($null -ne $suffix) {
64 $suffix = [System.Environment]::ExpandEnvironmentVariables($suffix)
65 }
66
67 $module.Result.changed = $true
68 $module.Result.state = $state
69
70 $module.Result.path = New-TempFile -Path $path -Prefix $prefix -Suffix $suffix -Type $state -CheckMode $module.CheckMode
71
72 $module.ExitJson()