如何使用 Join-Path 将两个以上的字符串组合成一个文件路径? [英] How do I use Join-Path to combine more than two strings into a file path?

查看:31
本文介绍了如何使用 Join-Path 将两个以上的字符串组合成一个文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想将两个字符串组合成一个文件路径,我使用 Join-Path 像这样:

If I want to combine two strings into a file path, I use Join-Path like this:

$path = Join-Path C: "Program Files"
Write-Host $path

打印"C:\Program Files".如果我想对两个以上的字符串执行此操作:

That prints "C:\Program Files". If I want to do this for more than two strings though:

$path = Join-Path C: "Program Files" "Microsoft Office"
Write-Host $path

PowerShell 抛出错误:

PowerShell throws an error:

Join-Path:找不到接受参数Microsoft Office"的位置参数.
在 D:\users\ma\my_script.ps1:1 字符:18
+ $path = 加入路径 <<<<C:程序文件"Microsoft Office"
+ CategoryInfo : InvalidArgument: (:) [Join-Path], ParameterBindingException
+ FullQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
.Commands.JoinPathCommand

Join-Path : A positional parameter cannot be found that accepts argument 'Microsoft Office'.
At D:\users\ma\my_script.ps1:1 char:18
+ $path = join-path <<<< C: "Program Files" "Microsoft Office"
+ CategoryInfo : InvalidArgument: (:) [Join-Path], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
.Commands.JoinPathCommand

我尝试使用字符串数组:

I tried using a string array:

[string[]] $pieces = "C:", "Program Files", "Microsoft Office"
$path = Join-Path $pieces
Write-Host $path

但是 PowerShell 提示我输入 childpath(因为我没有指定 -childpath 参数),例如"somepath",然后创建三个文件路径,

But PowerShell prompts me to enter the childpath (since I didn't specify the -childpath argument), e.g. "somepath", and then creates three files paths,

C:\somepath
Program Files\somepath
Microsoft Office\somepath

这也不对.

推荐答案

您可以使用 .NET 路径类:

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')

这篇关于如何使用 Join-Path 将两个以上的字符串组合成一个文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆