Я собрал билет в службу поддержки Mailgun, и Марко ответил решением, которым я поделился:
$inline = curl_file_create(realpath('../includes/images/logo_sml.png'));
...
'inline' => $inline,
curl_file_create - Создает объект файла CURL для прикрепления изображения. , Остальная часть кода не изменилась.
Ответ Бернхарда потребовал некоторой доработки для меня, потому что переменная среды% DATE% является в другом формате (как прокомментировано в другом месте). Также отсутствовала тильда (~).
Вместо:
установите backupFilename =% DATE: ~ 6,
Это будет работать для формата даты, отличного от американского ( дд / ММ / гггг
):
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
7z a QuickBackup%backupFilename%.zip *.backup
Sure.
FOR %%A IN (%Date:/=%) DO SET Today=%%A
7z a QuickBackup%TODAY%.zip *.backup
That is DDMMYYYY format.
Here's YYYYDDMM:
FOR %%A IN (%Date%) DO (
FOR /F "tokens=1-3 delims=/-" %%B in ("%%~A") DO (
SET Today=%%D%%B%%C
)
)
7z a QuickBackup%TODAY%.zip *.backup
I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19
Here's the code from that site:
::~~Author~~. Brett Middleton
::~~Email_Address~~. brettm@arches.uga.edu
::~~Script_Type~~. nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables
::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command. These variables can be used to name files, control the flow of execution, etc.
::~~Script~~.
@echo off
::-----------------------------------------------------------------------------
:: SetEnvDate1.CMD 6/30/98
::-----------------------------------------------------------------------------
:: Description : Sets or clears a group of environment variables containing
:: : components of the current date extracted from the string
:: : returned by the DATE /T command. These variables can be
:: : used to name files, control the flow of execution, etc.
:: :
:: Requires : Windows NT with command extensions enabled
:: :
:: Tested : Yes, as demonstration
:: :
:: Contact : Brett Middleton <brettm@arches.uga.edu>
:: : Animal and Dairy Science Department
:: : University of Georgia, Athens
::-----------------------------------------------------------------------------
:: USAGE
::
:: SetEnvDate1 can be used as a model for coding date/time routines in
:: other scripts, or can be used by itself as a utility that is called
:: from other scripts.
::
:: Run or call SetEnvDate1 without arguments to set the date variables.
:: Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
:: day number (DT_DD) and four-digit year (DT_YYYY).
::
:: When the variables are no longer needed, clean up the environment by
:: calling the script again with the CLEAR argument. E.g.,
::
:: call SetEnvDate1 clear
::-----------------------------------------------------------------------------
:: NOTES
::
:: A time variable could be added by parsing the string returned by the
:: built-in TIME /T command. This is left as an exercise for the reader. B-)
::
:: This script illustrates the following NT command extensions:
::
:: 1. Use of the extended IF command to do case-insensitive comparisons.
::
:: 2. Use of the extended DATE command.
::
:: 3. Use of the extended FOR command to parse a string returned by a
:: command or program.
::
:: 4. Use of the "()" conditional processing symbols to group commands
:: for conditional execution. All commands between the parens will
:: be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------
if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit
::-----------------------------------------------------------------------------
:: Check arguments and select SET or CLEAR routine. Unrecognized arguments
:: are ignored and SET is assumed.
::-----------------------------------------------------------------------------
:chkarg
if /I "%1" == "CLEAR" goto clrvar
goto setvar
::-----------------------------------------------------------------------------
:: Set variables for the day abbreviation (DAY), month number (MM),
:: day number (DD) and 4-digit year (YYYY).
::-----------------------------------------------------------------------------
:setvar
for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)
goto endit
::-----------------------------------------------------------------------------
:: Clear all variables from the environment.
::-----------------------------------------------------------------------------
:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit
:endit
Если вы знаете, что ваши региональные настройки не изменятся, вы можете сделать это следующим образом:
, если ваш краткий формат даты - дд / ММ / гггг:
SET MYDATE =% DATE: ~ 3,2 %% DATE: ~ 0,2 %% DATE: ~ 8,4%
если ваш краткий формат даты: ММ / дд / гггг:
SET MYDATE =% DATE: ~ 0,2 %% DATE: ~ 3,2 %% DATE: ~ 8,4%
Но общего способа сделать нет это не зависит от ваших региональных настроек.
Я бы не рекомендовал полагаться на региональные настройки для всего, что будет использоваться в производственной среде. Вместо этого вам следует рассмотреть возможность использования другого языка сценариев - PowerShell, VBScript, ...
Например, если вы создаете файл VBS yyyymmdd.vbs в том же каталоге, что и ваш пакетный файл, со следующим содержимым:
Я нашел два способа, которые работают независимо от настроек даты.
На моем компьютере date / t возвращает 2009-05-27
Вы можете получить доступ к реестру и прочитать региональные настройки (HKEY_CURRENT_USER \ Control Panel \ International)
Или используйте vbscript. Это уродливый гибрид командного файла и vbscript, который я создал некоторое время назад ....
@Echo Off
set rnd=%Random%
set randfilename=x%rnd%.vbs
::create temp vbscript file
Echo Dim DayofWeek(7) > %temp%\%randfilename%
Echo DayofWeek(1)="Sun" >> %temp%\%randfilename%
Echo DayofWeek(2)="Mon" >> %temp%\%randfilename%
Echo DayofWeek(3)="Tue" >> %temp%\%randfilename%
Echo DayofWeek(4)="Wed" >> %temp%\%randfilename%
Echo DayofWeek(5)="Thu" >> %temp%\%randfilename%
Echo DayofWeek(6)="Fri" >> %temp%\%randfilename%
Echo DayofWeek(7)="Sat" >> %temp%\%randfilename%
Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename%
Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename%
Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename%
Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " " _ >> %temp%\%randfilename%
Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename%
Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename%
Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2) >> %temp%\%randfilename%
::set the output into vars
if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F
set year=%y2kyear:~2,2%
::cleanup
del %temp%\%randfilename%
Это некрасиво, но работает.
Здесь доступен технический рецепт , который показывает, как отформатировать его в MMDDYYYY, вы сможете адаптировать его для своих нужд.
echo on
@REM Seamonkey’s quick date batch (MMDDYYYY format)
@REM Setups %date variable
@REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
echo %date%
EDIT: Причина раньше не работал из-за «умных цитат» в исходном тексте. Я исправил их, и командный файл будет работать, если вырезать и вставить его с этой страницы.
Вы также можете получить доступ к дате через переменную % DATE%
При тестировании моей системы % DATE%
выдает ddd dd / mm / yyyy
вы можете использовать операторы подстроки для создания желаемого формата
, т.е. выполнение следующей команды в MON 11/12/2018 с региональными настройками США
%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%
приведет к выводу:
11 Mon 12
аргументы подстроки -
% * переменная *: ~ * startpos *, * numberofchars *%
Как уже отмечалось, анализ даты и времени полезен только в том случае, если вы знаете формат, используемый текущим пользователем (например, MM / dd / yy или дд-ММ-гггг, просто чтобы назвать 2). Это можно определить, но к тому времени, когда вы выполните всю нагрузку и синтаксический анализ, вы все равно столкнетесь с ситуацией, когда используется неожиданный формат, и потребуются дополнительные настройки.
Вы также можете использовать некоторую внешнюю программу, которая будет возвращать метку даты в предпочитаемом вами формате, но у нее есть недостатки, связанные с необходимостью распространять служебную программу с вашим скриптом / пакетом.
есть также пакетные приемы с использованием CMOS-часов в довольно сырой форме, но для большинства людей это слишком близко к оголенным проводам, а также не всегда является предпочтительным местом для получения даты / времени.
Ниже приводится решение, позволяющее избежать вышеуказанных проблем. Да, это вызывает некоторые другие проблемы, но для моих целей я обнаружил, что это самое простое, ясное и портативное решение для создания отметки даты в файлах .bat для современных систем Windows. Это всего лишь пример, но я думаю, вы увидите, как изменить другие форматы даты и / или времени и т. Д.
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM the following may be needed to be sure cache is clear before using the new setting
reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f