gpt4 book ai didi

powershell - 如何将目录中的一组jpg文件作为一组修改为Base64

转载 作者:行者123 更新时间:2023-12-02 18:43:15 24 4
gpt4 key购买 nike

虽然我不是开发人员,但我已经通过 StackOverflow 寻找问题的答案已有一段时间了,感觉我欠你们很多一两杯冰镇啤酒。

我遇到了一个我似乎无法解决的问题。
我希望能够运行以下命令,将一组 jpg 文件转换为 Base64,以便提交给需要这种格式的监管机构:

[Convert]::ToBase64String((Get-Content C:\temp\168211_wheels.jpg -Encoding Byte)) >> c:\temp\Pictest.txt

我将针对一组 jpg 文件运行它,它们都在同一目录中。
我的第一个相当悲惨的尝试是这样的:

Get-ChildItem -Path ' C:\testimages\*' -Include '*.jpg' | ForEach-Object {
[Convert]::ToBase64String((Get-Content C:\testimages\*.jpg -Encoding Byte)) >> } c:\temp\Pictest.txt

我收到以下错误消息:

**At line:1 char:152
+ ... e64String((Get-Content C:\testimages\*.jpg -Encoding Byte))>>}c:\temp ...
+ ~
Missing file specification after redirection operator.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingFileSpecification**

非常欢迎任何指导或建议,因为这只是我第二次尝试使用 Powershell。

问候,
达伦

最佳答案

[System.IO.Directory]::EnumerateFiles('S:\SCRIPTS\GC', '*.exe', [System.IO.SearchOption]::AllDirectories) |
ForEach-Object {
return [PSCustomObject]@{
SourceFile = $_
TargetFile = [System.IO.Path]::ChangeExtension($_, 'j64')
}
} |
ForEach-Object {
$content = $null
$content = [System.IO.File]::ReadAllBytes($_.SourceFile)
$encodedContent = $null
$encodedContent = [System.Convert]::ToBase64String($content, [System.Base64FormattingOptions]::InsertLineBreaks)
[System.IO.File]::WriteAllText($_.TargetFile, $encodedContent, [System.Text.Encoding]::ASCII)
Write-Host "Processed $($_.SourceFile)"
}

使用 [System.IO.Directory]::EnumerateFiles(...) 处理大量文件时速度更快,因为它只返回完整的文件名,没有任何其他属性。

可以替换为Get-ChildItem -Path 'S:\SCRIPTS\GC' -Filter '*.exe' -File |在这种情况下,如果需要,请选择 -ExpandProperty 'FullName'


[System.IO.File]::ReadAllBytes(...)[System.IO.File]::WriteAllText(...) 只是在我看来,在这种情况下更明显。


请避免使用 powershell 的重定向运算符,如“>>”和“>”。他们经常制造问题。

关于powershell - 如何将目录中的一组jpg文件作为一组修改为Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67795712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com