当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何使用 PowerShell Replace 来替换字符串或字符

作者:精品下载站 日期:2024-12-14 03:41:58 浏览:12 分类:玩电脑

如何使用 PowerShell Replace 来替换字符串或字符


您需要在 PowerShell 中替换字符串或字符吗?或者您想将完整的文本块插入到文件中?那么 PowerShell 中的替换功能就是您要寻找的。

通过 PowerShell 中的 Replace 方法或 -replace 运算符,我们可以查找任何字符或(部分)字符串并将其替换为其他数据。

在本文中,我们将了解在 PowerShell 中替换字符串的不同方法,并且我还将为您提供一些有关替换功能的有用示例。

Powershell 替换字符串中的字符

在 PowerShell 中,我们可以对任何字符串或字符串变量使用 Replace() 方法。该方法需要两个参数,即您想要查找的文本或字符以及您想要替换的文本或字符。

解释 PowerShell Replace 函数最好通过示例来完成,因此让我们从一些简单的示例开始,例如替换字符串中的字符或单词。

我们采用以下字符串:

$str = "Welcome to LazyAdmin"

要将单词 to 替换为 at,我们可以使用以下方法:

$str = $str.Replace('to','at')

[玩转系统] 如何使用 PowerShell Replace 来替换字符串或字符

我已将替换方法的结果存储到同一个变量中。在PowerShell中使用replace方法不需要使用变量,如果需要的话也可以直接替换字符串。

"Welcome to LazyAdmin".Replace('to','at')

我经常使用的另一个例子是替换文件夹路径中的斜杠:

$Paths = "folder\subfolder"
$Paths.replace('\','\')

# Result
folder\subfolder

从字符串中删除字符或单词

我们还可以使用replace方法从字符串中删除单词或字符。为此,我们只需将内容替换为空字符串,如下所示:

# Replace the word 'to' with nothing
$str.Replace("to","")

让我们获取一个电子邮件地址列表,并从中删除域名和 @ 符号,这样我们就只剩下用户名了。我们将循环遍历包含邮件地址的数组,并将结果存储在 $usernames 中:

$mailAddresses = @("[email protected]","[email protected]","[email protected]")
$usernames = @()

$mailAddresses | ForEach{
    $usernames += $_.Replace("@lazydev.com","")
}

# Result
AdeleV
GradyA
JoniS

使用替换将文本插入模板

我创建的一些脚本发送了一封包含信息的电子邮件,例如新用户的用户名和密码,或未启用 MFA 的所有用户的概述。

对于这些电子邮件,我创建了一个 HTML 电子邮件模板,并在该模板中放置了用户名和密码的占位符。

<p>Hi {{manager.firstname}},</p>
<p>The account for {{user.fullname}} is ready. Below you will find the login credentials for {{user.firstname}}. The password is temporary and needs to be changed after the first login.</p>
  <p>
	  <table>
		  <tr>
			  <td style="font-family:sans-serif;font-size:14px;">Username: </td>
			  <td style="color:#000000;"><strong>{{user.UserPrincipalName}}</strong></td>
		  </tr>
		  <tr>
			  <td style="font-family:sans-serif;font-size:14px;">Password: </td>
			  <td><strong>{{user.Password}}</strong></td>
		  </tr>
	  </table>
  </p>
<p>If you have any questions, please let us know</p>
<p>IT</p>

正如您在 HTML 模板中看到的,我创建了带有大括号 {{ }} 的占位符。使用 PowerShell,我们可以加载 HTML 文件的内容并使用替换将所有占位符替换为正确的值:

#Get the mailtemplate
$mailTemplate = (Get-Content ($rootPath + '\' + $config.Settings.mailTemplateManager)) | ForEach-Object {
	$_ 	-replace '{{manager.firstname}}', $manager.GivenName `
	-replace '{{user.UserPrincipalName}}', $user.UserPrincipalname `
	-replace '{{user.Password}}', $config.Settings.password `
	-replace '{{user.fullname}}', $user.fullName `
	-replace '{{user.firstname}}', $user.givenName
} | Out-String	
		
return $mailTemplate

在本例中,我使用了 -replace 运算符,但您也可以使用 replace() 方法来替换多个实例:

$str = "Welcome to LazyAdmin"
$str.Replace('Welcome','Hello').Replace('to ','')

# Result
Hello LazyAdmin

Powershell 替换正则表达式

除了 Replace() 方法之外,我们还有 -replace 运算符。基本上,他们可以做同样的事情,用其他东西替换字符串中的任何字符或单词。但两者之间有一个很大的区别,-replace运算符使用正则表达式来匹配查找部分。

笔记

-replace 运算符仅使用正则表达式来查找关键字。它不在运算符的替换部分使用正则表达式。

让我们看下面的例子,我有一个日志文件列表,我想将其从 .log 重命名为 .txt。

[玩转系统] 如何使用 PowerShell Replace 来替换字符串或字符

为此,我们可以使用 PowerShell 中的 -replace 运算符从字符串末尾选择 .log 并将其替换为 .txt

Get-ChildItem c:\temp\files | Rename-Item -NewName { $_.name -replace '\.log$','.txt' }

现在,在这种情况下,我们还可以使用 replace() 方法,因为 .log 足够唯一,可以选择和替换。但是如果我们想从文件名中删除年份,那么我们需要使用正则表达式:

# Find 4 digits with \d{4}
Get-ChildItem c:\temp\files | Rename-Item -NewName { $_.name -replace '\d{4}','' }

[玩转系统] 如何使用 PowerShell Replace 来替换字符串或字符

如果您不是每天都这样做,那么创建正则表达式总是有点具有挑战性。 regex101.com 是一个测试表达式的好网站。

区分大小写和不区分大小写的替换

-Replace 运算符默认不区分大小写。您可以使用 -creplace 运算符而不是 -replace 使其区分大小写。例如:

$str = "Hello LazyAdmin"

# Case insensitive
$str -replace 'hello', 'Goodbye';
# Result : Goodbye LazyAdmin

# Case sensitive
$str -creplace 'hello', 'Goodbye;
# Result : Hello LazyAdmin

Powershell替换特殊字符

使用 PowerShell 中的替换运算符,我们可以轻松替换字符串中的所有特殊字符。正则表达式允许我们选择所有非单词字符,除了 a-z、A-Z 和 0-9 之外的所有字符。

例如:

$str = "Long [String] with _special@character#123$% and (spaces)'"
$str -replace ('\W', '')

# Result
LongStringwith_specialcharacter123andspaces

如果要删除除空格之外的所有特殊字符,那么我们需要使用稍微不同的正则表达式:

$str = "Long [String] with _special@character#123$% and (spaces)'"
$str -replace ('[^a-zA-Z\d\s:]', '')

# Result
Long String with specialcharacter123 and spaces

总结

使用 PowerShell 替换字符串中的字符或单词可以使用替换方法或 -replace 运算符轻松完成。使用特殊字符(例如 [ ]、\ 或 $ 符号)时,使用 replace() 方法通常比使用运算符变体更容易。因为这样你就不需要转义特殊字符。

请记住,在针对实际数据或文件运行脚本之前,请务必先测试脚本。

如果您有任何疑问,请在下面发表评论。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯