ValidateLength Powershell [英] ValidateLength Powershell

查看:25
本文介绍了ValidateLength Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个剧本,所以不要打我!

This is my first script so don't beat me up to bad!

我正在编写一个创建网络目录的脚本 &基于用户输入的 AD 组.以下是我到目前为止所得到的.它有效,但我想进行一些改进.

I'm working on a script that creates a network directory & AD group based on user input. The following is what I've gotten so far. It works but I would like to make a few enhancements.

我想验证用户输入的长度.我找到了一篇文章(PowerShell ValidateLength with Read-Host),解释了如何使用 ValidateLength 字符串检查用户的输入.这很好用,但是,我想将它包含在循环中.例如,如果用户没有输入正好 X 个字符 - 然后重试.现在它只是出错了.

I would like to Validate length for user inputs. I was able to find an article (PowerShell ValidateLength with Read-Host) that explains how to use the ValidateLength string to check a user's input. This works great, however, I would like to include it in a loop. Example if user does not input exactly X characters - then retry. Right now it just errors out.

任何帮助将不胜感激!

[ValidateLength(2,2)]$Division = [string](Read-Host -Prompt 'Please enter the TWO digit division number ')
[ValidateLength(4,4)]$Matter = [string](Read-Host -Prompt 'Please enter the FOUR digit matter number ')
[ValidateLength(4,4)]$Client = [string](Read-Host -Prompt 'Please enter the FOUR digit client number ')

推荐答案

虽然各种 [Validate... 属性适用于变量,但这是一种非标准用法(很少有人知道它们).当您确实想出错时,它最有效.

Although the various [Validate... attributes work on variables, it's a non-standard usage (and few people know about them). It works best when you do want to error out.

如果您不这样做,请自行检查并决定如果这不是您想要的,该怎么办:

If you don't, just check it yourself and decide and what to do in the event that it's not what you want:

do {
    $Division = [string](Read-Host -Prompt 'Please enter the TWO digit division number ')
    if ($Divison.Length -ne 2) {
        continue
    }

    $Matter = [string](Read-Host -Prompt 'Please enter the FOUR digit matter number ')
    if ($Matter.Length -ne 4) {
        continue
    }

    $Client = [string](Read-Host -Prompt 'Please enter the FOUR digit client number ')
    if ($Client.Length -ne 4) {
        continue
    }

    break
} while ($true)

这篇关于ValidateLength Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆