If I start a PowerShell as a regular user (not admin) and run
cd Desktop
mkdir test
cd test
git init
cd ..
I then cant delete the folder via PowerShell. I have tried the following commands as admin and as the current user.
rm -r test # -> no access permission
rmdir test # -> no access permission
del -r test # -> no access permission
del test # -> no access permission
It prints
CategoryInfo : PermissionDenied: (.git:DirectoryInfo) [Remove-Item], IOException
FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
But I don't understand why I can't remove folders with a .git folder in them.
CodePudding user response:
In order to remove [a directory that contains] hidden items, PowerShell's Remove-Item
cmdlet requires passing the -Force
switch:
Remove-Item -Recurse -Force test
The shortest form of this command (for interactive rather than scripting use), using the platform-neutral ri
alias and PowerShell's so-called elastic syntax, where it is sufficient to specify a prefix of a parameter name (such as -r
for -Recurse
), as long as that prefix is unambiguous):
ri -r -fo test
Note how a two-letter prefix is required for -Force
, because -f
alone is ambiguous: it could also refer to the -Filter
parameter.
git init
creates a.git
subdirectory that is assigned theHidden
attribute on Windows (on Unix-like platforms, the fact that the name starts with.
alone makes the directory a hidden one).On Windows,
rm
,del
,rmdir
are simply built-in aliases ofRemove-Item
, the single cmdlet used to remove both files and directories (removal of the latter requiring-Recurse
if the directory is not empty).
(On Unix-like platforms, onlydel
is defined as an aliases, so as not to shadow the platform-nativerm
andrmdir
utilities.)ri
is a platform-neutral alias derived from the nameRemove-Item
, and therefore preferable.To see all aliases defined for a given command use
Get-Alias -Definition $name
; e.g.:Get-Alias -Definition Remove-Item
Note: While it is arguably beneficial for PowerShell to require explicit opt-in via -Force
in order to delete hidden items - so that you don't accidentally delete items whose existence you may not be aware of - the error message is suboptimal, in that the problem isn't one of permissions.