gpt4 book ai didi

powershell - 获取动态创建的字符串长度

转载 作者:行者123 更新时间:2023-12-02 23:10:42 27 4
gpt4 key购买 nike

可以说我想做这样的事情:

$string = 'arbitrary string' # << is random
(Do-Something -Name ($string + (Get-Random)).Substring(0, [math]::Min(20, ??)

如何在 ($string + (Get-Random))中引用表达式结果的当前长度?

字符串少于20个字符时使用 Substring(0, 20)失败

Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length"

最佳答案

您必须将新字符串分配给变量:

Do-Something -Name ($s = $string + (Get-Random)).Substring(0, [math]::Min(20,$s.Length))

较简单的版本:
$Name = $string + (Get-Random)
if($Name.Length -gt 20){
$Name = $Name.Substring(0, 20)
}
Do-Something -Name $Name

如评论中所述,您还可以从字符串中按索引选择前20个字符,并再次与 -join运算符(v3.0及更高版本)组合:
$Name = "$string$(Get-Random)"[0..19] -join ''

感觉活泼?使用正则表达式(作为 suggested by wOxxOm):
$Name = "$string$(Get-Random)" -replace '^(.{20}).+','$1'

如果连接的字符串少于20个字符,则不会替换任何内容,否则整个字符串将匹配并被前20个字符替换

另一种方法是生成X的随机数,其中X为20- $string.Length(仅在 $string保证长度在2到19个字符之间的情况下有效):
$Name = "$string$(Get-Random -Min ('1' * (20 - $string.Length)) -Max ('9' * (20 - $string.Length)))"

关于powershell - 获取动态创建的字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435575/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com