[英]Set-Content and then Get-Content change the content somehow
PowerShell changes the contents of a text file on Get-Content
or the variable on Set-Content
. PowerShell会更改
Get-Content
上的文本文件或Set-Content
上的变量Set-Content
。
This is a PowerShell script for compiling a bunch of files and formatting them to a single text file, this part checks if the new file is equal to the old one, but according to the comparison, it never is. 这是一个PowerShell脚本,用于编译一堆文件并将其格式化为单个文本文件,该部分检查新文件是否等于旧文件,但根据比较,它永远不会。 I've tried messing with stuff like making the new var be a string array as get-content is.
我试过弄乱诸如使新的var成为get-content那样的字符串数组之类的东西。
$files = Get-ChildItem -path "./dir" | Where-Object -FilterScript {$_.Name -match '[A-J]'}
$var = @()
foreach ($file in $files){
$filePath = "dir\" + $file;
$fileContent = Get-Content $filepath
$var += $fileContent
}
$firstLine = '"this" "issen" "da" "first"'
$var1 = '"abc" "def" "12" "6"'
$var2 = '"456" "def" "12" "4"'
$newContent = $firstLine,$var,$var1,$var2
$oldContent = Get-Content './File.txt'
if (-not (Compare-Object $oldContent $newContent)) {
Write-Host Nothing new.
} else {
Write-Host Something new
Set-Content './File.txt' -value $newContent
}
Set-Content './File.txt' -value $newContent
pause
When comparing $newContent
to $oldContent
which is just $newContent
stored and retrieved from a text file they are not identical. 当比较
$newContent
至$oldContent
这仅仅是$newContent
存储和检索从一个文本文件,他们是不相同的。 They should be, right? 他们应该是吧?
The text files that are gathered from ./dir are like this: a00.txt 从./dir收集的文本文件如下:a00.txt
a12 bc23 abc
b00.txt b00.txt
a12 bc23 abg
Your first line $var = "stuff","and","thangs"
creates an array (3 strings): 您的第一行
$var = "stuff","and","thangs"
创建一个数组(3个字符串):
The -eq
operator doesn't work like that for comparing object arrays . -eq
运算符不能像比较对象数组那样工作。 You can instead use the Compare-Object cmdlet: 您可以改用Compare-Object cmdlet:
if (-not (Compare-Object $var $var2)) {
Write-Host True
}
Answer to your edit: 回答您的编辑:
Your first variable ( $newContent
) is an array of strings but also includes another array of strings . 您的第一个变量(
$newContent
)是一个字符串数组,但还包括另一个字符串数组 。 See here: 看这里:
PS D:\temp> $newContent -join ''
"this" "issen" "da" "first"System.Object[]"abc" "def" "12" "6""456" "def" "12" "4"
PS D:\temp> $oldContent -join ''
"this" "issen" "da" "first"a12 bc23 abca12 bc23 abg"abc" "def" "12" "6""456" "def" "12" "4"
A workaround is to pipe the variable to the Out-String
cmdlet, but you might find a cleaner way to solve it ;-) 一种解决方法是将变量通过管道传递到
Out-String
cmdlet,但是您可能会找到一种更干净的方法来解决它;-)
Compare-Object ($oldContent | out-string) ($newContent | out-string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.