Running a powershell script on a local machine that needs to manipulate files on a remote machine

Associate
Joined
8 Mar 2010
Posts
84
Hi everyone,

I need some assistance with an issue I have.

I need to run a script on a local machine to connect to a remote machine to search a directory for a folder and delete the folder.

I'm using the following command to connect to the remote computer: -

Code:
$PShostSession = Enter-PSSession -computername $UserCheckHost

The connection to the remote computer is fine and works as i get: -

[remotePC]: PS C:\Users\Documents>

What i need to do then is go to a specified directory, search for a folder by name and if that folder is found, delete it. I have tried the following commands in a separate powershell instance manually and it works: -

Code:
Invoke-Command -ScriptBlock {set-location "C:\Users\"}

However if i attempt to run any commands on the remote PC within the script on my local machine, none of the commands pass to the remote machine. Any assistance would be much appreciated Thanks
 
Why do you need to remotely execute the command? Surely all you need to do is something like RMDIR \\computername\sharename\directorypath /s /q
 
You could share it and remotely interact with the folder but I'd be sort of uncomfortable with sharing C:\users\ myself.

You could put the script on the other machine and get it to run locally instead non-interactively.

For your invoke-command if you want to work that way, I think you'd need to add -Session $PShostSession on the end of the command.
 
Last edited:
Why do you need to remotely execute the command? Surely all you need to do is something like RMDIR \\computername\sharename\directorypath /s /q

Thanks for the reply.

How would i pass credentials to that? could i just use the -Credential switch at the of the command?

Code:
RMDIR \\computername\sharename\directorypath /s /q -Credential $cred
(example)
 
Invoke-Command has a session parameter.

Code:
$PSSession = Enter-PSSession -ComputerName $Host
Invoke-Command -Session $PSSession -Command { Remove-Item -Force -Recurse $PathToDelete }
 
Last edited:
Invoke-Command has a session parameter.

Code:
$PSSession = Enter-PSSession -ComputerName $Host
Invoke-Command -Session $PSSession -Command { Remove-Item -Force -Recurse $PathToDelete }

I also said that!

For your invoke-command if you want to work that way, I think you'd need to add -Session $PShostSession on the end of the command.
 
Back
Top Bottom