Powershell - how to run a script located on another computer? - powershell

Could anyone please offer me some hints? I am stuck with this problem.
I have developed a PowerShell script located in:
\\\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
This script requires 4 arguments to work. I need to run that script from another computer.
I have tried:
Invoke-Command -ComputerName ComputerNameA
-FilePath \\\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
-ArgumentList {-arg0 string -arg1 string -arg2 string -arg3 string}
Any hints will be appreciated.
Update:
As to answer my original question, I think the answer is:
Invoke-Command -ComputerName ComputerNameA -Credential $cred
-FilePath \\ComputerNameA.xxx.xxx.local\d\xxx\script.ps1
-ArgumentList {-arg0 string -arg1 string -arg2 string -arg3 string}
Now, the new problem is I got the access denied error even the credential is exist (i.e. I setup a new user account - abcd and set the password as abcd)

If you try to execute a PS1 script located on a remote computer as if you do it physically on the computer itself, then you can achieve this via Remote Powershell.
https://4sysops.com/archives/use-powershell-invoke-command-to-run-scripts-on-remote-computers/
Obviously, it implies that the script will do things (i.e read/write operations) on the remote computer instead of yours.
Also, remote connection (in the BIOS settings ?) must be allowed on the remote computer.

You can try installing ssh server where the scripts is located then connect using putty for windows
then execute refer to this

Related

Installing Software using powershell

I am trying to get things configured to push software installs & patches through powershell. I have already created a GP to enable WinRM. I am able to connect to my test VM using enter-pssession -computername computer -credential username without any issues. However, I am getting error message when i try to use the following command to install software invoke-command -computername computername -command {c:\software\setup.exe}
I am new to powershell. I could be using the wrong command to install the software. I have already been copied the file to the test VM. Any assistance would be appreciate
I think your problem comes from the fact that you missed the variable character '$' to 'computername'.
I never seen the '-command' ever being used in an Invoke-Command so I cannot comment about that.
Also, you could use Start-Process to run your .exe maybe?

Run exe with arguments on remote machine

This one is ruining me. Something that I'm pretty sure should be simple just isn't working and it's probably just a single quotation/character out of place.
There's a lync/Skype tool called sefautil.exe that does all kinds of marvelous things the webGUI doesn't. A typical command would be:
C:\Program Files\Skype for Business Server 2015\ResKit>sefautil.exe /server:sfbpool01.domain.local sip:user1#domain.local /setfwddestination:user2#domain.local /enablefwdimmediate
This works fine when remoted onto any of the machines, but I'm really struggling to run it via remote PowerShell.
Whatever commands I try via invoke-command either give me a standard /? response or nothing at all. I've passed the args via -ArgumentList, as a variable, as anything I can think of and it's just not working.
What makes the thing even more tasking as if you run without admin rights, you won't ever get any results. The command has to be ran as an admin. Now I can quite easily put an admin mode checker into my script, but if it's just as easy to send the command as admin I'll take it.
Any help would be massively appreciated.
#qbanet359
I've gone about it a different way which feels a little cheap, but it does work so can't complain.
I've created a scheduled task on the server hosting sefautil.exe to run a batch file under elevated permissions - I've called it sefautil.
I also copied sefaUTIL.exe to C:\TEMP on the server.
Then in my PowerShell script I'm using:
$SERVER = "\\computer1\c$\temp"
"cd \" | Out-File "$SERVER\sefautiltest.bat" -Encoding unicode
"cmd /c C:\Temp\sefautil.exe /server:sfbpool01.ad.leics.gov.uk sip:dols.team#leics.gov.uk" | Out-File "$SERVER\sefautiltest.bat" -Append
gc $SERVER\sefautiltest.bat | out-file $server\sefautil.bat -encoding ascii
Invoke-Command -Credential $CREDS -ComputerName computer 01-ScriptBlock { schtasks /Run /TN sefautil }
It's almost certainly a long winded way of doing this, but it does work.
Thanks for giving me a fresh perspective on things.
A Little late to the party, but I'm sure a lot of other SfB-Admins will struggle here as well.
This is how I made it work:
Invoke-Command -ComputerName $Global:SefaUtilServer -ScriptBlock {&'C:\Program Files\Skype for Business Server 2015\ResKit\SEFAUtil.exe' '/server:epsachhst-lfe11.epsa.swisscom-mcc.local' $args[0] "/enablefwdnoanswer" "/setfwddestination:$($args[1])" "/callanswerwaittime:$($args[2])"} -Credential $Global:LyncSchedTask_Cred -Authentication Credssp -ArgumentList #($UserSip.replace("sip:",""),$Destination,$Delay)
Hint: make sure, that you don't run in the "Powershell Double Hop issue". SefaUtil will make a Connection to a Frontend Server (I assume it's the one with the CMS located) to make the actual changes in the DB. (See my answer on TechNet: https://social.technet.microsoft.com/Forums/office/en-US/5d4c4f90-1b40-4742-ae4b-c2e1a62a0adb/running-sefautil-remotely?forum=lyncdeploy#da6b82b9-cada-420b-a7a7-2110c0ed2280 (by cwa.cloud)
This is the solution I came up with below.
Basically create a batch file with powershell on the SfB server and then run it with psexec to use the System account (psexec had been copied to the server).
Make sure you insert your own server's name where it has "servername" and run the script with an account that has sufficient permissions. Then call the script with the correct parameters.
BTW, I've noticed it can return an error code of 1 if the forwarding is already in place.
param ([string]$FwdUser,[string]$DestUser)
#skype for business phone forwarding
#create a batch file to run the command, run it as system with psexec and remove the batch file afterwards. sefautil does not cooperate with remote execution
$sefautilcmd = "`"C:\Program Files\Skype for Business Server 2015\ResKit\SEFAUtil.exe`" /Server:servername.headoffice.novationleasing.com.au " + $FwdUser + " /setfwddestination:" + $DestUser + " /enablefwdimmediate"
New-Item \\servername\c$\temp\tempfwd.bat
Set-Content \\servername\c$\temp\tempfwd.bat $sefautilcmd
Invoke-Command -ComputerName servername -ScriptBlock {C:\temp\psexec.exe -s -accepteula c:\temp\tempfwd.bat}
Remove-Item \\servername\c$\temp\tempfwd.bat

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]}

PSSession display browser on remote computer

My goal is to display the (default) browser and open a specific URL on a remote session.
1 Create PSSession on a remote computer => OK
$computerName = "yannTPI-1"
$credential = get-credential
$session = new-PSSession -computerName $computerName -credential $credential
2 Run a script => OK
invoke-command -session $session -filePath $file
3 On that script... Open browser (many way...)
[System.Diagnostics.Process]::Start("http://stackoverflow.com")
start http://stackoverflow.com
And it works, under processes I can see a process corresponding to my browser. On my remote computer I'm connected with another account that the one I use to connect to it with PSSession. So it does not display as it is not the same User Name.
How can I force the display of the browser to another user ?
Sorry english is not my mother tongue, hope I'm clear enaugh.
You cannot. Remote interactive sessions isn't possible in PowerShell remoting and WMI remoting. You should use PSExec if this is something you need to do!
I tried that which quiet I'm want to do:
psexec -d "c:\program files\internet explorer\iexplore.exe"
IE Starts but the window is all black - I need the syntax to add -i [UserName/Pwd]
I also found that:
Unfortunately, when you use a specific user account, PsExec passes credentials in the clear to the remote workstation, thus exposing the credentials to anyone who happens to be «listening in».
Source: PsExec Security -i
I also tried on a WM and there was a big graphical problem. (Win7)
Anyway even if I'm able to open a browser correctly, is there a way to open a specific URL ? If not I won't try further.
Source: Windows Systernals PsExec
psexec.exe \machinename -u DOMAIN\username -i -d "c:\program files\internet explorer\iexplorer.exe" http://www.webpage.com
This will show up in the current shell of the user that is logged in.

Execute remote quiet MSI installs from Powershell

I am trying to use the Invoke-Command powershell cmdlet to install a MSI installer. From within powershell on the local machine and from the proper directory, the following works:
./setup /quiet
The following does not seem to work:
$script =
{
param($path)
cd "$path"
& ./setup /quiet
return pwd
}
return Invoke-Command -ComputerName $product.IPs -ScriptBlock $script -Args $sourcePath
For test purposes I am working on the local machine passing in "." for the -ComputerName argument. The paths have been verified correct before passing in to Invoke-Command, and errors generated on different versions of this code indicate the paths are correct. I have also tried with and without the "& " on the remote call to setup. Other Invoke-Command calls are working, so I doubt it is a permissions issue. I have verified that the return from the pwd call is the expected directory.
How do I get the install to work?
What error (if any) are you receiving? Unfortunately, you must run the shell as admin on your local machine to be able to connect to your local machine with invoke-command or any WINRM based command that requires administrative privilege (this is not a requirement when connecting remotely).
When connecting to loopback, I believe it is unable (for some security reason) to enumerate groups and determine if you are in an admin enabled AD or local group, which is how it auto elevates when invoking on a remote machine. The only solution may be to have a conditional which checks for localhost and if so, don't use the -ComputerName parameter.
This GitHub Issue covers it
You might try using Start-Process in your script block:
cd $path
start-process setup.exe -arg "/quiet"
Not sure if you will want or need to wait. Look at help for Start-Process.
I have had weird issues when trying to remotely execute a script on a local machine. In other words, remote powershell to the local machine. It comes back with an error that seems to say that PowerShell remoting is not enabled on the machine, but it was. I can run the script remotely from another machine to the target, but when using remoting to the same box, the issue crops up.
Verify that the WinRM service is running.
Verify powershell remoting has been enabled as in Enable-PSRemoting -force.
Verify your powershell execution policy is loose enough as in Set-ExecutionPolicy Unrestricted, for example. If the policy was set to RemoteSigned, this might be the problem.
You might also want to verify the user you are running the script as (locally, but using remoting) has privileges to "log on as a service" or as a batch job. Just guessing there, if the above list doesn't solve anything.