【问题标题】:How to include variable in a path?如何在路径中包含变量?
【发布时间】:2019-10-18 04:09:08
【问题描述】:

我正在尝试创建一个名为 creation_DDMMYYYY 的文件,其中 DDMMYYYY 是当前日期。我在路径上遇到了不正确的路径格式错误。

$nowDate=$(date)
New-Item -ItemType file "$HOME/creation_$nowDate.txt" 

因为我刚开始使用 Powershell,我真的不知道这里有什么问题......

【问题讨论】:

  • PoSh 无法判断 .txt 是文件名的一部分。它认为您在谈论 $nowDate.txt [具有属性的对象],而不是 ($nowDate).txt ... [grin]
  • 这很有意义。但是New-Item -ItemType file "$HOME/creation_($nowDate).txt" 仍然输出相同的错误。
  • 我总是使用国际化的可排序格式ni ("creation_{0:yyyyMMdd}.txt" -f (get-date))
  • @AdrianDanlos - 啊! [blush] 我没有注意到您没有定义日期格式。您似乎正在使用 datetime 对象 - 这在这样的字符串中不起作用。看看 LotPings 发布的内容。看起来它解决了你的问题。
  • "$nowDate" 可能包含文件系统名称中不允许的字符,例如 /:。使用类似$($nowDate.ToString('yyyy-MM-dd'))

标签: shell powershell path


【解决方案1】:

因为您在nowDate 中只使用了$date,所以路径不正确,因为它包含空格(文件夹名称不能带有空格)并且完全不是您想要的格式。

只需更改nowDate 即可获得正确的日期格式,它将起作用:

$nowDate = Get-Date -Format ddMMyyyy
New-Item -ItemType file "$HOME/creation_$nowDate.txt"
# Result:
Folder Properties...        Name
                            ----
                            creation_02062019.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2022-07-10
    • 2011-05-19
    • 1970-01-01
    • 2015-06-20
    • 2014-02-17
    相关资源
    最近更新 更多