powershell从url下载xml-在url中添加了unix时间戳



我有一个简单的powershell skript,用于从url下载XML。

我需要在url中动态添加unix时间戳,并使用unix时间戳格式的实际日期。然后我需要用windows任务调度程序运行它。

powershell skript现在的代码:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri "https://xxxxx&from_date=1668069585" -OutFile "C:IMPORTxxx_$(get-date -Format yyyy_MM_dd_hh_mm_ss).xml"

如何在&从_日期?

感谢

在PowerShell v5.1及更高版本中,可以使用[datetimeoffset]类型的.ToUnixTimeSeconds()方法:

$uri = 'https://xxxxx&from_date=' + [datetimeoffset]::Now.ToUnixTimeSeconds()

注:

  • PowerShell本身提供Get-Date-UFormat %s,它以字符串的形式返回Unix时间戳,但此仅在PowerShell(Core)7+中正常工作(在Windows PowerShell中,时间戳错误地表示为自1970年1月1日午夜以来的秒数本地时间;此外,它意外地包含小数部分)

使用除现在以外的时间戳:

[datetime]一样,明确且更灵活的[datetimeoffset]具有各种.Add...()方法,允许您计算相对于另一个时间戳的所需时间戳;例如.AddDays():

# Get *yesterday's* Unix time, at the *same time of day*.
[datetimeoffset]::Now.AddDays(-1).ToUnixTimeSeconds()

如果您想使用一天的开始(午夜),例如昨天的:

# Get the previous *local calendar day's* Unix time, i.e.
# from the start of that day (midnight)
([datetimeoffset] [datetime]::Now.Date).AddDays(-1).ToUnixTimeSeconds()
  • 请注意,虽然[datetimeoffset]实例与[datetime]实例一样,具有返回不带时间组件的日期的.Date属性,但该日期是(a)[datetime]实例和(b)不明确,因为其.Kind属性值始终为Unspecified

更一般地说,给定任意[datetimeoffset]实例,您可以通过减去.TimeOfDay属性的值来消除一天中的时间分量,该属性相对于时间戳所表示的UTC偏移量(时区);例如,以下内容等同于以上内容:

(($dto = [datetimeoffset]::Now) - $dto.TimeOfDay).AddDays(-1).ToUnixTimeSeconds()

最新更新