如何在PowerShell脚本中检查用户是否输入而没有输入?

Joh*_*ohn 7 powershell

我有一个powershell脚本,我希望用户输入一个值,脚本返回一个随机字符串作为密码.如果他们只是在提示输入密码长度时按Enter键,我希望它是9个字符的默认值.

我怎么处理没有输入?

我试过这样的事情,但不认为这是对的:

Write-Host输入密码长度要求:

$length = Read-Host
IF ( $length -eq $NULL) 
    { Do continue on with the value of 9 for the length}
ELSE
    {Use $length for the rest of the script}
Run Code Online (Sandbox Code Playgroud)

其他部分工作得很好; 然而,当生成密码时,我一直发现自己一遍又一遍地输入9.我宁愿直接进入.

任何帮助是极大的赞赏!

ste*_*tej 11

PowerShell很棒,因为你可以经常缩短代码并且它可以工作:)

if (!$length) { 
  Do continue on with the value of 9 for the length
} ...
Run Code Online (Sandbox Code Playgroud)

为什么?

[bool]$null         # False
[bool]''            # False
[bool]'something'   # True
Run Code Online (Sandbox Code Playgroud)


JPB*_*anc 5

我会说“按设计工作”。因为 $length 不为 NULL。正确的测试是:

if ($length -eq [string]::empty)
Run Code Online (Sandbox Code Playgroud)

所以也许这两个测试的结合。

J.P