Powershell + 7zip批量提取并重命名-收到“无文件可处理”消息

时间:2019-05-16 15:24:16

标签: powershell 7zip powershell-v6.0

已编辑:

最初,我的问题是为什么第一段代码不起作用。如果我在循环外的单个文件上单独运行它,则解压缩操作将起作用。但是一旦我用循环将其包裹起来,它将无法正常工作,也不会出现红色错误。

Thansk @nemze,他/她的回答启发了我将我的代码从以下位置更改:

customLambda

收件人:

$7ZipPath = "C:\7z\7za"
$zipFolderRoot = "Z:\long folder path\Test Folder\Unzip Test"
$zipOutPath = "Z:\long folder path\Test Folder\Unzip Test\Unzip"
$zipFilePassword = "TEST123"
ls -Path $zipFolderRoot -directory -Exclude Unzip

Foreach ($zipFolderChild in (ls -Path $zipFolderRoot -directory -Exclude Unzip))
{
$zipFile = '"$zipFolderChild"+"\"+"Data.zip"'
$command = "& $7ZipPath x -o'$zipOutPath' -y -p$zipFilePassword $zipFile"
iex $command
#file rename command that I have not written yet
}

通过将$7ZipPath = "C:\7z\7za" $zipFolderRoot = "Z:\long folder path\Test Folder\Unzip Test" $zipOutPath = "Z:\long folder path\Test Folder\Unzip Test\Unzip" $zipFilePassword = "TEST123" ls -Path $zipFolderRoot -directory -Exclude Unzip Foreach ($zipFolderChild in (ls -Path $zipFolderRoot -directory -Exclude Unzip)) { $zipFile = "$zipFolderChild"+"\"+"Data.zip" $command = "& $7ZipPath x -o'$zipOutPath' -y -p$zipFilePassword ""$zipFile""" iex $command #file rename command that I have not written yet } 定义移到$zipFile循环之外,就可以了!

我认为我的第二个障碍现在是将文件重命名为循环文件。

我要达到的目标:

  • 将20181001文件夹中的Data.xls重命名为20181001.xls
  • 将20181008文件夹中的Data.xls重命名为20181008.xls

修改后的代码仍在读取ForEach作为完整路径,我该如何仅提取文件夹名称

EDIT3:

尝试使重命名语句进入循环,但不确定如何使$zipFolderChild参数起作用,-NewName clear不起作用。还尝试过:

$zipFolderChild.Name.xls

在循环内部,也不起作用。

最终工作:

$folder= $zipFolderChild.Name
#file rename command that I have not written yet
$rename = "-path", "$zipOutPath\Data.xls" ,"-NewName", "$folder.xls"
& Rename-Item @rename

2 个答案:

答案 0 :(得分:1)

这样做更好吗?

& $7ZipPath x -o$zipOutPath -y -p$zipFilePassword $zipFile

$ zipFile将不会获得带单引号的变量:

 $zipFile = "$zipFolderChild" + "\" + "Data.zip"

答案 1 :(得分:1)

这对我有用:

$7ZipPath = "C:\7z\7za"
$zipFolderRoot = "Z:\long folder path\Test Folder\Unzip Test"
$zipOutPath = "Z:\long folder path\Test Folder\Unzip Test\Unzip"
$zipFilePassword = "TEST123"

Get-ChildItem -Path $zipFolderRoot -Exclude Unzip -Directory

Foreach ($zipFolderChild in (Get-ChildItem -Path $zipFolderRoot -Exclude Unzip))
{
    $zipFile = "$zipFolderChild\Data.zip" 
    $command = "x", "$zipFile", "-p$zipFilePassword", "-y", "-o$zipOutPath"
    & $7ZipPath @command
    #file rename command that I have not written yet
}

我将splatting用作$command

编辑:OP第二个问题的一些示例。

尝试两个示例,看看会发生什么。

第一:

$i = 0
Foreach ($zipFolderChild in (Get-ChildItem -Path $zipFolderRoot -Exclude Unzip))
{
    $zipFolderChild.name
    Write-Output "step"
}

第二:

$i = 0
$folder = Get-ChildItem -Path $zipFolderRoot -Exclude Unzip
Foreach ($zipFolderChild in $folder)
{      
    $folder[$i].name
    Write-Output $i
    $i++
}