Run .ps1 file on powershell: IP address connection - powershell

I am new to powershell and trying to run a .ps1 file in but am getting the following error.
Any help would be much appreciated!
[IP ADDRESS] Connecting to remote server [IP ADDRESS] failed with the following error message : The WinRM
cannot process the request. Default authentication may be used with an IP address under the following conditio
transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use
winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated.
information on how to set TrustedHosts run the following command: winrm help config. For more information, see
about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: ([IP ADDRESS]:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotUseIPAddress,PSSessionStateBroken
PS C:\windows\system32> winrm help config

Your code looks like it requires you to update line 8 with actual computer names. The win rm error is likely coming from the net use or Copy-Item cmdlets.
I would highly recommend being careful when running arbitrary powershell scripts from the internet. You should break down what each line is doing and understand before executing.

Related

Attempting to run Powershell on Remote Computer - Errors

I am wanting to access another windows device on my local network and run powershell commands. In my mind, it would be similar to SSH into a linux box. I would have an open window on my machine, but would be operating within the remote machine so that I can execute composer install or php artisan migrate type commands on the remote machine.
I have followed the instructions from:
https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/
I am attempting to use
Enter-PSSession -ComputerName <RemoteComputerName> -Credential <RemoteUser>
When I run the command, I get a popup with the username populated and asking for a password. I have entered my MS password for the account. (I have changed the password from within Windows to ensure they are synced)
And I get the following error:
Enter-PSSession : Connecting to remote server <REMOTECOMPUTER> failed with the following error message : The WinRM client
cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not
joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts
configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not
be authenticated. You can get more information about that by running the following command: winrm help config. For
more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName <REMOTECOMPUTER> -Credential <USER>
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (<REMOTECOMPUTER>:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I can't seem to figure out how to do this. And, maybe more importantly, is there a better way/utility to accomplish my goal? The remote computer is hosting WAMP and I just want to be execute development commands remotely so I can move the RemoteComputer into the basement and not have to spin my chair around to type on it.
TIA

How to test connectivity to a remote computer in powershell

There are two ways suggested in the docs both of which are completely useless to determine if the remote computer is available for powershell remoting.
Test-Connection is useless because it sends only ping, however, the destination may be running Intel AMT and thus respond to ping or may not be running winRM service, so this provides no useful information.
Test-WSMan should test the availability of Windows RM service, but it only works, if the WinRM works, otherwise (the computer is off or WinRM is not running) it gives an error:
Test-WSMan : 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".
At line:2 char:1
Test-WSMan -ComputerName destinationcomputer
+ CategoryInfo : InvalidOperation: (destinationcomputer:String) [Test-WSMan], InvalidOperationException
+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.TestWSManCommand
So I tried enveloping Test-WSMan in try-catch commands, but it still gives the error out, it is not really caught:
Try {
Test-WSMan -ComputerName destinationcomputer
} catch {
write-output "not working"}
Any idea how to do this? (i would be happy with Test-WSMan if I could get rid of the error and enforce it to return true or false)
Test $? after running test-wsman.
Test-WSMan destinationcomputer
if (! $?) {
'not working'
}
You could also do it this way since a failure returns no standard output:
if (!(Test-WSMan destinationcomputer)){
'not working'
}
See also Check if a command has run successfully
Also in powershell 7:
Test-WSMan destinationcomputer || 'not working'

Unable to contact server when I SSH into Powershell using an RSA key

I am working on a script that logs into a VM connected to my AD to perform some administrative functions. The script will be triggered by an application running on a Linux host. I've installed PowerShell Core and the Windows-Compatibility PowerShell module to allow me to log in via SSH. I can log in successfully and run the my script if I use a password, but if I log in using an RSA key, I get this error when I import AD:
Unable to contact the server. This may be because this server does not
exist, it is currently down, or it does not have the Active Directory
Web Services running.
CategoryInfo : ResourceUnavailable: (:) [Get-ADComputer], ADServerDownException
FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
PSComputerName : localhost
The script on the Linux host looks something like this:
#!/bin/bash
ssh ad\\ad-user#windows-host-ip \
-o IdentitiesOnly=yes \
-i ./id_rsa \
"C:\\pwsh\\pwsh.exe -c C:\Users\ad-user\Scripts\ad-management-script.ps1"
And the ad-management-script.ps1 looks something like this:
Import-WinModule ActiveDirectory
Get-ADUser -Identity ad-user
Like I said before: This runs perfectly if I leave the key off and enter a password, but it hits the error I mentioned above if I use the key.
Other notes: Regardless of which method I use to log in, I get these values from the $env:
> $env:username
ad-user
> $env:userdomain
ad
Thanks in advance for any guidance.
As per brief googling looks like people are getting similar issues with ActiveDirectory module while remoting to Windows machine. Not sure suggested workarounds are applicable to your case though. However there are alternatives for using this module. Try options below and see if any of it works.
1. In Powershell (not core):
$user = "someuser"
$searchByUser = "(&(objectCategory=person)(objectClass=organizationalPerson)(samaccountname=$user))"
([adsisearcher]$searchByUser).FindOne().Properties
2. DSQUERY (In CMD, no need for powershell)
dsquery * -filter "samaccountname=someuser"
3. NET (in CMD)
net user SOMEUSER /domain
This is known as the double hop problem. We can not use keys which are used for authentication to remote VM , to authenticate AD server too. There are multiple option which you can use, here is the guide
https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-7.2

Fix "Unable to check the status of the firewall" of `Set-WSManQuickConfig`

Why Enable-PSRemoting/Set-WSManQuickConfig can not "check the status of the firewall" running under Administrator on Windows 2012R2, Azure WebRole? How to fix this?
PS D:\Users\***User> enable-psremoting -force
WinRM is already set up to receive requests on this computer.
Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2"
Machine="localhost"><f:Message><f:ProviderFault provider="Config provider"
path="%systemroot%\system32\WsmSvc.dll"><f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"
Code="2" Machine="RD***CA2"><f:Message>Unable to check the status of the firewall.
</f:Message></f:WSManFault></f:ProviderFault></f:Message></f:WSManFault>
At line:69 char:17
+ Set-WSManQuickConfig -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand
OS Name: Microsoft Windows Server 2012 R2 Datacenter. OS Version: 6.3.9600 N/A Build 9600. Powershell: 4.0
PS.
Yes, there are:
Error PSRemoting using Session and CredSSP. No clear solution
Winrm quick config shows error . Rebooting/reimaging the instance does not help.
https://support.microsoft.com/en-us/kb/2697738. Hotfix (2012 year!) is not installed but then it needs installed each deployment?
https://technet.microsoft.com/en-us/library/hh849694.aspx. Has this message but that is for "client versions"
http://terenceluk.blogspot.ru/2012/05/executing-command-winrm-quickconfig.html Restarting firewall does not help
How to enable powershell remoting in Powershell V3?. No "HKLM:\SYSTEM\Policies\Microsoft\Windows Firewall" to change. restarting firewall service does not help.
Update.
Other valuable refs:
http://www.thomasmaurer.ch/2011/01/quick-powershell-remoting-guide/
http://www.davidaiken.com/2011/01/12/enable-powershell-remoting-on-windows-azure/
Get-Help about_Remote_Troubleshooting
In my case running this helped (manually creates the firewall rule):
netsh advfirewall firewall add rule name="Windows Remote Management (HTTP-In)" dir=in action=allow service=any enable=yes profile=any localport=5985 protocol=tcp
Taken from http://www.davidaiken.com/2011/01/12/enable-powershell-remoting-on-windows-azure/
I tried to enable winrm for ansible testing, nothing helped, the rules were in place. Changing the Windows display language from czech to english fixed my problem.

Random errors while doing Enter-PSSession in powershell

I have setup lots of Powershell scripts on my WIndows 2008 R2 server. The scripts do lots of processing (data crunching, executing SQLCMD.exe, bcp.exe etc). All of these scripts work without issues.
I am trying to call and execute the scripts from a remote laptop (within the same network) using the following command:
Enter-PSSession -ComputerName sun -ConfigurationName myprofile
The "myprofile" currently has just one function that will change directory to c:
This allows me to execute the scripts from my local laptop, however, they "run" on the server. That is my understanding.
However, I have not seen any scripts execute fully. At random intervals, the scripts fail with the below error messages... Once again, I have never seen these errors when I am trying to run the scripts on the server itself.
Any inputs on how to "fix" these errors? Any settings that I need to do on the "client" in terms of memory allocation?
a.
Processing data for a remote command failed with the following error message: Not enough storage is available to complete this operation. For more information, see the about_Remote_Troubleshooting Help topic.
b.
Get-Content : Exception of type 'System.OutOfMemoryException' was thrown.
At E:\automation\mssql-upload.ps1:144 char:14
+ (get-content <<<< $PipeFile -ReadCount 1000) | set-content $FinalFile
+ CategoryInfo : InvalidOperation: (:) [Get-Content], OutOfMemoryException
+ FullyQualifiedErrorId : ProviderContentReadError,Microsoft.PowerShell.Commands.GetContentCommand
c.
[Microsoft] [ODBC Driver Manager] Driver's SQLAllocHandle on SQL_HANDLE_ENV
d.
Processing data for a remote command failed with the following error message: The WSMan provider host process did not return a proper response. A provider in the host process may have behaved improperly. For more information, see the about_Remote_Troubleshooting Help topic.
It is likely your remote session is bumping up against the WS-Man quota MaxMemoryPerShellMB. You can see the current value by executing this command on the remote machine:
Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB
You can set a new value like so:
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 512 -Force
This sets the value at 512MB. Set it to a value that works for your application.