-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemp.psm1
More file actions
55 lines (46 loc) · 1.82 KB
/
Temp.psm1
File metadata and controls
55 lines (46 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Using module .\Logging.psm1
function Get-NamedTempFolder {
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Name,
[switch]$ForceEmpty
)
[String]$Local:Folder = [System.IO.Path]::GetTempPath() | Join-Path -ChildPath $Name;
if ($ForceEmpty -and (Test-Path $Local:Folder -PathType Container)) {
Invoke-Verbose -Message "Emptying temporary folder $Local:Folder...";
Remove-Item -Path $Local:Folder -Force -Recurse | Out-Null;
}
if (-not (Test-Path $Local:Folder -PathType Container)) {
Invoke-Verbose -Message "Creating temporary folder $Local:Folder...";
New-Item -ItemType Directory -Path $Local:Folder | Out-Null;
} elseif (Test-Path $Local:Folder -PathType Container) {
Invoke-Verbose -Message "Temporary folder $Local:Folder already exists.";
if ($ForceEmpty) {
Invoke-Verbose -Message "Emptying temporary folder $Local:Folder...";
Remove-Item -Path $Local:Folder -Force -Recurse | Out-Null;
}
}
return $Local:Folder;
}
function Get-UniqueTempFolder {
Get-NamedTempFolder -Name ([System.IO.Path]::GetRandomFileName()) -ForceEmpty;
}
function Invoke-WithinEphemeral {
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock]$ScriptBlock
)
[String]$Local:Folder = Get-UniqueTempFolder;
try {
Invoke-Verbose -Message "Executing script block within temporary folder $Local:Folder...";
Push-Location -Path $Local:Folder;
& $ScriptBlock;
} finally {
Invoke-Verbose -Message "Cleaning temporary folder $Local:Folder...";
Pop-Location;
Remove-Item -Path $Local:Folder -Force -Recurse;
}
}
Export-ModuleMember -Function Get-NamedTempFolder, Get-UniqueTempFolder, Invoke-WithinEphemeral;