0

I've got a PowerShell 2.0 script which performs some tasks involving non-MS apps which it launches. This works great if running via RDP or local console, but ends up deleting files when not intended if ran via an Enter-PSSession session from a remote workstation.

What I'm looking for and not finding (or comprehending), is if there is a way within a PowerShell script to test for if it is being executed locally, or remotely via Enter-PSSession. That would allow me to test if it was a remote session, and gracefully exit with a "Sorry, this must be ran locally" message.

2

you can do it with the following:
if ($Host.Name -like '*RemoteHost') { write-error "You must run locally"}

But my real suggestion would be figure out why the script doesn't run over a PSRemoting session and fix that problem.

  • I'd also be far more worried about why a remote session deletes files. What happens remotely could also happen locally. – Jim B Apr 14 '16 at 17:00
  • The script does a delete, then a call on a 3rd party executable which writes out a new file. However, if same file exists, the 3rd party exe does not overwrite; something which I don't have control over. And for this script, the purpose of it is to overwrite existing. In all cases, the files being overwritten can be regenerated should an undesired delete occurs; its more of an annoyance than a catastrophe. I'm just trying to make the script a bit more polite in its behavior. – Alan M Apr 14 '16 at 17:14
  • Jason's answer worked great. The only addition I added was to stick an "Exit 0" at the end so that remote users got a clean exit out of the script. "if ($Host.Name -like '*RemoteHost') { write-error "You must run locally"; Exit 0}" – Alan M Apr 14 '16 at 17:29
  • makes enough sense, I just love to live by the idea of if it can be done locally It should be able to be done by Invoke-Command. It makes things simpler when you have tons of machines to manage. – Jason B Apr 14 '16 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.