remove folder from string variable

Tsvetkov, Martin 22 Reputation points

$R = "${Env:ProgramFiles(x86)}\del"
remove-item $r -recurse

how to make that working

10x in advance

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,273 questions
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 27,591 Reputation points Microsoft Vendor


    According to the error, the string ${env:ProgramFiles(x86)}\del is not expanded. You can try this

    remove-item $ExecutionContext.InvokeCommand.ExpandString($r) -recurse  

    Best Regards,
    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. MotoX80 30,831 Reputation points

    The commands that you posted look ok. You don't mention what error you are getting, but I suspect it is an access denied.

    When it comes to "Program Files" folders, typically the Windows installer will lock down the permissions so that they cannot be deleted even by administrators. You should first try to uninstall the application that was installed into the "del" folder.

    Did you you run the uninstall? Did it fail? Is the full application still there or is it just a few folders that remain?

    0 comments No comments

  2. Tsvetkov, Martin 22 Reputation points

    Hi there. Sorry for the uncomplete Q. Now:
    I have txt file named readPath.txt with one line inside: ${Env:ProgramFiles(x86)}\del


    $r = Get-content readPath.txt
    $r ---> ${env:ProgramFiles(x86)}\del

    remove-item $r -Recurse

    the error message:
    Remove-Item : Cannot find drive. A drive with the name '${env' does not exist.
    At line:1 char:1

    • Remove-Item $r -Recurse
    • ~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : ObjectNotFound: (${env:String) [Remove-Item], DriveNotFoundException
    • FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
    0 comments No comments