Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 1 docs/testing-guidelines/PowerShellCoreTestStatus.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ The follow table represents the test coverage of the PowerShell Core Cmdlets in
|Select-String|delivered|delivered|yes|
|ConvertFrom-StringData|delivered|delivered|yes|
|Format-Table|delivered|delivered|yes|
|New-TemporaryDirectory|delivered|delivered|yes|
|New-TemporaryFile|delivered|delivered|yes|
|New-TimeSpan|delivered|delivered|yes|
|Get-TimeZone||delivered|yes|
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.IO;
using System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The implementation of the "New-TemporaryDirectory" cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.New, "TemporaryDirectory", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097032")]
[OutputType(typeof(System.IO.DirectoryInfo))]
public class NewTemporaryDirectoryCommand : Cmdlet
{
/// <summary>
/// Gets or sets an optional prefix for the temporary directory name.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Prefix { get; set; }

/// <summary>
/// Returns a temporary directory.
/// </summary>
protected override void EndProcessing()
{
string tempPath = Path.GetTempPath();

if (!string.IsNullOrEmpty(Prefix))
{
DirectoryInfo prefixedTargetDirectory = GetTemporaryDirectoryWithPrefix(tempPath, Prefix);
if (ShouldProcess(prefixedTargetDirectory.FullName))
{
try
{
DirectoryInfo createdDirectory = CreateTemporaryDirectory(prefixedTargetDirectory.FullName);
WriteObject(createdDirectory);
}
catch (IOException ioException)
{
ThrowTerminatingError(
CreateErrorRecord(
ioException,
ErrorCategory.WriteError,
prefixedTargetDirectory.FullName));
}
catch (System.UnauthorizedAccessException unauthorizedAccessException)
{
ThrowTerminatingError(
CreateErrorRecord(
unauthorizedAccessException,
ErrorCategory.PermissionDenied,
prefixedTargetDirectory.FullName));
}
}

return;
}

DirectoryInfo targetDirectory = PathUtils.GetTemporaryDirectory();
if (ShouldProcess(targetDirectory.FullName))
{
try
{
DirectoryInfo createdDirectory = Directory.CreateDirectory(targetDirectory.FullName);
WriteObject(createdDirectory);
}
catch (IOException ioException)
{
ThrowTerminatingError(
CreateErrorRecord(
ioException,
ErrorCategory.WriteError,
targetDirectory.FullName));
}
catch (System.UnauthorizedAccessException unauthorizedAccessException)
{
ThrowTerminatingError(
CreateErrorRecord(
unauthorizedAccessException,
ErrorCategory.PermissionDenied,
targetDirectory.FullName));
}
Comment on lines +69 to +84
}
}

private static DirectoryInfo GetTemporaryDirectoryWithPrefix(string tempPath, string prefix)
{
if (prefix.Contains(Path.DirectorySeparatorChar) || prefix.Contains(Path.AltDirectorySeparatorChar))
{
throw new System.ArgumentException(
"The prefix cannot contain directory separator characters.",
nameof(prefix));
}

DirectoryInfo temporaryDirectory = new(tempPath);
while (true)
{
DirectoryInfo targetDirectory = new(
Path.Combine(
temporaryDirectory.FullName,
prefix + Path.GetRandomFileName()));

if (!targetDirectory.Exists)
{
return targetDirectory;
}
}
}

private static DirectoryInfo CreateTemporaryDirectory(string path)
{
if (System.OperatingSystem.IsWindows())
{
return Directory.CreateDirectory(path);
}

return Directory.CreateDirectory(
path,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}

private static ErrorRecord CreateErrorRecord(System.Exception exception, ErrorCategory category, string targetPath)
{
return new ErrorRecord(
exception,
"NewTemporaryDirectoryWriteError",
category,
targetPath);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ CmdletsToExport = @(
'Get-PSBreakpoint', 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession',
'Import-PSSession', 'Get-Random', 'Get-SecureRandom', 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace',
'Disable-RunspaceDebug', 'Enable-RunspaceDebug', 'Get-RunspaceDebug', 'Start-Sleep', 'Join-String',
'Out-String', 'Select-String', 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan',
'Out-String', 'Select-String', 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryDirectory', 'New-TemporaryFile', 'New-TimeSpan',
'Get-TraceSource', 'Set-TraceSource', 'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData',
'Get-UICulture', 'Get-Unique', 'Get-Uptime', 'Clear-Variable', 'Get-Variable', 'New-Variable',
'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose', 'Write-Warning', 'Invoke-WebRequest',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ CmdletsToExport = @(
'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', 'Import-PSSession', 'Get-Random', 'Get-SecureRandom'
'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', 'Disable-RunspaceDebug', 'Enable-RunspaceDebug',
'Get-RunspaceDebug', 'ConvertFrom-SddlString', 'Start-Sleep', 'Join-String', 'Out-String', 'Select-String',
'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan', 'Get-TraceSource', 'Set-TraceSource',
'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryDirectory', 'New-TemporaryFile', 'New-TimeSpan', 'Get-TraceSource', 'Set-TraceSource',
'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData', 'Get-UICulture', 'Get-Unique', 'Get-Uptime',
'Clear-Variable', 'Get-Variable', 'New-Variable', 'Remove-Variable', 'Set-Variable', 'Get-Verb', 'Write-Verbose',
'Write-Warning', 'Invoke-WebRequest', 'Format-Wide', 'ConvertTo-Xml', 'Select-Xml', 'Get-Error', 'Update-List',
Expand Down
10 changes: 8 additions & 2 deletions 10 src/System.Management.Automation/utils/PathUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,13 @@ internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string modu
}

internal static DirectoryInfo CreateTemporaryDirectory()
{
DirectoryInfo moduleDirectory = GetTemporaryDirectory();
Directory.CreateDirectory(moduleDirectory.FullName);
return new DirectoryInfo(moduleDirectory.FullName);
}

internal static DirectoryInfo GetTemporaryDirectory()
{
DirectoryInfo temporaryDirectory = new DirectoryInfo(Path.GetTempPath());
DirectoryInfo moduleDirectory;
Expand All @@ -705,8 +712,7 @@ internal static DirectoryInfo CreateTemporaryDirectory()
Path.GetRandomFileName())));
} while (moduleDirectory.Exists);

Directory.CreateDirectory(moduleDirectory.FullName);
return new DirectoryInfo(moduleDirectory.FullName);
return moduleDirectory;
}

internal static bool TryDeleteFile(string filepath)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

Describe "New-TemporaryDirectory" -Tags "CI" {
BeforeEach {
$tempDirectory = $null
}

AfterEach {
if ($tempDirectory -and (Test-Path -LiteralPath $tempDirectory.FullName)) {
Remove-Item -LiteralPath $tempDirectory.FullName -Force -Recurse -ErrorAction SilentlyContinue
}
}

It "creates a new temporary directory" {
$tempDirectory = New-TemporaryDirectory

$tempDirectory | Should -Exist
$tempDirectory | Should -BeOfType System.IO.DirectoryInfo
$tempDirectory.FullName | Should -BeLikeExactly "$([System.IO.Path]::GetTempPath())*"
(Get-Item -LiteralPath $tempDirectory.FullName).PSIsContainer | Should -BeTrue
}

It "creates unique temporary directories" {
$tempDirectory = New-TemporaryDirectory
$secondTempDirectory = New-TemporaryDirectory

try {
$secondTempDirectory.FullName | Should -Not -BeExactly $tempDirectory.FullName
$secondTempDirectory | Should -Exist
$secondTempDirectory | Should -BeOfType System.IO.DirectoryInfo
}
finally {
if ($secondTempDirectory -and (Test-Path -LiteralPath $secondTempDirectory.FullName)) {
Remove-Item -LiteralPath $secondTempDirectory.FullName -Force -Recurse -ErrorAction SilentlyContinue
}
}
}

It "with WhatIf does not create a directory" {
New-TemporaryDirectory -WhatIf | Should -BeNullOrEmpty
}

It "with WhatIf and Prefix does not create a directory" {
New-TemporaryDirectory -Prefix "Test_" -WhatIf | Should -BeNullOrEmpty
}

It "has an OutputType of System.IO.DirectoryInfo" {
(Get-Command New-TemporaryDirectory).OutputType.Name | Should -Contain "System.IO.DirectoryInfo"
}

It "creates a directory with custom prefix" {
$prefix = "MyApp"
$tempDirectory = New-TemporaryDirectory -Prefix $prefix

$tempDirectory | Should -Exist
$tempDirectory | Should -BeOfType System.IO.DirectoryInfo
$tempDirectory.Name | Should -BeLike "$prefix*"
}
Comment on lines +48 to +50
}
1 change: 1 addition & 0 deletions 1 test/powershell/engine/Basic/DefaultCommands.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ Describe "Verify aliases and cmdlets" -Tags "CI" {
"Cmdlet", "New-PSSessionOption", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "New-PSTransportOption", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "New-Service", "", $($FullCLR -or $CoreWindows ), "", "", "Medium"
"Cmdlet", "New-TemporaryDirectory", "", $( $CoreWindows -or $CoreUnix), "", "", "Low"
"Cmdlet", "New-TemporaryFile", "", $( $CoreWindows -or $CoreUnix), "", "", "Low"
"Cmdlet", "New-TimeSpan", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None"
"Cmdlet", "New-Variable", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Low"
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.