Powershell-使用[io.compression.zipfile]时出错:CreateFromDirectory

Powershell-使用[io.compression.zipfile]时出错:CreateFromDirectory,powershell,Powershell,我想使用powershell使用目录的内容创建一个.zip文件,我使用绝对路径名取得了一些成功,但是现在我尝试切换到相对路径,我在尝试创建.zip文件时收到一个错误 在脚本的主体中,我使用设置脚本所在目录的路径 $scrPath = Split-Path $myInvocation.MyCommand.Path Set-Location $scrPath 然后我将初始化2个变量以存储相对路径,然后将这些变量用作参数: $timeStamp = (get-date).ToString("ddMM

我想使用powershell使用目录的内容创建一个.zip文件,我使用绝对路径名取得了一些成功,但是现在我尝试切换到相对路径,我在尝试创建.zip文件时收到一个错误

在脚本的主体中,我使用设置脚本所在目录的路径

$scrPath = Split-Path $myInvocation.MyCommand.Path
Set-Location $scrPath
然后我将初始化2个变量以存储相对路径,然后将这些变量用作参数:

$timeStamp = (get-date).ToString("ddMMyyyy")
$files_in = "..\Current\CustomerName\Temp\"
$file_out = "..\Current\CustomerName\" + $timeStamp + ".zip"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipFile]::CreateFromDirectory($files_in, $file_out)
$files\u in变量工作正常,可以找到我要查找的文件,但是系统对$file\u out变量做了一些奇怪的操作,没有找到正确的输出路径

我看到的错误是:

使用“2”参数调用“CreateFromDirectory”时出现异常:“可能” 找不到路径的一部分 'C:\Users\Current\CustomerName\fileName.zip'


按照我设置$file\u out变量的方式,我希望它输出到C:\Users\My.Username\Desktop\MyProject\Current\CustomerName\fileName.zip,但它省略了路径的\My.Username\Desktop\MyProject部分-为什么?

当您为.NET方法提供非绝对路径时,它是相对于pro的工作目录解析的cess(您从中启动的目录)-一个不受设置位置影响的值

您可以使用
解析路径
相对于提示符的当前位置解析它:

$file_out = Join-Path -Path (Resolve-Path '..\Current\CustomerName\').Path -ChildPath "timestamp.zip"

[io.compression.zipFile]::CreateFromDirectory($ExecutionContext.SessionState.Path.GetUnsolvedProviderPathFrompPath($files\u-in),$ExecutionContext.SessionState.Path.GetUnsolvedProviderPathFrompPath($file\u-out))
@PetSerAl不应该是
GetResolvedSpathFrompPath($file\u-out)
?@MathiasR.Jessen
已解决
在路径不存在时引发异常。我假设目标zip文件还不存在。
CreateFromDirectory
无法处理
PSPath
之类的
DriveName:\Some\path
,因此必须将其转换为提供程序路径。