我想使用以下代码在 XML 文件中搜索名称:
# Basispfad zu den DWX-Dateien
$dwxFilePath = "C:\Users\xyz\Desktop\testordner4\000\0000000001\DocumentInfo.dwx"
# Lese den Inhalt der DWX-Datei
$dwxContent = Get-Content -Path $dwxFilePath -Raw
# Entferne Leerzeichen aus dem Inhalt
$dwxContentWithoutSpaces = $dwxContent -replace '\s', ''
# Write dwxContentWithoutSpaces
Write-host $dwxContentWithoutSpaces # This always works and always gives the same output
# Definiere den regulären Ausdruck für den Rechnungsnamen in der SectionMetadata
$regex = [regex]'OriginalFileName="(.*?)".*?' # This only seems to work when I open it once with Notepad
# Suche nach dem Match im Inhalt der DWX-Datei
$match = $regex.Match($dwxContentWithoutSpaces)
# Definiere Invoice-Namen
$Name = $match.Groups[1].Value
# Schreibe Invoice-Name
Write-host $Name
这仅当我用记事本打开
.dwx
文件一次,保存并关闭它时才有效。
我肯定缺少接线员。
有什么想法吗?
$dwxContent = Get-Content -Path $dwxFilePath -Raw -Encoding UTF8
没用。
https://adamtheautomator.com/powershell-convert-string-to-int/#Casting_to_XML
您可以考虑将 $dwxContent 变量转换为 XML,然后 PowerShell 将在 XML 对象中本机工作。然后,您将能够使用 .NET XML 类的方法和属性。
[xml]$dwxContent
tl;博士
Get-Content
无法识别您文件的真实字符编码,因此您需要确定真实的编码并通过-Encoding
参数指示它。
如果您使用的是 Windows PowerShell 并且通过
-Encoding
参数不支持真正的编码,则必须直接使用 .NET API。
请参阅下一节了解详细信息。
但是,由于您的文件是一个 XML 文件,因此最好这样解析它。
虽然基于 regex 的方法适用于简单的情况,但使用 XML 解析器通常更可取。
另一个优点是 .NET 的 XML API 会自动检测 XML 文件的编码(如果通过其 XML 声明指示),例如
<?xml version="1.0" encoding="ISO-8859-1"?>
换句话说:如果您切换到 XML 解析,您的编码问题也可能会消失。
Select-Xml
cmdlet 提供了一种解析 XML 文件并通过 XPath 表达式查询它们的便捷方法,因此以下内容可能适合您:
$name = (
Select-Xml -LiteralPath $dwxFilePath -XPath '//*/@OriginalFileName' |
Select-Object -First 1
).Node.InnerText
仅当我用记事本打开 .dwx 文件一次,保存并关闭它时才有效。
这意味着
Get-Content
无法识别您文件的真实字符编码,而记事本似乎可以。
使用基于 regex 的方法,使用
Get-Content
的 -Encoding
参数确实是解决方案的关键,但您需要首先确定真正的编码是什么 - 根据您的问题,它 不是 UTF-8。
请注意,
Get-Content
默认采用什么编码 - 文件开头没有 BOM(字节顺序标记) - 因 PowerShell 版本而异:
Windows PowerShell 采用系统的旧版 ANSI 代码页,例如美国英语系统上的 Windows-1252。
PowerShell(核心)7+现在 - 幸运的是 - 假设UTF-8,即Unicode最广泛使用的编码。
ANSI:
-Encoding Ansi
Ansi
标识符,遗憾的是,请使用以下解决方法:
Get-Content -Encoding ([cultureinfo]::CurrentCulture.TextInfo.ANSICodePage) -Raw $dwxFilePath
Get-Content
,在两个 PowerShell 版本中,确实能够根据 BOM 识别各种 Unicode 编码(很少使用的 UTF-7 编码除外)。 如果您的文件的
真实编码(请参阅下一节了解如何发现它)无法通过预定义的-Encoding
标识符使用,例如
utf-8
:
PowerShell(核心):
-Encoding
,例如
-Encoding ([System.Text.Encoding]::GetEncoding('ISO-8859-1')
.CodePage
属性值;例如,以下内容与上述内容等效:
-Encoding 28591
Windows PowerShell中:
# NOTE: Be sure to pass a *full* file path, because .NET's
# working dir. usually differs from PowerShell's.
[System.IO.File]::ReadAllText($dwxFilePath, [System.Text.Encoding]::GetEncoding('ISO-8859-1'))
确定文本文件的真实编码:
encoding
属性(如果存在);例如,
<?xml version="1.0" encoding="ISO-8859-1"?>
WSL,则调用 file
/
wsl file
;
file
Unix 实用程序提供文件的简洁描述,包括其字符编码(对于文本文件)。
wsl file DocumentInfo.dwx
Get-Content
无论如何都会识别此类文件)。