On a Cisco device, can parse the device capabilities using CDP ( see On a cisco device, how do you show the capabilities? ) however you might have CDP disabled on your network.
The best would be to check if Vlan interfaces are present (means a switching-able device) and if fastEthernet X/X/X type interfaces exist ( likely a switching-able router ).
By using these two facts, you get a quite accurate idea of what the device is, but it is Cisco specific.
You can also use the Cisco feature navigator / Juniper reference to construct a detection using the model name ( If you know which devices you have on you network, most of the times you have a limited quantity of models ), which will be more accurate but specific to your network.
The advantage is that this time it is generic and not specific to one brand, and there is no risk of a wrong detection.
Alternatively, you might want to use a CMDB or an inventory software to prepare this information for later use, then you would just have to query your database to check wether is a switch or a router.