Try, catch in powershell invoke-command - powershell

It is not going to "catch" block as part of invoke-command for the incorrect host using powershell
$server= #("correcthost","Incorrecthost")
foreach($server in $server)
{
Try{
Invoke-Command -ComputerName $server -ArgumentList $server -ScriptBlock {
$serverk=$args[0]
write-host $serverk
}
}
Catch
{
write-host "error connecting to $serverk"
}
}
I expect the catchblock getting executed as i am trying to incorrect host
but the actual output is not printing catch block

There are two issues. First, the variable $serverk is out of scope in the catch block. It's being used only on the remote computer, so it doesn't exist - or have value - on the local system.
Debugging any Powershell script should always start with turning on the strict mode, so warnings about uninitialized variables are generated. Like so,
Set-StrictMode -Version 'latest'
...<code>
The variable '$serverk' cannot be retrieved because it has not been set.
At line:12 char:41
+ write-host "error connecting to $serverk"
+ ~~~~~~~~
+ CategoryInfo : InvalidOperation: (serverk:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The fix is easy, just refer to $server that's the variable used in iterating $servers.
The second issue is caused by ErrorAction, or to be specific, not declaring one. Add -ErrorAction Stop to Invoke-Command and process the exception in catch block like so,
catch{
write-host "error connecting to $server`: $_"
}
error connecting to doesnotexist: [doesnotexist] Connecting to remote server doesnotexist failed...

Related

How can I handle the remote server message by PowerShell?

I created a short PowerShell scrtipt in order to import a .reg file (an ODBC) to another server session.
I faced to this warning/issue.
The message is this (below):
The operation completed successfully.
+ CategoryInfo : NotSpecified: (The operation completed successfully.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : MYSERVERNAME
NotSpecified: (:) [], RemoteException
The script, install without problem the .reg file, but constantly I get the message.
This is my code:
#PARAMETERS - Variables
$Serverlist = Get-Content C:\ServerList.txt
try
{
Foreach ($ServerName in $Serverlist)
{
$session = New-PSSession -ComputerName $servername
Write-Host -Foregroundcolor Green "Copying ODBC Driver for $servername"
$copy_cmd = "C:\MYFILE.reg"
Copy-Item $copy_cmd \\$servername\C$\ -recurse -force;
Write-Host -Foregroundcolor Green "ODBC Successfully copied on $servername"
#$session = New-PSSession -ComputerName $servername
Invoke-Command -Session $session -ScriptBlock {
#Start-Process
reg import C:\CopiedFile.reg #This line generate the message
Write-Host -Foregroundcolor Green "ODBC was installed
}
catch
{
Write-Host "ERROR" -Foregroundcolour Red
exit
}
I tried to incapsulate the Invoke-Command or reg import in to try - catch statement, but the message still appear. I used another command, instead reg import, but the nothing change.
I can use this command line, but I would like to catch the error.
Write-Host -Foregroundcolor Green "ODBC is installed " } ##-ErrorAction SilentlyContinue
There is any way to get the eventually error or handle the message.
Thanks in advance.
If the try block does not generate a terminating error, it will not move into the Catch block. This is controlled by -ErrorAction parameter. So you can set
Invoke-Command Session $session -ScriptBlock {} -ErrorAction Stop
This will cause the Invoke-Command Cmdlet to generate terminating errors(if any error occurs) allowing catch block to execute.

If statement in PowerShell dependant on if RPC Server is unavailable

I'm writing a script in PowerShell that ideally would gather information from another server. If it's not able to reach that server, I want to prompt it to have the user manually enter the information. I know how to do all of these, but I'm getting hung up when the RPC Server is unavailable. I will also say that I know how to fix the error when it occurs, but I do not want to rely on my end users to have to go in and fix this.
As an example, if I run:
Get-WmiObject Win32_ComputerSystem -Computer 10.5.21.94
the result I get back is:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ Get-WmiObject Win32_ComputerSystem -Computer 10.5.21.94
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],
COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I'm trying to find a way to write an if statement that will check to see if the RPC server is available or not, but I'm not sure what to check in order to create a true/false variable. And again, I'm not really looking for someone to tell me how to write the if statement, I'm just trying to figure out any query I can run to determine if I can properly connect to this server and get a result back that can tell me to continue on or not.
An easy way to get around it in an if-statement is just to ignore potential errormessages with Erroraction and use a -not statement to check whether it can reach the destination or not and then append a $false value to a variable if it can't.
See the below example.
$status = ""
if (!(Get-WmiObject Win32_ComputerSystem -ComputerName 10.5.21.94 -ErrorAction SilentlyContinue)) {
Write-Host "Server is unavailable!"
$status += $false
}
else {
Get-WmiObject Win32_ComputerSystem -ComputerName 10.5.21.94
}
if ($status -eq $false) {
$Server = Read-Host "Please enter the destionation"
Get-WmiObject Win32_ComputerSystem -ComputerName $Server
}
There was a suggestion for a Try/Catch block, but since this is not a terminating error, it didn't work initially. Then I found this:
Try/catch does not seem to have an effect
There is an answer in there about making all errors terminating:
try {
$ErrorActionPreference = "Stop"; #Make all errors terminating
get-item filethatdoesntexist; # normally non-terminating
write-host "You won't hit me";
} catch{
Write-Host "Caught the exception";
Write-Host $Error[0].Exception;
}finally{
$ErrorActionPreference = "Continue"; #Reset the error action pref to default
}
This gave me exactly what I was looking for!

Handling a remote connection exception

The desired result from this script is to find out the PowerShell version on a list of hosts. I would like to handle the exception when the remote machine is down or does not have remoting enabled. However, the catch does not appear to be entered. Just the standard red flaming error message from PowerShell appears.
What do I need to do to catch the exception?
X:\Scripts\PSAutomation> Get-Content .\get-versions.ps1
server_list = #(
'CAPPY'
)
$server_list |
ForEach-Object {
Try {
Invoke-Command -ComputerName $_ {$PSVersionTable.PSVersion}
}
Catch
{
Write-Host "Failed to connect to $_"
}
}
X:\Scripts\PSAutomation> .\get-versions.ps1
[CAPPY] Connecting to remote server CAPPY failed with the following error message : WinRM cannot process the
request. The following error occurred while using Kerberos authentication: Cannot find the computer CAPPY. Verify
that the computer exists on the network and that the name provided is spelled correctly. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (CAPPY:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken
Just set the ErrorAction for that call to stop:
Invoke-Command -ComputerName "sdf" {$PSVersionTable.PSVersion} -ErrorAction Stop

Handling Domain Join Errors

I have created a basic script to add a PC to the domain. Although this works there is room for error, and I want to put in some error handling.
do {
Add-Computer -DomainName $Domain -Credential(get-credential)
} while (!$?)
Using !$? runs the while loop while the last command is not successful.
However, there are various errors that return. Whether the PC is off the network, incorrect user ID or password, or domain specification, I want to be able to handle those errors and display something meaningful.
One of the errors returned
Add-Computer : This command cannot be executed on target computer('PCName') due to
following error: Logon failure: unknown user name or bad password.
At line:1 char:13
+ Add-Computer <<<< -DomainName $Domain -Credential(get-credential);
+ CategoryInfo : InvalidOperation: (PCNAME:String) [Add-Computer], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.AddComputerCommand
Working with error handlers in lets say VBA, an error ID is given, and using if statements you can do something with it.
The FullyQualifiedErrorID in the error above is the same across all errors received for different reasons, so I do not believe I can use that.
How can I capture the specific error "Logon failure: unknown user name or bad password." or other errors and display a meaningful message so the admin can take appropriate action?
If nothing else you should be able to use the error message for distinguishing between errors:
do {
$joined = $true
$cred = Get-Credential
try {
Add-Computer -DomainName $Domain -Credential $cred -ErrorAction Stop
} catch {
$joined = $false
switch -regex ($_.Exception.Message) {
'.*unknown user name.*' { ... }
'.*domain does not exist.*' { ... }
...
default { 'Unexpected error' }
}
}
} until ($joined)
Note that you'll need to set the error action to Stop (-ErrorAction Stop), because otherwise the errors would be non-terminating and thus not catchable.
Use it with the -ErrorAction parameter:
Add-Computer ... -ErrorAction SilentlyContinue -ErrorVariable computerError
The ErrorVariable is an array, so the resulting error will be stored in:
$computerError[0]
To use the same variable over and over again, use a + in front of the var name:
Add-Computer -ErrorVariable +manyErrors
And the last error will always be:
$manyErrors[$manyerrors.count - 1]
To get the last error code if it has a corresponding Win32 error code then run the following
$manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode
And then if you gather the potential error codes you could do the following
if ($manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode -eq 1)
{
Write-Host error happened
}
elseif ($manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode -eq 2)
Write-Host other error happened
}

PowerShell IIS:\ WebAdmin Remote Invocation triggers WSAStartup error, WSANOTINITIALISED

I'm using PSRemoting with the WebAdministration module to get info about various sites, and it's working. I am, however, receiving an annoying non-fatal COM exception during invocation of the command, and wondering if anyone else has resolved it. Here's a minimal implementation:
cls
$command = {
param($alias)
Import-Module 'WebAdministration'
$binding = Get-WebBinding -HostHeader $alias
$binding
}
$server = 'server'
$args = #('alias')
$session = New-PSSession -ComputerName $server
Write-Host ("Invoking")
try {
Invoke-Command -Session $session -ScriptBlock $command -ArgumentList $args
Write-Host ("Invoked")
} catch {
Write-Host ("Caught $_")
} finally {
Write-Host ("Removing")
Remove-PSSession -Session $session
Write-Host ("Removed")
}
And here are the results:
Invoking
protocol : http
bindingInformation : 10.x.x.x:80:alias
...
Schema : Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema
An unhandled COM interop exception occurred: Either the application has not called WSAStartup, or WSAStartup failed. (Exception from HRESULT: 0x800
7276D)
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : COMException
Invoked
Removing
Removed
I observe the result is returned prior to the error being thrown.
Amusing details:
- Get-Website, Get-Item "IIS:\...", Get-WebBinding all result in the same error
- Running $command directly on the target machine as written results in no error
- Get-Item "d:\..." does not result in any error
- The COM error doesn't
I was able to work around the issue using the following:
$iisIpAddresses = Invoke-Command -Session $session -scriptblock {
if (!(Get-Module WebAdministration))
{
Import-Module WebAdministration
}
$iisBindings = Get-WebBinding
[String[]]$iisBindings = $iisBindings | Select bindingInformation
$iisBindings
}
Remove-PSSession $session
This is buried somewhere deep in the bowels of PowerShell's implementation of .NET and winsock. It's below anything I can calibrate, so I've added " -ErrorAction SilentlyContinue" to my remote invoke. It doesn't fix anything, but everything works correctly. That's answer enough for now, I guess.