简体   繁体   中英

Executing a powershell script locally to run on a remote computer

I have the current powershell script

$release = read-host "enter release"
$fullPath = "10.0.0.3"
$fullPath = $fullPath + $release
$fullPath = $fullPath + ".bat"
start-process $fullPath

Currently I log in to a remote machine to run this code for this example 10.0.0.2. The code then pulls the files from another remote machine (10.0.0.3). What I would like to do is execute this script from my local machine (10.0.0.1) and have it run on .2. I have full access to the box so that should make it easier. How can i go about doing this?

Put the script into a script file say ReleaseProcessing.ps1 and execute it like so:

Invoke-Command -ComputerName 10.0.0.2 -FilePath .\ReleaseProcessing.ps1

You will be prompted to "enter release" on the local computer but the script is transferred to and runs on the remote computer. This requires that you are running PowerShell 2.0 or higher and that you have enabled remoting on 10.0.0.2 by running the Enable-PSRemoting on that machine. Also, since there is another machine involved you could run into 2nd hop credential issues. If that is the case, consider using the -Authentication paramter with a value of CredSSP .

I have used this once in a project. Where i needed to create website on APP server and had to run from a INT server. So I kept the site setup script on App server and ran remotely from INT server.

 $script = 
 {
 $Filetoexe = $args[0]
 invoke-expression "$Filetoexe"
 }
 Invoke-Command -ComputerName <Computername> -credential <credentials> -ScriptBlock $script -Args "D:\sitesetup.ps1"

save this and run this. The last line "Invoke-Command" will get executed and it will access the remote computer that you have given and will execute the script block .

The script block takes the argument passed in the last line and executes the file in the script block.

What ever function you need to run on the remote system must be done with in the script block.

Hope it is helpful....

this works well if you have your remote servers setup for remote access via powershell

$scriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$StrServers = Get-Content -Path "$scriptPath\Environment\$strEnvironment.txt"


$content = [IO.File]::ReadAllText("$scriptPath\environment\test.txt")
foreach ($strServer in $content)
{
Invoke-Command -ComputerName $strServer -FilePath $scriptPath\testScript.ps1 -ArgumentList $StrLog
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM