简体   繁体   中英

PowerShell. Remove Forbidden Characters

What are the good ways of replacing uppercase letters to lower case letters while leaving only numbers and dashes from the strings with PowerShell?

We are automating deployment of Azure resources based on some strings. A lot of Azure Resources can only have in their names combinations of lowercase letters, numbers and dashes. 在此处输入图像描述

在此处输入图像描述

From the docs , valid names are:
Lowercase letters, numbers, and hyphens. Can't start or end with hyphen. Consecutive hyphens aren't allowed. Length 1-63 characters

To make sure a proposed name obides by these rules, one way would be to use a series of -replace actions, followed by trimming any possible hyphens at the beginning or start of the string, convert to lowercase and finally truncate the remaining string to the 63 character limit.

Something like this:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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