【问题标题】:Why are my zip files saving in system32 instead of the directory Im currently in?为什么我的 zip 文件保存在 system32 而不是我当前所在的目录中?
【发布时间】:2023-03-23 20:36:01
【问题描述】:

我目前有一个脚本,它将从我所在的目录中获取文件,将它们复制到同一目录中的文件夹中,然后将其压缩到 example.zip -- 唯一的问题是当我尝试压缩它们时使用:

Add-Type -AssemblyName System.IO.Compression.FileSystem
function ZipFiles( $zipfilename, $sourcedir )
{
  # Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}

该 zip 文件 $zipfilename 保存到 C:\Windows\system32 而不是我目前所在的 C:\myDir\env\filesToZip。知道为什么会发生这种情况,而不是在我执行 PowerShell 脚本的目录中创建 zip 文件吗?

【问题讨论】:

  • PowerShell 当前位置与进程工作目录不同。 related

标签: windows powershell command-line


【解决方案1】:

作为PetSerAl hints at,.NET 方法在解析相对路径名时将默认为进程(不一定是powershell)的当前工作目录。

使用Resolve-Path在powershell中使用当前位置解析路径:

function ZipFiles( $zipfilename, $sourcedir )
{
  $sourcepath = Resolve-Path $sourcedir
  if($sourcepath.Provider -ne 'FileSystem'){
    throw 'File system path expected for $sourcedir'
  }

  $destinationpath = Resolve-Path $zipfilename
  if($destinationpath.Provider -ne 'FileSystem'){
    throw 'File system path expected for $zipfilename'
  }

  $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
  [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcepath.ProviderPath, $destinationpath.ProviderPath, $compressionLevel, $false)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多