简体   繁体   English

如何使用 PowerShell 清除文本文件中返回的变量值?

[英]How to blank out returned variable values in text file using PowerShell?

I have text files with values I would like to blank out using a PowerShell script.我有一些文本文件,我想使用 PowerShell 脚本将其清空。

For example, there are the following variables and their corresponding values:例如,有以下变量及其对应的值:

Customer FirstName = CHRISTINE
Customer LastName = TOWN
CRN = 211021815L

I would like the script to go through the contents of the file and replace the returned values so they appear as below:我希望脚本遍历文件的内容并替换返回的值,使其显示如下:

Customer FirstName = ******
Customer LastName = ******
CRN = ******

Ideally, the number of asterisks will be the same for every returned value so that no information can be derived from it.理想情况下,每个返回值的星号数量都相同,因此无法从中导出任何信息。 As in, if the Customer FirstName returnd value is 8 characters, the number of asterisks should NOT match 8 characters.例如,如果Customer FirstName返回的值为 8 个字符,则星号的数量不应与 8 个字符匹配。 It should be arbitrary.它应该是任意的。

Note that I have seen an existing question asked that is similar but the person asks how to insert a variable value into a placeholder rather than replacing an already retured value.请注意,我已经看到一个类似的现有问题,但该人询问如何将变量值插入占位符而不是替换已经返回的值。 As the returned value within my text files are constantly changing, a different solution is needed.由于我的文本文件中的返回值不断变化,因此需要不同的解决方案。

I am very new to PowerShell but came up with something pretty basic below:我对 PowerShell 很陌生,但在下面想出了一些非常基本的东西:

(Get-Content C:\Temp\Logs\logfile.log).replace('CRN = <REGEXPRESSIONHERE>', '*****') | Set-Content C:\Temp\Logs\logfile.log

Is there a nicer way to accommodate for more variables in the single line rather than having a line to replace the returned value for each variable that needs to be blanked out?有没有更好的方法来容纳单行中的更多变量,而不是用一行来替换需要清空的每个变量的返回值?

Here's a possible solution:这是一个可能的解决方案:

( Get-Content .\logfile.log | ForEach-Object { $_ -replace "(.+) = .+", "`$1 = ****" } ) | Set-Content .\logfile.log

I believe you have to allow Get-Content and ForEach-Object to complete before writing back to the same file.我相信在写回同一个文件之前,您必须允许Get-ContentForEach-Object完成。 That's the reason for the extra set of parentheses.这就是额外的括号的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM