remove foldershare remotely

corne nietnodig 196 Reputation points

We have shared folders which must be copied and deleted regurally. So i made a powershell script and try to do copy and delete the share but i can only copy the complete folderstructure but not delete it and not move it remotely. When all subfolders and files are copied to another server then the rootfolder share is empty but cannot be deleted remotely not in a batchfile with cmd not with powershell and not with robocopy. Process is in use. But when i make a new share end trie it is also not deleted, just the subfolders. When i delete the complete patch remotely then it can be deleted but not the share. \servername\share what can be deleted is: \servername\patch to share\share or \servername\e$\patch Is there somewhere a setting that prevents deleting rootfolder shared folders?

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,455 questions
{count} votes

Accepted answer
  1. Rich Matheisen 45,756 Reputation points

    You don't have to pipe anything. Put this in the script block (change the share name, of course!):

    $ShareName = "Junk"
    $p = (Get-SmbShare $ShareName).Path
    Remove-SmbShare $ShareName -Force
    Remove-Item -Path $p
    0 comments No comments

14 additional answers

Sort by: Most helpful
  1. Rich Matheisen 45,756 Reputation points

    Have you tried using Invoke-Command to run a scriptblock on the remote machine? You can use (in the scriptblock) Get-SmbShare to see if any users are connected to the share before you remove it with Remove-SmbShare. Once the share is gone you can remove the directory.

    0 comments No comments

  2. corne nietnodig 196 Reputation points

    Hi Rich,

    Can you give an example? but the share cannot be in use because it is also when making a new share, brand new en then put some files and folders in it. The files and subfolders are removed but not the share itself.

  3. corne nietnodig 196 Reputation points

    Invoke-Command -Server "REMOTE-MACHINE" -ScriptBlock { Remove-SmbShare -Name "SHARE-NAME" -Force}

    Invalid argument. A parametre cannot be found.

    I filled Remote-machine with the server name and share-name with the share-name

    0 comments No comments

  4. corne nietnodig 196 Reputation points

    I can do it like this but not the other way around.


    If (Test-Path $Local) {
    Move-Item -Path $Local -Destination $Remote -Confirm
    Write-Host "Move Successful"
    Else {
    Write-Host "$Remote : can not be found"

    I think it has something to do with protection on a server share to remotely remote or delete that share.

    With the full path it is succeeding.