Triggering a remote powershell script to run independently - powershell

I've created a script which calls 'dfsutil', and is available for all the members in my team. Some members don't have RSAT (dfsutil) installed locally, so I'd like to 'trigger' a .ps1 script independently of the source PC (PC1) to be run on a server (Server1) which has 'dfsutil' installed.
It's easy enough to trigger a remote PowerShell script from the source 'PC1' by dot-sourcing it from 'myscript.ps1':
. \\Server1\scripts\dfsscript.ps1
As we already know, the above will fail as PowerShell is looking for 'dfsutil' locally on PC1, rather than on the server 'Server1'.
'dfsscript.ps1' has been written so it can be run independently, without need to return the values to PC1.
I can't seem to find any documentation which shows how to initialise a remote script which only uses the values and conditions of the OS it was triggered on.
Any thoughts?

Dot-sourcing is about the scope of a PowerShell session, but doesn't include the computing environment, so what you are doing won't get the script on Server1 to run from Server2, but still act like it is on Server1 with access to all of Server1's installed apps, etc.
What you need to do is use PowerShell remoting to actually run the script on the remote server (i.e. trigger from Server2, but execute on Server1). For example:
Invoke-Command -ComputerName Server1 -FilePath <path>\script.ps1

Related

Script location of a remotely executed script?

How can I get a remotely executed script to know it's own location? I'm using Invoke-Command to run a script on a remote server. The script needs to create files in the directory in which it lives. Running with relative addressing doesn't work (i.e. .\output.log), the scripts generally end up in my user profile on the remote server. I tried all the methods outlined in this question but none of them seem to work when the script is remote.
Update: Provided script invocation code per request
$server='ad1hfdahp802'
$remotepath='\\ad1hfdahp802\d$\AHP\pi_exceed_presentation\pi_exceed_presentation_deploy.ps1'
$SDFEnvironment='INT'
Invoke-Command -ComputerName $server -FilePath $remotepath -ArgumentList($SDFEnvironment,$remotepath)
The remote script takes the $remotepath and turns it into a file system path.
Using -FilePath with Invoke-Command means that you read the script locally and send the content as the scriptblock to the remote computer. $PSScriptRoot only works when the script is executed directly on the target. You could try using:
Invoke-Command - ComputerName "computer1" -Scriptblock { & '\\server\path\to\script.ps1' } -Authentication Credssp
Be aware that you need CredSSP to make this work since the remote computer can't use your credentials to access network-resources without it. As an alternative, you could use psexec (or start a process remotely). Ex.
psexec \\computer1 powershell -noprofile -file \\server\path\to\script.ps1
After trying some of the changes proposed I've come to understand that the Invoke-Command isn't actually running the remote script at its original location, but rather loading it from the original location and then running it under the context of PowerShell as the user running the local script. The "script directory" is actually a directory in the user's workspace regardless of where the script originally lived.
This clarifies things for me somewhat. While there may be ways to divine where the script originally came from or to actually start a session on the remote server then run the script as a "local" script there, the need for the remote script to further access other servers, creating multiple hops in authentication, means I have to add CredSSP to the mix.
It seems my original plan, to pass the path I'm using to locate the script to the script so it can place output files in the original directory, is probably the best approach given that I also have to add CredSSP to the mix.
I'm open to refutation, but I don't think any of the proposed solutions actually improve the functionality of the remote script so I'm going to stick with what I started with for now. Thanks to everyone for their contributions.
Enter a session on the remote server, and call the script from there.
local PS> Enter-PSSession -ComputerName $server ...
remote PS> powershell d:\AHP\...\script.ps1
remote PS> exit
local PS>
Then you can use $PSScriptRoot in the script in the remote server to get the local path of the directory of the script on the remote server.
EDIT:
To locate the script on the remote server, you can use your knowledge of the network path of the script file, and parse the output of net share to map network path to local path on the remote server.
remote PS> net share | where { $_.StartsWith('D$ ') } | foreach { [regex]::Split($_, " +")[1]}

Powershell tasks from local machine to remote machine

I am performing below tasks on remote machine from a local machine:
Creating/Deleting/Modifying some directory
Copying some folder from local to remote machine
Installing some .exe silently with noninteractive option
Exectuing some batch files
I want to write a script in PowerShell. Novice to PowerShell. I have done some basic investigation of terms like "PowerShell Remoting" etc.
What are the things I need to look for? Related exmple for this will help, where should I look for those?
Reading from docs on MSDN:
To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, use the New-PSSession cmdlet to create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession. To run a command in a disconnected session, use the InDisconnectedSession parameter. To run a command in a background job, use the AsJob parameter.
So basically you should do something like:
$session = New-PSSession
Invoke-Command -Session $session -FilePath <PathToScript>
There is a good section on PowerShell remoting in the Getting Started with PowerShell 3.0 Virtual Academy class. If you don't want to start there, read the about_Remote help topic, then move on to the other remoting help topics listed at the bottom.

Windows - remotely running executable or cmd using WMI or powershell, and logging the output

This is incredibly difficult to do. I can't believe it. It should be so easy.
Anyway, using WMI (with both vbscript and perl) I'm able to start a process on a remote machine that runs a .exe, but I cannot get the output to write to a log. This is driving me nuts. I have to use WMI or powershell because I can't install anything additional on the remote machines, which are all Windows 2003 or newer. I also cannot assume that powershell remoting is enabled on all target machines, so I may not even be able to use powershell. This can cause a problem with powershell.
Here is what I'm trying to do in psuedo code:
servers = server1, server2, server3
for each server in servers
run command on remote server >> log.txt
next
I'm assuming you have powershell remoting enabled on all the servers and that you want the results saved in a local log file (ie not on each server)...
$Servers = "server1", "server2","server3"
Invoke-Command -ComputerName $Servers -ScriptBlock { ping.exe www.stackoverflow.com } >> c:\localfile.txt
This also assumes that your exe outputs to stdout, I think there will be issues capturing other streams.

Installing an .exe on a remote machine from PowerShell

So, I have been trying to do the following via a PowerShell script:
For a list of computers, do:
Ping the computer (via WMI) to see if it's available; if not, log & break, if so, continue on
Create a folder on the root of the C:\ drive (via Invoke-WmiMethod); if fails, log & break, if successful, continue on
Copy files (includes an .exe) from another machine into that folder; if fails, log & break, if successful, continue on
Run the .exe file (via Invoke-WmiMethod); if fails, log & break, if successful, log success, done (with this computer.)
The problem I'm running into is the execution of the .exe (program installer) -- the Invoke-WmiMethod command usually works, but for some machines, it hangs (not fails, but hangs.) I've tried a whole bunch of stuff to try to get it to run as a job so I can set a timeout on the install (running the Invoke-WmiMethod command with -AsJob param, always returns Failed...; Start-Job -Computer $compname { Invoke-WmiMethod..., returns Completed but the install never happens; making sure the remote machines have Windows Firewall disabled, UAC turned off, etc. but still if I run the Invoke-WmiMethod command on them, not running as a job, it hangs. And yes, I'm running PS as a Domain Admin, so I should have rights on the target machines.)
So being a newb at all things PowerShell, I'm now at a complete loss as to what to try next... How would you tackle running a .exe on a remote system from a PowerShell script? One caveat is that the target machines don't all run PowerShell [V1|V2] (target PCs are a mix of XP, Vista and 7) or don't have remoting enabled. The other caveat being that the installer is an .exe, and not an .msi, and this can't be changed (it's a third-party app.)
Thanks in advance to anyone who can point me in the right direction here (and give me some sample code...)
What OS is running on the system (management station or central system) where these scripts are getting executed? If Windows XP, there is a known issue with WMI and -asJob.
Check this: WMI Query Script as a Job
In such a case, I'd suggest moving to a Windows 7 system and then run the script to remotely install .exe on all other machines.

powershell v2 remote features?

Just listened to Hansellminutes podcast. He had a talk with two Microsoft PS developers. They mentioned PS V2 remoting features.
I have some scripts based on PS v1. In terms of remoting commands or executions, I installed PS on local and a remote machines. Then I use PsExec.exe to push bat on remote to execute PS scripts. Now I am thinking to take advantage of PS V2.
To simple questions I have, to get a list of files on local, I can use the following codes:
$fs = Get-Item -Path $Path | Where { !$_.PSIsContainer ... } # more constrains in ...
if ( $fs -ne $null )
{
# continue to work on each file in the collection
...
}
What is the equivalent command to get a collection of files from a remote? I prefer to get a similar collection of file objects back so that I can access to their properties.
The second question is how to exec a command on remote with external application? I tried to use WIM Process before, but I could not get WMI class working on a case of Windows 2008 server. Then I used PsExec.exe to push a bat to a remote to execute PS script. It works in the cases. However, the problem I have to install PS on the remote as well. I am going to working another remote. I'll try to avoid to install PS on the remote. Can I take PS V2 advantage to execute a command on a remote Windows? What's the new commands?
By the way, normally, I have to pass user name and pwd to a remote. I guess in PS I have to pass user/pwd as well.
You can either put your code above in a script file and invoke it on a remote computer using V2 remoting like so:
PS> Invoke-Command remotePCName -file c:\myscript.ps1
You will need to be running with admin privs (elevated if UAC enabled) in order to use remoting. The command above will copy the script to the remote machine, execute it and return deserialized objects. These objects are essentially property bags. They are not "live" objects and setting properties on them like IsReadOnly will not affect the remote file. If you want to set properties then do it in your script that executes on the remote PC.
The option if you have a little bit of script is to use a scriptblock like so:
PS> Invoke-Command remotePCName { Get-Item C:\*.txt | Where {$_.IsReadOnly }
You can execute native commands (EXE) on the remote computer in either script or a scriptblock. You only need to make sure the EXE is available on the remote PC.
Regarding credentials, if you're on a domain and you have admin privs on the remote computer you won't need to pass credentials as your default credentials should work. If you need to run as a specific user then use the -Credential parameter on Invoke-Command like so:
PS> $cred = Get-Credential
PS> icm remotePCName { gci c:\windows\system32 -r *.sys } -credential $cred
Regarding your last comment, no PowerShell will use Windows integrated security so you should not have to pass any username or password unless you wanted to run it as a different user.
If you haven't yet enabled PS remoting, every time I've tried I've had to actually turn off UAC while I was enabling remoting (then I could re-enable UAC once remoting was enabled). Running Enable-PSRemoting from an elevated command prompt was not enough and the error message was not at all useful.
EDIT: I've just confirmed in a fresh Windows 7 VM that this is not an issue. It could have been a beta issue that I am no longer experiencing as I've been using beta/rc/ctp of PowerShell and Windows 7 for a long time.