Windows date to variable

How-to: Windows Environment Variables

Environment variables are mainly used within batch files, they can be created, modified and deleted for a session using the SET command. To make permanent changes, use SETX

Variables can be displayed using either SET or ECHO.

Variables have a percent sign on both sides: %ThisIsAVariable%
The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
(This is unlike Parameter variables which only have one % sign and are always one character long: %A )

A variable name may include any of the following characters:
A-Z, a-z, 0-9, # $ ‘ ( ) * + , — . ? @ [ ] _ `

The first character of the name must not be numeric.

Array variables

Unlike PowerShell, which fully supports arrays, there is no built in support for array variables within the CMD shell. However with some effort you can replicate this functionality using a series of separate variables, named to represent the array:

Set elem[1]=First element
Set elem[2]=Second one
Set elem[3]=The third one

To perform array indexing operations with these, use EnableDelayedExpansion and a reference like !elem[%var%]!
this is explained fully in this StackOverflow Q/A.

Standard (built-in) Environment Variables

Variable Volatile
(Read-Only)
Default value assuming the system drive is C:
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\ \AppData\Roaming
CD Y The current directory (string).
ClientName Y Terminal servers only — the ComputerName of a remote host.
CMDEXTVERSION Y The current Command Processor Extensions version number. (NT = «1», Win2000+ = «2».)
CMDCMDLINE Y The original command line that invoked the Command Processor.
CommonProgramFiles C:\Program Files\Common Files
COMMONPROGRAMFILES(x86) C:\Program Files (x86)\Common Files
COMPUTERNAME
COMSPEC C:\Windows\System32\cmd.exe or if running a 32 bit WOW — C:\Windows\SysWOW64\cmd.exe
DATE Y The current date using same region specific format as DATE.
ERRORLEVEL Y The current ERRORLEVEL value, automatically set when a program exits.
FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING
Internet Explorer
Default
These are undocumented variables for the Edge browser in Windows 10. HighestNumaNodeNumber Y (hidden) The highest NUMA node number on this computer. HOMEDRIVE Y C: HOMEPATH Y \Users\ LOCALAPPDATA C:\Users\ \AppData\Local LOGONSERVER \\ NUMBER_OF_PROCESSORS Y The Number of processors running on the machine. OS Y Operating system on the user’s workstation. PATH User and
System C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem; PATHEXT .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC
Determine the default executable file extensions to search for and use, and in which order, left to right.
The syntax is like the PATH variable — semicolon separators. PROCESSOR_ARCHITECTURE Y AMD64/IA64/x86 This doesn’t tell you the architecture of the processor but only of the current process, so it returns «x86» for a 32 bit WOW process running on 64 bit Windows. See detecting OS 32/64 bit PROCESSOR_ARCHITEW6432 = %PROCESSOR_ARCHITECTURE% (but only available to 64 bit processes) PROCESSOR_IDENTIFIER Y Processor ID of the user’s workstation. PROCESSOR_LEVEL Y Processor level of the user’s workstation. PROCESSOR_REVISION Y Processor version of the user’s workstation. ProgramW6432 = %ProgramFiles% (but only available when running under a 64 bit OS) ProgramData C:\ProgramData ProgramFiles C:\Program Files or C:\Program Files (x86) ProgramFiles(x86) 1 C:\Program Files (x86) (but only available when running under a 64 bit OS) PROMPT Code for current command prompt format,usually $P$G
C:> PSModulePath %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\ Public C:\Users\Public RANDOM Y A random integer number, anything from 0 to 32,767 (inclusive). %SessionName% Terminal servers only — for a terminal server session, SessionName is a combination of the connection name, followed by #SessionNumber. For a console session, SessionName returns «Console». SYSTEMDRIVE C: SYSTEMROOT By default, Windows is installed to C:\Windows but there’s no guarantee of that, Windows can be installed to a different folder, or a different drive letter.
systemroot is a read-only system variable that will resolve to the correct location.
Defaults in early Windows versions are C:\WINNT, C:\WINNT35 and C:\WTSRV TEMP and TMP User Variable C:\Users\ \AppData\Local\Temp
Under XP this was \ \Local Settings\Temp TIME Y The current time using same format as TIME. UserDnsDomain Y
User Variable Set if a user is a logged on to a domain and returns the fully qualified DNS domain that the currently logged on user’s account belongs to. USERDOMAIN USERDOMAIN_roamingprofile The user domain for RDS or standard roaming profile paths. Windows 8/10/2012 (or Windows 7/2008 with Q2664408) USERNAME USERPROFILE %SystemDrive%\Users\
This is equivalent to the $HOME environment variable in Unix/Linux WINDIR

%windir% is a regular User variable and can be changed, which makes it less robust than %SystemRoot%
Set by default as windir=%SystemRoot%
%WinDir% pre-dates Windows NT, its use in many places has been replaced by the system variable: %SystemRoot%

1 Only on 64 bit systems, is used to store 32 bit programs.

Unless stated otherwise, all the variables above are System variables

Environment variables are stored in the registry:

User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

By default, files stored under Local Settings do not roam with a roaming profile.

Dynamic environment variables are read-only and are computed each time the variable is expanded. When all variables are listed with SET, these will not appear in the list. Do not attempt to directly SET a dynamic variable.

Shell variables

Variables for current shell session are created with the SET command and are available only to the current CMD shell. These are only stored in memory not the registry. Shell variables are destroyed when the current shell (CMD) exits.

Running the SET command with no options will display all shell variables but also all User and System environment variables.

If the SET command is used to modify the PATH, or if it is removed completely with PATH ; that will not affect any other programs or CMD sessions opened before or after the current one.

Undocumented Dynamic variables (read only)

%__APPDIR__% The directory path to the current application .exe, terminated with a trailing backslash. (Global) — discuss
%__CD__% The current directory, terminated with a trailing backslash. (Global)
%=C:% The current directory of the C: drive. ( See Raymond Chen’s explanation of this.)
%=D:% The current directory of the D: drive if drive D: has been accessed in the current CMD session.
%DPATH% Related to the (deprecated) DPATH command.
%=ExitCode% The most recent exit code returned by an external command, such as CMD /C EXIT n, converted to hex.
%=ExitCodeAscii% The most recent exit code returned by an external command, as ASCII. (Values 0-32 do not display because those map to ASCII control codes.)
%FIRMWARE_TYPE% The boot type of the system: Legacy, UEFI, Not implemented, Unknown Windows 8/2012.
%KEYS% Related to the (deprecated) KEYS command.
More detail on these undocumented variables can be found in this stackoverflow answer from Dave Benham.

Undocumented Dynamic variables (read/write)

%__COMPAT_LAYER% Set the ExecutionLevel to either RunAsInvoker (asInvoker), RunAsHighest (highestAvailable) or RunAsAdmin (requireAdministrator) for more see elevation and Q286705 / Application Compatibility Toolkit for other Compatibility Layers (colours,themes etc).

Pass variables between batch scripts

There are several ways to pass values between batch files, or between a batch file and the command line, see the CALL and SETLOCAL pages for full details.

A child process by default inherits a copy of all environment variables from its parent, this makes environment variables unsuitable for storing secret information such as API keys or user passwords, especially in rare occasions like crashes where a crash log will often include the full OS environment at the time of the crash. PowerShell/Get-Credential is a more secure approach.

If Command Extensions are disabled, the following dynamic variables will be not accessible:
%CD% %DATE% %TIME% %RANDOM% %ERRORLEVEL% %CMDEXTVERSION% %CMDCMDLINE% %HIGHESTNUMANODENUMBER%

“Men may be convinced, but they cannot be pleased against their will. But though taste is obstinate, it is very variable, and time often prevails when arguments have failed”

How the environment-building process works — Raymond Chen [MSFT].
PowerShell — Working with Environment variables.
User Shell Folders — Profile, Start Menu — Location of user profile folders.
Detecting 32 vs 64 bit Windows
CALL — Evaluate environment variables.
SET — View environment variables, set local variables.
SETX — Set environment variables.
Q100843 — The four types of environment variable.
Q286705 — Set compatibility variables in a batch file.
Q242557 — Registry Settings for Folder Redirection.
StackOverflow — Storing a Newline in a variable.

Пакет Windows: отформатированная дата в переменную

Как сохранить текущую дату в формате гггг-ММ-ДД в некоторую переменную в Windows .bat файл?

аналог оболочки Unix:

14 ответов:

вы можете получить текущую дату в локаль-агностический способ с помощью

затем вы можете извлечь отдельные части, используя строки:

другой способ, где вы получаете переменные, которые содержат отдельные части, было бы:

гораздо приятнее, чем возиться с подстроками, за счет загрязнения вашего пространства имен переменных.

Если вам нужно UTC вместо местного времени, команда более или менее то же самое:

Если вы хотите достичь этого с помощью стандартных команд MS-DOS в пакетном файле, то вы можете использовать:

Я уверен, что это может быть улучшено дальше, но это дает дату в 3 переменных для Дня (dd), месяца (мм) и года (гггг). Затем вы можете использовать их позже в своем пакетном скрипте по мере необходимости.

хотя я понимаю, что ответ был принят для этого вопроса, этот альтернативный метод может быть оценен многими, кто хочет достичь этого без используя консоль WMI, поэтому я надеюсь, что это добавляет некоторую ценность этому вопросу.

используйте date / T, чтобы найти формат в командной строке.

если формат даты «Чт 03/03/2016» использовать следующим образом:

еще два способа, которые не зависят от настроек времени (взято из Как получить данные/время независимо от локализации). И как же сделать день недели, и ни один из них не требует разрешения администратора!:

MAKECAB — будет работать на каждой системе Windows (быстро, но создает небольшой временный файл) (скрипт foxidrive):

ROBOCOPY — это не родная команда для Windows XP и Windows Server 2003, но это может быть загружено с сайта Microsoft. Но он встроен во все, начиная с Windows Vista и выше:

и еще три способа, которые используют другие языки сценариев Windows. Они дадут вам больше гибкости, например, вы можете получить неделю в году, времени в миллисекундах и так далее.

JScript / BATCH гибрид (нужно сохранить как .bat ). JScript доступен на каждой системе от Windows NT и выше, в составе Windows Script Host (хотя можно отключить через реестр это редкий случай):

VBScript / BATCH гибридный (можно ли внедрить и выполнить VBScript в пакетном файле без использования временного файла?) тот же случай , что и jscript, но гибридизация не является так идеально:

PowerShell — может быть установлен на каждой машине, которая имеет .NET-скачать с Microsoft ( v1, v2 и v3 (только для Windows 7 и выше)). По умолчанию устанавливается на все формы Windows 7/Win2008 и выше:

составлена самостоятельно jscript.net/batch (я никогда не видел Windows-машины без .Инет так я думаю, что это это довольно портативный):

Логман это не может получить год и день недели. Он сравнительно медленный, также создает временный файл и основан на отметках времени, которые logman помещает в свои файлы журналов.Будет работать все, от Windows XP и выше. Вероятно, он никогда не будет использоваться никем-включая меня-но это еще один способ.

просто использовать %date% переменной:

Мне очень понравился метод Джоуи, но я решил немного расширить его.

в этом подходе вы можете запускать код несколько раз и не беспокоиться о том, что старое значение даты «прилипает», потому что оно уже определено.

каждый раз, когда вы запускаете этот пакетный файл, он будет выводить совместимое с ISO 8601 комбинированное представление даты и времени.

в этой версии вам нужно будет быть осторожным, чтобы не копировать/вставлять один и тот же код в несколько мест файл, потому что это приведет к дублированию меток. Вы можете либо иметь отдельную метку для каждой копии, либо просто поместить этот код в свой собственный пакетный файл и вызвать его из исходного файла, где это необходимо.

Я устанавливаю переменную окружения в значение в числовом формате, желаемом, делая это:

в соответствии с ответом @ProVi просто изменить в соответствии с требуемым форматированием

EDIT Согласно комментарию @Jeb, который является правильным, приведенный выше формат времени будет работать только в том случае, если ваша команда DATE /T возвращает

его легко редактировать в соответствии с вашим языком, однако, используя индексацию каждого символа в строке, возвращаемой соответствующей переменной окружения %DATE%, вы можете извлечь части строки тебе нужно.

например. Использование %DATE

10,4% расширит переменную среды DATE, а затем использует только 4 символа, которые начинаются с 11-го (смещение 10) символа расширенного результата

например, если вы используете даты в стиле US, то применяется следующее

из-за даты и времени формат-это информация о местоположении, получение их из переменных %date% и %time% потребует дополнительных усилий для анализа строки с преобразованием формата в рассмотрение. Хорошая идея-использовать некоторый API для извлечения структуры данных и анализа, как вы хотите. WMIC-это хороший выбор. Ниже пример использования Win32_LocalTime. Вы также можете использовать Win32_CurrentTime или Win32_UTCTime.

можно использовать PowerShell и перенаправить его вывод в переменную среды с помощью цикла.

из командной строки ( cmd ):

в пакетном файле вы можете избежать %a как %%a :

Если у Вас установлен Python, вы можете сделать

вы можете легко адаптировать строку формата к вашим потребностям.

Если вы не возражаете против одноразовых инвестиций от 10 до 30 минут, чтобы получить надежное решение (которое не зависит от настроек региона Windows), пожалуйста, читайте дальше.

давайте освободим наши умы. Вы хотите упростить сценарии, чтобы просто выглядеть так? (Предположим, вы хотите установить переменную LOG_DATETIME)

Читайте также:  Драйвер для ноутбука lenovo g500 для windows 10
Оцените статью