Home > OS >  how to delete a folder using invoke command in powershell
how to delete a folder using invoke command in powershell

Time:08-03

First time asking a question here after using it for a long time.

I'm currently making a powershell script to delete userdata when they left the company for a month.

I already tried deleting the folder using the normal remove-item and this works however this is a very slow process when going over the network.

I then found out about the invoke-command function which can run on a remote computer. Now i can't seem to get this working.

I keep getting the error that the path is not found. However it seems like powershell is changing my path. How can i prevent this from happening?

Cannot find path 'C:\Users\admcia\Documents\P$\PERSONAL\JOBA' because it does not exist.
      CategoryInfo          : ObjectNotFound: (C:\Users\admcia...$\PERSONAL\JOBA:String) [Remove-Item], ItemNotFoundException
      FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
      PSComputerName        : ODNDATA
 

my code is the following: Note that P$ is the local drive letter on the server. Also note That $item.SamAccountName is used for creating foldername. (we use Samaccountname as the name of the users folder.

     $localPath1 = "P$"   "\PERSONAL\"   $item.SamAccountName
     $serverName = "Remotecompter"
     Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }

CodePudding user response:

If as seen from your local machine, the drive is \\Remotecomputer\P$\, then for the remote computer (where the code is executed) the path is just P:\.
To combine strings into a path, I would suggest you better use the Join-Path cmdlet rather than concatenating the strings with ' '

Try

$localPath1 = Join-Path -Path 'P:\PERSONAL' -ChildPath $item.SamAccountName
$serverName = "Remotecompter"
Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }

CodePudding user response:

You can use -ArgumentList in Invoke command,

Invoke-Command -ComputerName $serverName -ScriptBlock { 
param($localPath1)
Remove-Item $localPath1 -Force -Recurse -Confirm:$false
 } -ArgumentList($localPath1)

make sure your path is correct, and if it does not work try to hardcode the path in your code.

  • Related