【发布时间】:2021-12-02 18:28:24
【问题描述】:
我在我的脚本上取得了一些进展,该脚本会自动更新 excel 文件中的链接而无需打开它们。我已经成功地使该函数在单个文件上工作,并输入文件名和要替换的文本。现在我正在尝试扩展它,以便它对脚本目录中的所有文件执行相同的操作。
以下是脚本在步骤中与 cmets 的搭配方式:
# This part will be responsible from fetching the week number to replace from the script directory name, currently I am testing with pre-determined number
# $wk = Get-Item -Path $PWD | Select-Object -Property BaseName
# $wknn = "$wk".Substring(13,2) -as [int]
$wknn = 41
$wkold = $wknn-1
$wkprev = $wknn-2
$DefaultFiles = Get-ChildItem | Where-Object {$_.Name -like "*.xls*"}
ForEach($File in $DefaultFiles)
{
# Build ZIP file name
$zipFile = $_ -ireplace [regex]::Escape(".xlsb"), ".zip"
# Create temporary folder
$parent = [System.IO.Path]::GetTempPath();
[string] $guid = [System.Guid]::NewGuid();
$tempFolder = Join-Path $parent $guid;
New-Item -ItemType Directory -Path $tempFolder;
# Rename file to ZIP
Rename-Item -Path $_ -NewName $zipFile
# Not using Expand-Archive because it changes the ZIP format
C:\7z\7za.exe x "$zipFile" -o"$tempFolder"
# Replace old text with new text. First replace wk-1 to wk and then wk-2 to wk-1
$fileNames = Get-ChildItem -Path $tempFolder -Recurse -Include *.rels
foreach ($file in $fileNames)
{
(Get-Content -ErrorAction SilentlyContinue $file.FullName) |
Foreach-Object { $_ -replace $wkold, $wknn } |
Foreach-Object { $_ -replace $wkprev, $wkold } |
Set-Content $file.FullName
}
# Changing working folder because 7Zip option -w doesn't work
Set-Location -Path $tempfolder
# Update archive with new files. Not using Compress-Archive because it changes the ZIP format
C:\7z\7za.exe u -r "$zipFile" *.*
# Rename file back to XLSB
Rename-Item -Path $zipFile -NewName $_
#Move the final .xlsb file back to the script root
move-Item -Path $_ -destination $PSScriptRoot
#Set location to script root to start over
Set-Location -Path $PSScriptRoot
}
}
我遇到了 forEach 循环的问题。我不确定如何在 Build Zip File Name 步骤的第一个循环中引用文件名。之后我想将输出文件移动到脚本根目录时如何引用它。此外,我怀疑 forEach 循环的堆叠可能不那么简单,并且需要在代码中执行额外的步骤,但由于我刚开始使用 C 语言,我没有经验,无法找到我的问题的简单答案。
我非常感谢您对我的代码中的语法提供一些帮助 :)
【问题讨论】:
-
$file.Name,尽管您可能希望在外部或内部 foreach 循环中重命名$file变量
标签: excel powershell zip