Fix New-Item -Force to error on invalid directory name (#24936)

This commit is contained in:
Kris Borowinski
2025-02-07 22:32:23 +05:00
committed by GitHub
parent 0beb24e10f
commit 8854c00ec2
2 changed files with 18 additions and 1 deletions
@@ -2716,8 +2716,15 @@ namespace Microsoft.PowerShell.Commands
}
catch (IOException ioException)
{
// Ignore the error if force was specified
#if UNIX
if (!Force)
#else
// Windows error code for invalid characters in file or directory name
const int ERROR_INVALID_NAME = unchecked((int)0x8007007B);
// Do not suppress IOException on Windows if it has the specific HResult for invalid characters in directory name
if (ioException.HResult == ERROR_INVALID_NAME || !Force)
#endif
{
// IOException contains specific message about the error occurred and so no need for errordetails.
WriteError(new ErrorRecord(ioException, "CreateDirectoryIOError", ErrorCategory.WriteError, path));
@@ -386,3 +386,13 @@ Describe "New-Item -Force allows to create an item even if the directories in th
$FullyQualifiedFile | Should -Exist
}
}
Describe "New-Item -Force should throw an error for invalid characters in directory path" -Tags "CI" {
BeforeAll {
$invalidPath = Join-Path -Path $TestDrive -ChildPath 'Invalid?'
}
It "Should throw an error when -Force is used with an invalid directory path" -Skip:(!$IsWindows) {
{ New-Item -Path $invalidPath -ItemType Directory -Force -ErrorAction Stop } | Should -Throw -ErrorId 'CreateDirectoryIOError,Microsoft.PowerShell.Commands.NewItemCommand'
}
}