Running cmd command to remote host on PowerShell - powershell

I need to run in PowerShell script cmd command, which command will be running on remote cmd line. So I put in my script
Invoke-Command -ComputerName $line -scriptblock {cmd.exe /c "whoami"} -credential $Cred
and it works, but only if on remote host was run Enable-PSRemoting -Force
Otherwise I get error:
[192.168.1.1] Connecting to remote server 192.168.1.1 failed with the following error message : Access denied. For more information, see the about_Remote_Trou
bleshooting Help topic.
+ CategoryInfo : OpenError: (192.168.1.1:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
I need run that command to many (about 200) remote hosts, so the question is how can I do this without manually running on each remote host Enable-PSRemoting -Force? Server is in domain but romote hostd don't.

If your servers are on a domain, you could enable PS Remoting on them all via Group Policy: https://www.briantist.com/how-to/powershell-remoting-group-policy/

Related

Unable to run a PS script from UNC path on a remote server

I'm trying to run the following PS command from server A on server B (10.11.12.13) which is supposed to run a PS script locally but from a UNC path. So I have:
Invoke-Command -ComputerName 10.11.12.13 -Credential $cred -ScriptBlock {powershell.exe -ExecutionPolicy Bypass "\\netshare\PSScript.ps1"}
After I enter my credentials it fails with the error:
*\\netshare\PSScript.ps1 : The term '\\netshare\Powershell\PSScript.ps1' is not recognized as
+CategoryInfo: NotSpecified: (\\netshare\Pow... recognized as :String) [],
RemoteException
+FullyQualifiedErrorId: NativeCommandError
+PSComputerName: 10.11.12.13*
In my command if I replace the unc path with a local path such as C:\files\PSScript.ps1 it runs fine.
The remote server is running PS v4. I've already run the command:
Set ExecutionPolicy Unrestricted on server B. I also tried adding -File after Bypass but that also fails with a different error.
How do I get that script to run from server B? Solutions like copying a script to server B first will not work. I also need this to run from the command line (not from a script).
Three things:
There is no reason to invoke powershell.exe from within PowerShell. Invoke the script by the call-operator &
Pay attention to the double-hop issue. If you connect to a remote computer by network logon you can't authenticate from within this remote connection to another remote computer (here network share).
Use Invoke-Command -FilePath C:\PSScript.ps1 -ComputerName 10.11.12.13 instead. Thereby you don't have to copy the file to every remote computer in advance.
Finally got it working with this:
Invoke-Command -FilePath \\netshare\PSScript.ps1 -ComputerName 10.11.12.13 -Credential $cred
Would still have liked to figure out how to run it inside a ScriptBlock however.

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

PowerShell Access is denied. PSRemotingTransportException + FullyQualifiedErrorId : PSSessionStateBroken

I was trying to establish a remote connection to another system and execute some basic commands.
Below are the steps that I have done :
Configured the remote machine to accept Shell commands - Enable-PSRemoting –
Force
Tested the configuration on remote machine - Test-WsMan COMPUTERNAME.
Executed the following commands on the host machine :
1.Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { Get-ChildItem C:\ } -credential USERNAME.
2.Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { Get-ChildItem C:\ } -credential $Credentials.
3.Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { Get-ChildItem C:\ }
In all the cases, we were getting access denied error :
Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
From MSDN:
Start Windows PowerShell as an administrator by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator.
The WinRM service is confi gured for manual startup by default. You must change the startup type to Automatic and start the service on each computer you want to work with. At the PowerShell prompt, you can verify that the WinRM service is running using the following command:
get-service winrm
The value of the Status property in the output should be “Running”.
To configure Windows PowerShell for remoting, type the following command:
Enable-PSRemoting –force
In many cases, you will be able to work with remote computers in other domains. However, if the remote computer is not in a trusted domain, the remote computer might not be able to authenticate your credentials. To enable authentication, you need to add the remote computer to the list of trusted hosts for the local computer in WinRM. To do so, type:
winrm s winrm/config/client '#{TrustedHosts="RemoteComputer"}'
Here, RemoteComputer should be the name of the remote computer, such as:
winrm s winrm/config/client '#{TrustedHosts="CorpServer56"}'
You should check if the winrm is running. Also add your remote hosts to the trusted hosts list (or your local machine).
Hope that helps.

Running a Setup.exe from a network share, via Invoke-Command in Powershell

PSEXEC started to give me some trouble, and I decided to recode in PowerShell.
This batch command used to work for me, before PSEXEC started messing things up:
psexec -accepteula \\<ServerToBeUpdated> -u <User> -p <Password> cmd /c "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe /silent /Update"
I'm trying to do this with Invoke-Command in Powershell, but with no luck so far.
I've tried many combinations, and googled a lot, and overall it seems that PowerShell is not fond of the UNC path I'm trying to install from.
Here is what I've got:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Start-Process -FilePath "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe" -ArgumentList "/update /silent" -wait }
I get this error message:
This command cannot be run due to the error: Access is denied.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : DE5441
Some people say that the setup.exe has be copied locally on the remote server. But this does not seem to be an option for me, mainly for two reasons.
My setup.exe identifies that it is not in the right path, then it kills the local the setup.exe process, and automatically starts a new setup.exe from the UNC path.
I also need the ExitCode from my setup.exe, which gets lost when the "killing" starts as mentioned in reason number 1.
As a final note, I did grant access for PowerShell to run remotely with the Enable-PSRemoting command, and I also get expected results from this simple test:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Hostname }
You are experiencing a so called double-hop authentication issue. If using normal authentication you will not be able to authenticate to a second computer from the machine you are invoking the command on.
To solve this you can use CredSSP.
To enable CredSSP on the machine that is being called:
Enable-WSManCredSSP -Role Server -force
To enable CredSSP on the client:
Enable-WSManCredSSP -Role Client -DelegateComputer server.domain.com -force
The -delegateComputer parameter expects a FQDN but also takes wildcards.
After enabling CredSSP you can use it to invoke your command with the parameter -authentication CredSSP

Confusing Powershell behavior

Am a bit confused w/ remote executing a powershell command. I have a test server (Win 2k8-R2-SP1) called ServerA, which has powershell remoting enabled correctly. From my dev machine (Win 2k8-R2-SP1), am able to remote execure powershell commands correctly.
But, when I try to execute the same command from a different server called ServerB (Win 2k8-R2), I get the following error
[ServerA] Connecting to remote server failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM.
If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
All three machines are in the same domain. My confusion is that from my dev machine, I am perfectly able to connect to ServerA and execute the command.
Will the fact that ServerB does not have SP1, make a difference? Please advise. I am using the same domain account which has admin rights on all 3 servers.
And the command that I am trying is
Invoke-Command -ComputerName ServerA -ScriptBlock {Get-UICulture}.
Please help.
Thanks
Run winrm quickconfig or Enable-PSRemoting -force from ServerB.
Verify service is running with get-service winrm
http://technet.microsoft.com/en-us/magazine/ff700227.aspx
Also, run this from your local dev box:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
I've had this same problem as well, on a machine that was working for remote powershell in the past. In my case the solution was to clear the Security Log. It was full, and I believe this was preventing powershell from making a proper secure connection.
The following fixed my problem:
You either have to empty your iplisten list which can be checked using the following CMD command:
netsh http show iplist
or to add the loop back address to it if there is any other addresses:
netsh http add iplisten 127.0.0.1
I was having this same issue and resolved in the following way. Running
winrm quickconfig
returned the below error.
winrm : WSManFault
At line:1 char:1
+ winrm quickconfig
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (WSManFault:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Message
ProviderFault
WSManFault
Message = WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.
Error number: -2144108183 0x80338169
WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.
In my case, this was a virtual NIC for a hypervisor service I was running on my machine. Once I changed this to Private, winrm quickconfig ran without error. I still had issues connecting to some machines and getting the same failure as described in this thread. To resolve, I checked for and started the winrm service where it was stopped.
get-service -ComputerName computer -Name winrm
Status Name DisplayName
------ ---- -----------
Stopped winrm Windows Remote Management (WS-Manag...
get-service -ComputerName computer -Name winrm | Start-Service
To save having to enable WinRM on every single server you manage, you can run this batch script:
Requirements:
A text file with all the servers you wish to enable WinRM on
PSExec in your Windows\System32 directory, downloaded from: https://technet.microsoft.com/en-us/sysinternals/pstools.aspx?f=255&MSPPError=-2147217396
Powershell on the server you're connecting to
Usage: EnablePSRemoting.bat PCs.txt
#echo off
for /f %%f in (%1) do (
psexec.exe \\%%f -accepteula -h -d -s powershell.exe "enable-psremoting -force"
echo Enabled on %%f
)
I have been looking for the answer for days and I found the issue;
It seems that the IIS 7 .NET Extensibility component was not installed causing this issue. We have a 2012 R2 Exchange 2010 server;
https://technet.microsoft.com/en-us/library/dd421841(v=exchg.80).aspx
I installed it by entering this in powershell;
See here the prerequisites for Exchange 2010.
https://technet.microsoft.com/en-us/library/bb691354(v=exchg.141)
This Exchange server of ours has only the mailbox role, the other is still CAS and HUB transport;
So we need this command;
Add-WindowsFeature NET-Framework-Features,RSAT-Clustering,Web-Mgmt-Console,WAS-Process-Model,Web-Basic-Auth,Web-Lgcy-Mgmt-Console,Web-Metabase,Web-Net-Ext,Web-Server,Web-Windows-Auth -Restart
The part of Web-Net-Ext installed the IIS 7.NET Extensibility component.
No need to restart.
Just my 2 cents, maybe this helps someone else :-)
In my case, WinRM was not configured correctly. This is what I used to enable it remotely:
$x=Get-WmiObject -ComputerName "<computer name>" -Namespace "root\cimv2" -Class "Win32_Process" -List
$x.Create('C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command {Enable-PSRemoting}"',$null,$null)