使用格式运算符构造路径会引发类型错误

Constructing a path with the format operator throws a type error

我正在尝试使用 PowerShell 的内置 -f 功能,但我总是遇到

错误

Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Filter'. Specified method is not supported.

这是我的代码,我做错了什么才能做我想做的事?

$beefcakes = @('Homeboy', 'Coldfry', 'Redpearl')
foreach ($bf in $beefcakes) {
  $HomeDir = "C:\Testing\"
  $DestPath = "$HomeDir$bf\"
  switch ($bf) {
    Homeboy  { $redfern = "1234" }
    Coldfry  { $redfern = "888" }
    Redpearl { $redfern = "0011" }
  }

  if (Test-Path '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf) {
    $savefile = '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf
  } else {
    $savefile = '{0}\{1}_{2}_Redo.csv' -f $DestPath, $redfern, $bf
  }
}

您需要将格式化表达式放在子表达式中或将其分配给变量,否则 PowerShell 会将 -f 解释为 Test-Path 的缩写参数 -Filter,这需要字符串参数,而不是对象数组。

Test-Path       '{0}\{1}_{2}.csv' -f      $DestPath, $redfern, $bf
    ⇕                  ⇕           ⇕                 ⇕
Test-Path -Path '{0}\{1}_{2}.csv' -Filter $DestPath, $redfern, $bf

改变这个:

if (Test-Path '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf) {
  $savefile = '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf
} else {
  $savefile = '{0}\{1}_{2}_Redo.csv' -f $DestPath, $redfern, $bf
}

进入这个:

if (Test-Path ('{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf)) {
  $savefile = '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf
} else {
  $savefile = '{0}\{1}_{2}_Redo.csv' -f $DestPath, $redfern, $bf
}

或(更好)这个:

$savefile = '{0}\{1}_{2}.csv' -f $DestPath, $redfern, $bf
if (-not (Test-Path $savefile)) {
  $savefile = '{0}\{1}_{2}_Redo.csv' -f $DestPath, $redfern, $bf
}

一般来说,最好避免在循环内重复分配静态值 ($HomeDir),使用 Join-Path cmdlet 构建路径(保存你不得不管理反斜杠的头痛)。您在这里甚至不需要格式运算符。只需将您的变量放在双引号字符串中。

$HomeDir = 'C:\Testing'
foreach ($bf in $beefcakes) {
  $DestPath = Join-Path $HomeDir $bf
  ...
  $basename = "${redfern}_${bf}"
  $savefile = Join-Path $DestPath "$basename.csv"
  if (-not (Test-Path $savefile)) {
    $savefile = Join-Path $DestPath "${basename}_Redo.csv"
  }
}