From 8854c00ec29bbc54482c173fe3951575fa241d6a Mon Sep 17 00:00:00 2001 From: Kris Borowinski Date: Fri, 7 Feb 2025 18:32:23 +0100 Subject: [PATCH] Fix `New-Item -Force` to error on invalid directory name (#24936) --- .../namespaces/FileSystemProvider.cs | 9 ++++++++- .../Microsoft.PowerShell.Management/New-Item.Tests.ps1 | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3432d8816e..3423709d3c 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -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)); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 index 89f21d5e05..5cd5a660c8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 @@ -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' + } +}