【问题标题】:Multiple variables in path路径中的多个变量
【发布时间】:2018-12-14 22:38:14
【问题描述】:

我计划使用以下脚本循环遍历文本文件来设置源 PDF 位置的变量,并指定创建新文件夹(带有周数)以将源 PDF 移动到的路径。

$pdfSource = 'C:\path\in\text\file'
$newFolder = 'C:\path\to\newfolder\in\text\file'
Get-ChildItem $pdfSource '*.pdf' -Recurse | foreach {
    $x = $_.LastWriteTime.ToShortDateString()
    $new_folder_name = Get-Date $x -UFormat %V
    $des_path = "C:\path\to\newfolder\$new_folder_name"

    if (Test-Path $des_path) {
        Move-Item $_.FullName $des_path
    } else {
        New-Item -ItemType Directory -Path $des_path
        Move-Item $_.FullName $des_path
    }
}

我似乎无法弄清楚下面一行的语法,以包含$newFolder 路径变量以及我正在创建的现有$new_folder_name

$des_path = "C:\path\to\newfolder\$new_folder_name"

【问题讨论】:

  • 您是否在寻找Join-Path cmdlet?例如$des_path = Join-Path $newFolder $new_folder_name

标签: powershell


【解决方案1】:

选项一:

$des_path = "${newFolder}\${new_folder_name}"

选项2:

$des_path = "${0}\${1}" -f $newFolder, $new_folder_name

选项 3:

$des_path = $newFolder + $new_folder_name

选项 4:

$des_path = Join-Path -Path $newFolder -ChildPath $new_folder_name

【讨论】:

    【解决方案2】:

    您的字符串扩展(插值)方法没有问题:

    $new_folder_name = 'foo' # sample value
    $des_path = "C:\path\to\newfolder\$new_folder_name" # use string expansion
    

    按预期生成字符串文字 C:\path\to\newfolder\foo

    Adam's answer 向您展示构建文件路径的替代方法Join-Path 是最强大且最符合 PowerShell 的习惯,尽管速度很慢。
    另一种选择是使用[IO.Path]::Combine()

    [IO.Path]::Combine('C:\path\to\newfolder', $new_folder_name)
    

    如果您当前的文化不是en-US(美国英语),那么您计算$new_folder_name 值的方式应该是有问题的,但由于错误实际上不是 [1];无论哪种方式,都应该简化:

    代替:

    $x = $_.LastWriteTime.ToShortDateString()
    $new_folder_name = Get-Date $x -uformat %V
    

    使用:

    $new_folder_name = Get-Date $_.LastWriteTime -uformat %V
    

    也就是说,将$_.LastWriteTime 直接 传递给Get-Date,作为[datetime] 实例 - 无需通过字符串表示 绕道。


    [1] .ToShortDateString() 返回一个culture-sensitive 字符串表示,而PowerShell 通常使用invariant 文化来确保跨文化的一致性;因此,如果您将 string 传递给接受 [datetime] 实例的参数,则应该(仅)识别 invariant 文化的格式,而不是 当前文化。虽然对于用 PowerShell 编写的 函数 确实如此,但在 编译的 cmdlet(通常基于 C#)中,current文化被意外应用;虽然这是一个错误,但为了向后兼容,决定不修复它 - 请参阅this GitHub issue

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 2020-10-02
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多