【问题标题】:PowerShell. Remove Forbidden Characters电源外壳。删除禁止字符
【发布时间】:2021-04-06 08:54:32
【问题描述】:

用 PowerShell 将大写字母替换为小写字母,同时只保留字符串中的数字和破折号的好方法是什么?

我们正在根据一些字符串自动部署 Azure 资源。许多 Azure 资源的名称中只能包含小写字母、数字和短划线的组合。

【问题讨论】:

  • 你是什么trying to do?根据您的用例,正则表达式可能会起作用,也可能不会。例如,使用非拉丁字符集将比 might expect 更棘手。
  • 我们正在自动部署名称中只能包含小写字母、数字和破折号的 Azure 资源。
  • 请将此添加到您的问题中。同时提供你已经尝试过的示例和代码。

标签: powershell


【解决方案1】:

来自the docs,有效名称为:
小写字母、数字和连字符。不能以连字符开头或结尾。不允许使用连续的连字符。长度 1-63 个字符

为了确保提议的名称遵守这些规则,一种方法是使用一系列-replace 操作,然后修剪字符串开头或开头的任何可能的连字符,转换为小写,最后截断剩余字符串不超过 63 个字符。

类似这样的:

$proposedName = '_Container___Name-123-'
$containerName = (($proposedName -replace '[^-a-z0-9]', '-' -replace                   # any character not hyphen, letter or digit --> '-'
                                          '-{2,}', '-').Trim("-").ToLower() -replace   # remove leading and trailing hyphens and convert to lowercase
                                          '(.{63}).*', '$1').TrimEnd("-")              # truncate to 63 characters and trim any trailing hyphens

$containerName # --> container-name-123

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多