Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell在windows和unix中正确生成文件路径_Windows_Powershell_Unix - Fatal编程技术网

Powershell在windows和unix中正确生成文件路径

Powershell在windows和unix中正确生成文件路径,windows,powershell,unix,Windows,Powershell,Unix,我想为powershell脚本中的文件路径生成字符串。我希望它在windows和mac中都能工作 目前,代码被硬编码到类似windows的路径(“\”->windows“/”->unix): $templatep=“$CoreRoot\templates\$serviceName” 我将此更改为: $templatep=加入路径$CoreRoot“模板”$serviceName 它可以在mac和Powershell 6.0中运行。但它在我的windows服务器上无法使用Powershel

我想为powershell脚本中的文件路径生成字符串。我希望它在windows和mac中都能工作

目前,代码被硬编码到类似windows的路径(“\”->windows“/”->unix):

$templatep=“$CoreRoot\templates\$serviceName”

我将此更改为:

$templatep=加入路径$CoreRoot“模板”$serviceName
它可以在mac和Powershell 6.0中运行。但它在我的windows服务器上无法使用Powershell 4。我必须这样做:


$templatep=连接路径$CoreRoot-ChildPath“模板”|连接路径-ChildPath$serviceName

你知道为什么这在我的mac电脑里工作吗?这是powershell 5或6中的新功能吗? 我不喜欢用管道连接多个连接路径。有更好的方法吗


谢谢

首先,使用.NET framework的解决方案:

[IO.Path]::Combine('a', 'b', 'c')
这将在Unix上生成
a/b/c
,在Windows上生成
a\b\c
,并方便地支持任意数量的路径组件

注:

  • 此解决方法仅适用于文件系统路径,而
    连接路径
    设计用于任何PowerShell驱动器提供程序的路径

  • 确保除第一个组件外,没有其他组件以
    \
    (Windows)或
    /
    (Unix)开头,因为前面的任何组件都会被忽略;e、 例如,在Windows上:
    [IO.Path]::合并('\a','\b',c')#->'\b\c'-'\a'被忽略(!)

    请注意,
    连接路径
    不显示此行为;详情见我的

作为使用管道对
连接路径
调用进行排序的替代方法,您只需使用
(…)
(子表达式):


自Windows PowerShell版本5.1.14393.693起,
Join Path-?
显示的语法(附带参数省略):

正是附加的
-AdditionalChildPath
参数
,其声明方式收集了所有剩余的位置参数(
ValueFromRemainingArguments
),使得指定任意数量的子组件起作用,例如,
连接路径a b c
确实有效

不幸的是,这项功能增强了Windows PowerShell

请注意,尽管
[-Path]
是一个数组参数,但其目的不是接受单个输出路径的多个子路径组件,而是允许多个父子路径对的连接;e、 g:

$ Join-Path a,b c  # same as: Join-Path -Path a,b -ChildPath c
a\c
b\c

最后,即使这可能不可取,您也可以在两种平台上使用硬编码
/
作为路径分隔符,因为许多Windows API函数以及PowerShell自己的cmdlet可以互换地接受
\
/

然而,并不是所有的实用程序都会以这种方式运行,所以通常使用适合平台的分隔符更安全

例如,以下功能在Windows上运行良好:

Get-Item c:/windows/system32 # same as: Get-Item c:\windows\system32

据我所知,通过PowerShell 5.0,
连接路径
只能采用两条路径。通过管道连接到另一个联接或使用.Net的
[io.path]::combine()
方法是我知道的两种解决方法。
Join-Path [-Path] <String[]> [-ChildPath] <String> [[-AdditionalChildPath] <String[]>]
$ Join-Path a,b c  # same as: Join-Path -Path a,b -ChildPath c
a\c
b\c
Get-Item c:/windows/system32 # same as: Get-Item c:\windows\system32