How to obtain exit code when I invoke NET USE command via Powershell?

pencilCake picture pencilCake · Mar 18, 2014 · Viewed 8.3k times · Source

I have the powershell snippet below which I intend to close connections to a shared locations by calling NET.exe tool:

 if ($connectionAlreadyExists -eq $true){
            Out-DebugAndOut "Connection found to $location  - Disconnecting ..."
            Invoke-Expression -Command "net use $location /delete /y"  #Deleting connection with Net Use command
            Out-DebugAndOut "Connection CLOSED ..."
        }

QUESTION:How can I check if the invoked Net Use command worked fine without any errors? And if there is, how can I catch the error code.

Answer

Duncan picture Duncan · Mar 18, 2014

You can test the value of $LASTEXITCODE. That will be 0 if the net use command succeeded and non-zero if it failed. e.g.

PS C:\> net use \\fred\x /delete
net : The network connection could not be found.
At line:1 char:1
+ net use \\fred\x /delete
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The network con...d not be found.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

More help is available by typing NET HELPMSG 2250.

PS C:\> if ($LASTEXITCODE -ne 0) { Write-Error "oops, it failed $LASTEXITCODE" }
if ($LASTEXITCODE -ne 0) { Write-Error "oops, it failed $LASTEXITCODE" } : oops, it failed 2
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

You might also choose to capture the error output from the net use command itself and do something with it.

PS C:\> $out = net use \\fred\x /delete 2>&1

PS C:\> if ($LASTEXITCODE -ne 0) { Write-Output "oops, it failed $LASTEXITCODE, $out" }
oops, it failed 2, The network connection could not be found. 
More help is available by typing NET HELPMSG 2250.