How to remotely execute an remote script in PowerShell - powershell

First off: This is not a duplicate of How to remote execute an ELEVATED remote script in PowerShell.
My scenario is similar but different in a certain way. What I want to do is the following:
Invoke-Command -UseSSL -ComputerName "$COMPUTER" -FilePath \\script.example.com\secretshare$\install_test.ps1 -ArgumentList 'U'
As the called script performs an installation and manipulates firewall rules, it needs elevated privileges. Irritatingly the error I get is an access error on the share mentioned above.
When I use this suggestion where I use PowerShell DSC, which is run as SYSTEM, it works. But only on Servers running Windows Management Framwork 4.0. So obviously I need a solution for Windows Server 2008 (R2) systems.
I hope someone can point me to the right direction so I can update this question to help other admins aswell.

Related

Programs running on Hyper-V with Invoke-Command hang

I'm trying to run my software on Hyper-V VM using powershell Invoke-Command, without success. Host OS -Windows 10. Guest OS - also Windows 10. VM Generation 1.
I did some simple experiments and found out this:
If I run
Invoke-Command -VMName MY_VM -Credential $Cred -ScriptBlock { calc }
then I can see launched calc.exe on the guest system right with UI.
But if I run mspaint or any non-Microsoft program, nothing happens. The program just hangs in the VM TaskManager without any effect.
I also tried to run several different programs using CLI calling Invoke-Command several ways, but got the same result.
What could be the problem?
The basic answer is that powershell remote connections (or any remote connection like rdp, ssh, etc) take place in a separate logon session, and can't really interact with each other.
There are two reasonable ways to do this:
Use PsExec - part of the microsoft sysinternals tools group.
# List sessions - note the session ID of the session you want the process to start in
quser /server:$computername
# Run a process remotely, specifying the logon ID
PsExec.exe -s -i $ID notepad.exe
Use a scheduled task that runs when you are logged in and is visible. You can do this with powershell's various New-ScheduledTask commands to create one, or follow this guide by Scripting Guy! using WMI Win32_ScheduledJob methods.
See use powershell to start a gui program on a remote machine for more details on both options, and a well-written description of why it's hard to do in windows.

Starting Service on remote server failed

I encounter strange behavior when trying to remotely start a service.
on Server A i'm running this line (it's part of bigger script named RunRemoteService.ps1):
Invoke-Command -ComputerName $B_comp -ScriptBlock {Powershell.exe -File "run_service.ps1"} -Credential $cred
And the script run_service.ps1 contains the following line (it's also part of bigger script):
$my_service_name.Start()
Now here's the strange thing, If I run RunRemoteService.ps1 when I have an open remote connection (mstsc) to server B then the script works perfectly and the required service on B is really starting.
However, if I run RunRemoteService.ps1 when there is no mstsc connection with server B then the script failed (service doesn't start).
Why is this happening and how can it be resolved?
EDIT: I explored this issue a bit more and found out that this occurs only when trying to run my specific service.
that means that my service must run from a session of already logged on user (that is why it's working if I mstsc to the server before).
So I guess my new question is - is there a way I can login to remote machine from powershell?
Thanks.
If you cannot use Credential delegation as suggested by #EBGreen. Try using psexec.exe for calling the script instead of PowerShell remoting.
psexec \\server "cmd /c powershell.exe -f c:\script.ps1"
Get psexec from sysinternals.com
Ok, so my question had evolved and modified on the fly so this solution is to the latest issue I had which is - I couldn't remotely start my service if no user is logged on to remote machine.
The solution is a workaround:
I configured auto-login (using sysinternals auto-login tool) on remote server.
I used Restart-Computer cmdlet at the beginning of the test.
Now after the restart is complete and ps-session is restored, user is logged in automatically to server and I can remotely start my service.
Thanks.

Powershell snap-in for exchange 2007

Ive never used powershell before but it seems like the correct tool to use to read the number and size of mailboxes on our 2007 and 2010 exchange servers. I'm running Powershell on Windows 7 and NOT on the exchange server. The commands used in the examples i have found are not recognised.
From my initial reading it appears i need the Exchange snap in. However, i can't seem to find a download page or instructions for loading it into Powershell, or if it is even possible to access this data from a workstation other than the exchange server. I was wondering if some one could give me some feedback on my problem and point me in the right direction.
thanks.
I have gotten this to work on windows 7 64 bit with exchange 2007 64
I installed the exchange management console via the exchange server 2007 installation files
you don't need to establish a remote powershell session, you run the commands with a domain/network administrator privileged powershell on the workstation.
I'm trying to get just the powershell snapin as I don't need the whole console, but as of right now, with the whole console and powershell you can load the exchange management snapin to powershell and create mail-enabled user accounts.
after installing the exchange management console you can execute
add-pssnapin microsoft.exchange.management.powershell.admin
to load the exchange snapin and begin pulling exchange data.
on top of that you may need to start the service on the exchange server "microsoft exchange system attendant"
i guess you need to establish a powershell remote session to the exchange server and run your powershell cmdlets.
You can start with having a look at the help about remote powershell
PS C:\Windows\system32> help about_Remote
Once you establish a remote powershell session to the exchange server you can add the Exchange Management Shell snap-in from Windows PowerShell
Click Start, click Programs, and then click Windows PowerShell 1.0, Click Windows PowerShell, Type the following command:
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
Use the chdir command to change to the Exchange Server\Bin directory. For example, type:
chdir "c:\program files\microsoft\exchange server\bin"
Type the following command:
.\Exchange.ps1
Once the exchange module is loaded you can start using the various cmdlets.
I had the same problems when I was first trying to get this work, and it was never clear to me what I needed to do.
I was very new to Powershell and was trying to run the add-pssnapin without first creating a new session.
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://EXCHANGE-SERVERNAME/PowerShell/ -Authentication Kerberos -Credential $myCred
Import-PSSession $Session
Where the -ConnectionUri points to your exchange server name and the $myCred holds your admin credentials to access the server.
This will import all modules you can use against MS Exchange.
Note1: you can narrow this down to improve the speed of the import by only selecting to import certain modules you will be using. Good if, for example, you know you will only use certain tools.
You can do this by adding -CommandName and list necessary aliases you want to import.
Note2: Good practice to remove the sessions after you are finished:
Remove-PSSession $Session

Unable to get required information from remote machines using powershell invoke-command

I am developing a tool which uses powershell script to search for new windows updates for the machine. Currently by using the 'invoke-command' i am remotely accessing the various build controllers,virtual machines and hosts and running this powershell script. But invoke-command is unable to fetch the update details every time whenever it is executed.
the usage of invoke-command as follows:
invoke-command -computername buildcontroller1 -filepath searchupdates.ps1 -credential $myceredential
if i run this command, 1st time i will get the output, but when again if i run this command after 2 to 3 hours or after 1 day,its not retrieving the update details.
can anyone please tel me the reason for this.
I cannot tell you the reason for this.
I suspect the reason for needing to ask is an absence of error handling in the searchupdates.ps1 script.

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.