Unable to remove a directory on network drive with PowerShell
<p>I have built a script that removes a user from AD, Exchange, Lync etc. At the end of the script it deletes the users profile-folder and home-directory. The thing is, only the user who is being deleted has the Full Control for the profile-folder, so I need to delete the folder with his/hers credentials.</p>

<p>First I tried this:</p>

<pre><code>Remove-Item -Path \\networkdrive\share$\profilefolder -Recurse -Force -Credential $UsersCredentials
</code></pre>

<p>but I got the following error:</p>

<blockquote>
  <p>Remove-Item : Cannot retrieve the dynamic parameters for the cmdlet. The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials.</p>
</blockquote>

<p>Then I tried to do it with the <code>New-PSDrive</code> cmdlet:</p>

<pre><code>New-PSDrive -Name F -PSProvider FileSystem -Root \\networkdrive\share$\profilefolder -Credential $UsersCredentials
</code></pre>

<p>I get the following error:</p>

<blockquote>
  <p>New-PSDrive : Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again</p>
</blockquote>

<p>I read somewhere that connecting to the network drive with IP-address might solve the error above, but when I tried that, I got a new error:</p>

<blockquote>
  <p>New-PSDrive : The specified network password is not correct</p>
</blockquote>

<p>Do you have any suggestion as to what I could do? My goal is to use the credentials of the person being deleted to remove the folders. My next step is to download the NetApp PowerShell cmdlets and see if I could get the directories removed with those.</p>

<p><strong>Edit:</strong> I decided that I would not to try to remove the folder with other credentials, but instead take the ownership, and delete the folder after that. I tried:</p>

<pre><code>takeown /F \\server\share\folder /A /R /D y
</code></pre>

<p>But I got the following error:</p>

<pre><code>SUCCESS: The file (or folder): "\\server\share\folder" now owned by the administrators group.
</code></pre>

<p>takeown : 
At line:1 char:1
+ takeown /F \server\share\folder /A /R /D y
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError</p>

<p><strong>ERROR: The data area passed to a system call is too small.</strong></p>

<p>So it seems I am not able to take the ownership, for some reason. Any suggestions how I could proceed from here?</p>