windows – batch file to check 64bit or 32bit OS – Stack Overflow

Batch file to check 64bit or 32bit os

Many DOS commands in the different versions of Windows are similar but may support different parameters. Plus, newer versions of Windows may support new commands or retire older ones. Thus, if you wish to write a batch file that can run on different types of machines, it may prove beneficial to determine the version of Windows on which the batch file is running. This way the batch file can execute commands appropriate to the operating system.

The following batch file will determine whether or not the machine is running Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, Windows 2000, or Windows NT. It can easily be modified to support other versions of Windows as necessary or to set an environment variable based on the version of Windows detected. Note that for this batch file to correctly discern between newer versions of Windows Server and consumer versions of Windows, it is more convoluted than batch files you may see elsewhere. I have explained the reasoning below.

1) Open a Notepad window.

2) Copy the following text into Notepad (you may want to access this tip’s printed version as some lines wrap):

@echo off

ver | find "2003" > nul
if %ERRORLEVEL% == 0 goto ver_2003

ver | find "XP" > nul
if %ERRORLEVEL% == 0 goto ver_xp

ver | find "2000" > nul
if %ERRORLEVEL% == 0 goto ver_2000

ver | find "NT" > nul
if %ERRORLEVEL% == 0 goto ver_nt

if not exist %SystemRoot%system32systeminfo.exe goto warnthenexit

systeminfo | find "OS Name" > %TEMP%osname.txt
FOR /F "usebackq delims=: tokens=2" %%i IN (%TEMP%osname.txt) DO set vers=%%i

echo %vers% | find "Windows 7" > nul
if %ERRORLEVEL% == 0 goto ver_7

echo %vers% | find "Windows Server 2008" > nul
if %ERRORLEVEL% == 0 goto ver_2008

echo %vers% | find "Windows Vista" > nul
if %ERRORLEVEL% == 0 goto ver_vista

goto warnthenexit

:ver_7
:Run Windows 7 specific commands here.
echo Windows 7
goto exit

:ver_2008
:Run Windows Server 2008 specific commands here.
echo Windows Server 2008
goto exit

:ver_vista
:Run Windows Vista specific commands here.
echo Windows Vista
goto exit

:ver_2003
:Run Windows Server 2003 specific commands here.
echo Windows Server 2003
goto exit

:ver_xp
:Run Windows XP specific commands here.
echo Windows XP
goto exit

:ver_2000
:Run Windows 2000 specific commands here.
echo Windows 2000
goto exit

:ver_nt
:Run Windows NT specific commands here.
echo Windows NT
goto exit

:warnthenexit
echo Machine undetermined.

:exit

3) Save the file as %WINDIR%whichvers.bat

4) Now, from the command prompt, enter:

whichvers

This will display which version of Windows you are running.

NOTES:

  1. The reasoning for using the SYSTEMINFO command rather than relying on the VER command is because Windows Server 2008 “shares” version numbers with other Windows releases (see Microsoft). Thus relying on a “version number” of 6.0 to detect Windows Vista or 6.1 to detect Windows 7 fails to differentiate a machine from Windows Server 2008 or Windows Server 2008 R2.

  2. The creation of %TEMP%osname.txt is solely because I could not place the results of systeminfo | find “OS Name” directly into the for /f command – it does not like piped commands. You may find an easier way to handle grabbing the information from SYSTEMINFO – if so, please comment.

  3. The environment variable %vers% has leading spaces. I could remove these with a longer batch file, but in this case it is not necessary.

  4. The batch file detects for SYSTEMINFO as it assumes if it gets beyond the older operating system detections, the running version of Windows is even older and will not have this utility. On Windows 7 64-bit it is still located in the %SystemRoot%system32 folder – if later versions of Windows become 64-bit only, this batch file may have to be updated.

Return to the Windows XP and DOS page.

How can i check for python version in a program that uses new language features?

As noted above, syntax errors occur at compile time, not at run time. While Python is an “interpreted language”, Python code is not actually directly interpreted; it’s compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that’s when you’re getting your error, not (quite exactly) when your code is running.

You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code – and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:

import sys
if sys.hexversion < 0x02060000:
    from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
    from my_module import thisFunc, thatFunc, theOtherFunc

.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)

Another thing that might be worth pointing out (that I’m a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like

value = 'yes' if MyVarIsTrue else 'no'

..it did support code like

value = MyVarIsTrue and 'yes' or 'no'

That was the old way of writing ternary expressions. I don’t have Python 3 installed yet, but as far as I know, that “old” way still works to this day, so you can decide for yourself whether or not it’s worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.

How to launch cmd, check system hardware and software specification.

What is CMD?,
Basically CMD stands for Command, CMD is the interface which was used in the early ages of the computer revolution before a Graphical User Interface was invented by Apple .Inc on a Macintosh Computer. The graphical User Interface was later adopted by the PC or Windows computer later on. The CMD interface or window is normally a black screen with lines and it operates with commands issued by the user through keyboard input.

To launch the command line on a windows 7 or later version, Press the Windows Key, Type “CMD, (without the quotes) and hit the return or Enter key on the Keyboard.
A window like the one below will be launched and you will be able to proceed with checking for system software and hardware specification.

To check for system software and hardware, Typesysteminfo” in the command line and press the Enter on your keyboard.

windows - batch file to check 64bit or 32bit OS - Stack Overflow

The commandline will load both the hardware and software specification of the machine or computer on which you will be running the command.
On completion of loading the command issued, the screen will be filled with multiple text.

Screenshot: hardware and software specification of the machine or computer on which you will be running the command.

C:UsersShafique>systeminfo
Host Name: SHAFIQUE-PC (This represents the name of the system, normally entered sring installation of the Operating System)
OS Name: Microsoft Windows 7 Ultimate (This is the name and Edition of the Operating system of the computer on which the command is issued)
OS Version: 6.1.7600 N/A Build 7600 (this represents the version of the Operating system)
OS Manufacturer: Microsoft Corporation (Operating system manufacturer)
OS Configuration: Standalone Workstation
OS Build Type: Multiprocessor Free
Registered Owner: Shafique
Registered Organization:
Product ID: 00426-OEM-8992662-00010
Original Install Date: 12/2/2021, 1:09:16 AM
System Boot Time: 11/16/1655, 2:05:42 PM
System Manufacturer: TOSHIBA
System Model: Satellite L300
System Type: X86-based PC
Processor(s): 1 Processor(s) Installed. [01]: x64 Family 6 Model 15 Stepping 13
GenuineIntel ~1662 Mhz
BIOS Version: INSYDE 1.30, 10/9/2008
Windows Directory: C:Windows
System Directory: C:Windowssystem32
Boot Device: DeviceHarddiskVolume2
System Locale: en-us;English (United States)
Input Locale: en-us;English (United States)
Time Zone: (UTC 03:00) Nairobi
Total Physical Memory: 1,916 MB
Available Physical Memory: 252 MB
Virtual Memory: Max Size: 3,855 MB
Virtual Memory: Available: 1,249 MB
Virtual Memory: In Use: 2,606 MB (this figure represents the RAM the computer has)
Page File Location(s): C:pagefile.sys (this is the path to the file in which system state is saved whenever the computer is put in sleep mode or Hibernated)
Domain: WORKGROUP
Logon Server: \SHAFIQUE-PC
Hotfix(s): 1 Hotfix(s) Installed. [01]: KB958488
Network Card(s): 2 NIC(s) Installed. : Realtek RTL8102E/RTL8103E Family PCI-E Fast Ethernet NIC (NDIS 6.20)
Connection Name: Local Area Connection
Status: Media disconnected
[02]: Realtek RTL8187B Wireless 802.11b/g 54Mbps USB
2.0 Network Adapter
Connection Name: Wireless Network Connection
Status: Media disconnected

How to use CMD to for checking disk capacity and fixing volume errors
Launch the elevated commandline as described in the previous How to article,

Type diskpart and hit the return or enter key
system errors

Next, type list disk and hit the return or enter key on your keyboard

windows - batch file to check 64bit or 32bit OS - Stack Overflow

Disk 0 is the combined internal HDD in the computer having 149 GB and Disk 1 is the recovery of reserved partition of the physical HDD, it is normally not shown among the system drive partition as it is a system reserved partition and its automatically created at the time of installing the Operating System. The total capacity of the HDD in the computer on which the command were run is 150GB after adding the system reserved memory.

To check computer drives for Errors and fix them using CMD
Launch CMD as described in the previous how to article, or to launch cmd faster, press and hold down the Windows Key, then Press the R key on your keyboard, then type CMD in the small Run window and hit the enter key on your keyboard.
windows - batch file to check 64bit or 32bit OS - Stack Overflow

Type chkdsk D: /r /f

The above command will check the driver or partition labeled D, repair and fix any error found.
windows - batch file to check 64bit or 32bit OS - Stack Overflow

This may take several minutes depending on the capacity of data on the drive and the size of the drive being checked.

windows - batch file to check 64bit or 32bit OS - Stack Overflow

hardware and software specification of the machine or computer on which you will be running the command.

Learn how grepper helps you improve as a developer!

:/>  Как форматировать все на компьютере

Windows: получить информацию о железе и ос через cmd (утилита wmic). – trust me i`m an engineer

Частенько возникают ситуации когда нужно узнать аппаратную начинку ПК, не отрывая при этом пользователя от работы. На мой взгляд, самый быстрый вариант запустить удаленно командную строку с помощью PsExec или DameWare Remote Support и поглядеть нужную информацию. Ваш покорный слуга чаще всего использует утилиту WMIC для этих целей. Ниже приведена общая информация и список часто используемых ключей.

WMI —  запиленная под windows реализация стандарта Web-Based Enterprise Management ( WBEM ). Стандарт используется многими крупными компаниями для мониторинга и управления различными системами и компонентами распределенной информационной среды предприятия с использованием объектно-ориентированных идеологий и протоколов HTML и XML

Утилита WMIC (Windows Management Instrumentation Command) — консольная утилита для вызова объектов и методов WMI. Присутствует во всех версиях Windows начиная с Windows XP.  

Вообще функционал WMIC довольно велик. Если заморочиться, с помощью этого инструмента можно сделать много чего. Ваш покорный слуга выписал список популярных команд для получения информации о железе и ОС, чтобы долго не вспоминать.

1. Получить информацию о процессоре. (Название, количество ядер, количество потоков, максимальная частота)

wmic CPU get Name,NumberOfCores,NumberOfLogicalProcessors,Maxclockspeed /format:list

2. Получить информацию о материнской плате (Производитель, модель)

wmic baseboard get manufacturer, product /format:list

3. Получить информацию о BIOS (Производитель, Дата, Версия)

wmic BIOS get manufacturer,name,SMBIOSBIOSVersion,version /format:list

4. Получить информацию о модулях памяти (Объем, модель, серийный номер)

wmic memorychip get manufacturer,speed,Capacity,DeviceLocator,PartNumber /format:list

5. Получить информацию о HDD (Модель, Размер)

wmic diskdrive get model,size /format:list

6. Получить информацию о логических дисках. (Буква, общий объем, свободное место, имя)

:/>  Восстановление системы не работает, не удалось, не завершилось успешно в Windows 10

wmic logicaldisk get deviceid,size,freespace,volumename /format:list

7. Получить список принтеров и их статусы.

wmic printer list status

8. Получить информацию об операционной системе (Название, версия)

wmic OS get Name,Version /format:list

9. Получить список служб.

wmic service list brief

10. Получить список запущенных процессов

wmic process list brief

Проверка версии python

Python предустановлен в большинстве дистрибутивов Linux и macOS.

Чтобы узнать, какая версия Python установлена в вашей системе, введите команду python –version или python -V:

python --version

Команда выведет версию Python по умолчанию, в данном случае, то есть 2.7.15. Версия, установленная в вашей системе, может отличаться.

Python 2.7.15 

Версия Python по умолчанию будет использоваться всеми сценариями, которые установлены в качестве интерпретатора в строке сценария shebang.

В некоторых дистрибутивах Linux установлено несколько версий Python одновременно. Обычно двоичный файл Python 3 называется, python3а двоичный файл Python 2 – python или python2, но это не всегда так. Вы можете проверить, установлен ли Python 3, набрав:

python3 --version
Python 3.6.8

Хотя Python 2 хорошо поддерживается и активен, Python 3 считается настоящим и будущим языка.

На момент написания этой статьи, последним основным выпуском Python является версия 3.7.x. Скорее всего, в вашей системе установлена более старая версия Python 3. Если вы хотите установить последнюю версию, процедура зависит от операционной системы, которую вы используете.

Оставьте комментарий