How to test connectivity to a remote computer in powershell - 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'

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

Why do I get a "Get-WindowSize" not implemented error when using the PowerShell call Get-Service on a remote machine?

I have a Windows 10 host machine that connects to a Hyper-V Windows 10 VM hosted on the same box.
I've been following along the Pluralsight PowerShell tutorial.
I'm trying to get the services available on a remote computer.
I can start a session on the remote computer with the following command:
Enter-PSSession -ComputerName Client1 -Credential username
Once the session has started and I am connected, I attempt to call Get-Service to identify the services on the client computer.
[Client1]: PS C:\Users\username\Documents>Get-Service
When I run the above command, I get the following error message:
Remote host method get_WindowSize is not implemented.
+ CategoryInfo : ResourceUnavailable: (:) [out-lineoutput], PSRemotingDataStructureException
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerShell.Commands.OutLineOutputCommand
I am running the same version of PowerShell on the host and client machines (5.1.18362.145).
I assume that somehow this is an issue on the client machine?
[Client1]: PS C:\Users\username\Documents>Get-Service | out-string
That should work, maybe a bug with PowerShell or new version of Windows 10
Other link : https://social.technet.microsoft.com/Forums/en-US/67142783-2acd-4d54-aef2-8d89d71457c5/powershell-remoting-broken-in-windows-10-1903?forum=winserverTS
"Remote host method get_WindowSize is not implemented."
This happens to all Remoting Sessions started With Powershell_ISE on the Client-Side.
The workaround with Out-String sucks, it destroys the Result-Object of that call.
Best fix so far is either using not ISE or embed your remote Procedure in a Script and call it with Powershell.exe
Really annoying...and not fixed by now.
Workaround Example: Instead of using enter-pssession and then asking for a result of running services, you could use: $YourServices=Invoke-command -ComputerName <computername> -ScriptBlock {get-service}. Then you have all Service-Stats in your Object $YourServices.

Run .ps1 file on powershell: IP address connection

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.

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.

Powershell error/exception handling

I am having some problems with handling errors/exceptions regarding the invoke-command.
I am trying to catch errors when the target computer does not exist, however the message i am shown and the way the script in the catch block acts makes me think there is something i missed or miss understood.
this is the portion of the script with the problem:
$session = New-Pssession -computername $computerName
Invoke-Command -session $session -ScriptBlock $command -ArgumentList $sqlServerName, $userToGivePermisions
Remove-PSsession -session $session
Basically i want to handle errors when $computerName is not a valid computer on the network. I purposely gave it a wrong name to test it out and i get the following error:
[dcd] Connecting to remote server failed with the following error message : WinRM cannot process the request. The following error occured while using Kerberos authentication: The network path was not found.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
[dcd] is the name of the non existing machine. I put the code in a try catch and did a check on the error message using a -contains. The condition ALWAYS came out false and i tried almost ever single word in the error above.
When i displayed the error message in the catch block using $_.exception.message i got a different error about $session being null.
When i did a -contains using words in the displayed error message about $session it still returned false for every word i tested.
I don't understand which of these is the error and why isn't the -contains ever returning true. I added the -ea stop to all 3 lines to catch all the non terminating errors but to no avail.
Anyone have any idea what is going on?
-contains checks whether an element is in an array or not. e.g:
1,2,3 -contains 2 # Is True
"a","bc","d" -contains "b" # Is False
Try the -match or the -like operators instead. Have a look at the comparison operator documentation.