How to run PowerShell script on a remote computer? - powershell

I'm aiming to run the script for Google Chrome installation on a remote computer.
The script for local installation has been saved on my PC (\localhost\c$\Chrome\Chrome Installer.ps1").
I was thinking to copy the script first to the remote machine and then run the script remotely. Could you please suggest the best way to run that script remotely?
Thank you in advance
Best Regards,
Stan
You can find the script below:
$Installer = "$env:temp\chrome_installer.exe"
$url = 'http://dl.google.com/chrome/install/375.126/chrome_installer.exe'
Invoke-WebRequest -Uri $url -OutFile $Installer -UseBasicParsing
Start-Process -FilePath $Installer -Args '/silent /install' -Wait
Remove-Item -Path $Installer
$login = Read-Host "Please enter login id"
$comp = Read-Host "Please enter computer name or IPV4 adress"
Copy-Item -Path "\\localhost\c$\Chrome\Chrome Installer.ps1" -Dest "\\$($comp)\c$\temp"

I was thinking to copy the script first to the remote machine and then run the script remotely.
You don't actually need to copy it to the remote host first - you can have Invoke-Command run a script from your local file system on a remote computer like so:
Invoke-Command -ComputerName $comp -FilePath "C:\Chrome\Chrome Installer.ps1"
To pass credentials for the remote machine, specify the account name as an argument to the -Credential parameter and PowerShell will prompt you for the password:
$login = Read-Host "Enter the user name for the remote host"
Invoke-Command -ComputerName $comp -FilePath "C:\Chrome\Chrome Installer.ps1" -Credential .\$login

You can do enter-pssession to get a local prompt and paste in your script using your credentials. You can also checkout invoke-commdand and specify a script file and tagret.
Run: update-help
then run:
help invoke-command -examples
You should see something that works for your situation.

Related

Running a remote cmd command in PowerShell

I uploaded some files to a remote host with PowerShell, by FTP. On this host runs Windows 7 Embedded.
It turns out there is EWF (Enhanced Write Filter). So after a restart the uploaded files were gone. For saving the changes it needs commit them in cmd (at the remote host) by: ewfmgr d:-commit How can I include this command in my PowerShell code?
The code:
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts -Value * -Force
Restart-Service WinRm
Test-WSMan $line
Invoke-Command -ComputerName $line -scriptblock {cmd.exe /c "ewfmgr d: -commit"} -credential $FTPCredential
When I run Enable-PSRemoting -Force manually on the remote computer, it works, but it is uncomfortable and take lots of time. Is there another way to do this once for many hosts simultaneously?
Example-Code:
$session = New-PSSession -ComputerName yourRemoteComputer
Invoke-Command -Session $session -Scriptblock {ewfmgr d: -commit}
Remove-PSSession -Session $session
You have to enable Powershell Remoting on your host to invoke a command like this (https://technet.microsoft.com/en-us/library/ff700227.aspx)
If you need to transmit Credentials to your remote host, you can add the -Credential-Parameter to New-PSSession. This article describes how to add valid Credentials to your script (https://technet.microsoft.com/en-us/library/ff700227.aspx)
Greetings, Ronny

How do I remotely start a VM on VMWare Workstation using Powershell?

I have VMWare Workstation and beginner's knowledge of PowerShell.
I've created a script that successfully starts a VM on my local machine by using the vmrun tool. However, if I run it through a remote session, nothing happens. Any idea why?
Get-PSSession | Remove-PSSession
$VMHostMachine | New-PSSession
$rs = Get-PSSession # testing using localhost
Write-Debug ("Now starting VM on host: " + $VMHostMachine)
$script = {param($VMImagePath, $VMConsolePath);
$QuotedVMPath = "`"{0}`"" -f $VMImagePath
$Result = Start-Process -FilePath $VMConsolePath -ArgumentList "-T", "ws", "start", $QuotedVMPath -Wait -PassThru -NoNewWindow
}
Invoke-Command -Session $rs -ScriptBlock $script -ArgumentList $vmConfig.VMImagePathOnHost, $vmConfig.VMRunUtiltyPath
Invoke-Command works if I remove the session parameter:
Invoke-Command -ScriptBlock $script -ArgumentList $vmConfig.VMImagePathOnHost, $vmConfig.VMRunUtiltyPath
I have a similar script that successfully reverts to a snapshot on my localhost through a PSSession, so why is starting a VM giving me trouble?
Does it work if you "enter-pssession" and then try to invoke?
I'm assuming it's "not working" for you here, because you invoke commands through PSSession where there are no visible desktops / gui-session, and you are expecting the VMWare workstation to appear? The receiving end is a service.
You could check if the process is running VMWare with Get-Process.
To do what you want to achieve here you could take a look at PsExec, which allows to start applications into an active session.
https://technet.microsoft.com/en-US/sysinternals/bb897553.aspx
Note the "-i" parameter on PSExec.

PowerShell Invoke-WMImethod on WinXp Issue

I am running the below Invoke-WMImethod against remote machines to 7zip up a backup archive. On Win7 it works just fine, on WinXp it dies. I am guessing it dies on the -p$pass in my 7zip options.
$pass = Read-Host "Enter backup password"
$7zip = "cmd /c $backuploc\7za.exe a $backupname.7z -p$pass -mhe $backupfolder"
InVoke-WmiMethod -class Win32_process -name Create -ArgumentList $7zip -ComputerName SVR1 -Credential $cred | Out-Null
Again this is working just fine on the Win7 boxes..why does this fail on XP? and is there a way to get the password option working. (without hard coding password, exclude WinRM also)

Powershell remote application(.cmd) deployment

I am beginner with PowerShell and struggling to get this around with the help from different sites, My requirement and scenario is
I have a windows server 2008(rktdepy) with PowerShell installed and I have packaged application with a .cmd file. When I click this .cmd file the application will be deployed.
The server name is rktdepy and I want to create a PowerShell script which will connect to other servers in the network (the server names should be picked up from a txt files) and install the application accessing the file remotely from rktdepy server. The files are not supposed to be copied to any server and should not use psxec for security reason.
So far I have used invoke and mapping the network drive but still I have issues
$Comsession = Get-content c:\adminfiles\scripts\deploy.txt | new-pssession -throttlelimit 50
Invoke-command -computername RKTDEPLY54 -scriptblock { (new-object -comobject wscript.network).mapnetworkdrive("R:", "\\rktdepy\deploy", $true) }
Invoke-command -session $comsession -scriptblock {"CMD /C r:\QR_DEPLOY.CMD"}
The above script throws error,
I dont want to use any password in the script and it should fetch the current logged in user password from rktdepy server. I is ok if the scripts prompts for a user name and password which will have admin access to all servers.
It looks like you are dealing with a couple problems. One is that the session where you map the drive is gone when you run the next Invoke-Command that uses the mapped drive. You could move that into the same script block to fix a problem like that. The second one is a "second hop" issue. See a resource like Don Jones' Secrets of PowerShell Remoting free ebook on http://powershell.org/wp/books.
Steve
I have testing the following on my machine and it is working so far. There is also another method you can try out listed below.
Method1:
1. I have txt file with a list of computers named allcomputers.txt. It contains name of machines on each line.
Machine10
Machine20
Machine30
Machine40
The deployment script (mydeploytest.ps1) which accepts Computername, Username and Password as input and creates a new PSSession and then invokes command.
param(
[string]$ComputerName,
[string]$User,
[string]$pass
)
Get-PSSEssion | Remove-PSSession
$session = New-PSSession -ComputerName $ComputerName
Invoke-Command -Session $session -ScriptBlock {
param(
[string]$ComputerName,
[string]$Username,
[string]$Password
)
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("U:", "\\RKTDEPY\deploy", $false, $Username, $Password)
Invoke-Expression "CMD /C U:\deploy.cmd"
$net.RemoveNetworkDrive("U:")
} -args $ComputerName,$User,$pass
Get-PSSEssion | Remove-PSSession
Powershell commandline oneline to accomplish deployment task.
PS C:> Get-Content C:\scripts\allcomputers.txt | Foreach { C:\scripts\mydeploytest.ps1 $_ "yourserviceaccount" "password"}
Method2:
The help method for Invoke-Command has an example on how to solve the doublehop issue stevals is mentioning in the answer.
PS C:\> Enable-WSManCredSSP -Delegate Server02
PS C:\>Connect-WSMan Server02
PS C:\>Set-Item WSMan:\Server02*\Service\Auth\CredSSP -Value $true
PS C:\>$s = New-PSSession Server02
PS C:\>Invoke-Command -Session $s -ScriptBlock {Get-Item \\Net03\Scripts\LogFiles.ps1} -Authentication CredSSP
-Credential Domain01\Admin01
I think with little modification to method 2 you can achieve what you want.

Invoke-Command invocation of server script error

I have this script in the client computer that try to run a script from the server computer:
try {
$s = New-PSSession -ComputerName "name" -Authentication CredSSP -Credential $credential
Enter-PSSession -Id $s.Id
Set-ExecutionPolicy ByPass -Scope CurrentUser
Invoke-Command -Session $s -FilePath c:\release1.ps1
} catch {
Write-Error "Error occurred: " $_.Exception.ToString()
} finally {
Exit-PSSession
Remove-PSSession $s }
the script in the server is something like this
Set-Alias vmrun "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"
Start-Process -NoNewWindow -FilePath vmrun -ArgumentList " -T ws revertToSnapshot M:\myvm.vmx Release1"
but I got the error
Write-Error : A positional parameter cannot be found that accepts argument 'System.Management.Automation.ItemNotFoundException: Cannot
find path 'C:\release1.ps1' because it does not exist.
-FilePath must specify a path to a file on the local computer. The file is read locally, then passed to the remote computer as a block of code.
See http://technet.microsoft.com/en-us/library/hh849719.aspx:
Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.
The solution is to put release1.ps1 on the local computer. Or if it must be on the remote computer, then put it in a share that is accessible to the local computer and access it with a UNC path.
Invoke-Command -Session $s -FilePath \\name\share\release1.ps1