在Powershell中串联变量


9

我正在尝试在Powershell中连接两个变量以形成完整的文件路径和文件名以保存文本文件。

我有两个变量

  • $ Log_path和
  • $ Log_name

我正在尝试在这段代码中将两个变量结合在一起:

$ objWorkbook = $ objExcel.Workbooks.Open $ Log_path“ \ $ Log_name”

我找不到正确的功能组合?

还需要在Log_path和Log_name变量之间添加“ \”,以正确格式化文件路径。

Answers:


5

您可以使用Join-Path,它将为您放置目录斜杠。

$objWorkbook = $objExcel.Workbooks.Open (Join-Path $Log_path $Log_name)

如果$ Log_Path父级已经有斜杠,它将处理逻辑。

>join-path c:\temp test.txt
c:\temp\test.txt

>join-path c:\temp\ text.txt
c:\temp\test.txt

12
$path = "C:\folder"
$name = "file.exe"
$fullname = $path + "\" + $name
$fullname

(要么)

$fullname = "$path\$name"

但不是

$fullname = '$path\$name'

输出量

C:\ folder \ file.exe

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.