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
 
Soldato
Joined
1 Apr 2014
Posts
18,605
Location
Aberdeen
Why do you need to remotely execute the command? Surely all you need to do is something like RMDIR \\computername\sharename\directorypath /s /q
 
Soldato
Joined
25 Mar 2004
Posts
15,746
Location
Fareham
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:
Associate
OP
Joined
8 Mar 2010
Posts
84
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)
 
Soldato
Joined
1 Apr 2014
Posts
18,605
Location
Aberdeen
That’s not Powershell line but a CMD batch file line. You just make sure that you run it from an account with appropriate access rights.
 
Caporegime
Joined
18 Oct 2002
Posts
29,491
Location
Back in East London
Invoke-Command has a session parameter.

Code:
$PSSession = Enter-PSSession -ComputerName $Host
Invoke-Command -Session $PSSession -Command { Remove-Item -Force -Recurse $PathToDelete }
 
Last edited:
Soldato
Joined
25 Mar 2004
Posts
15,746
Location
Fareham
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