Tec*_*yTJ 10 scripting powershell shell-scripting
我的脚本中有一个 Param 块
Param (
[Parameter(Mandatory=$True)]
[string]$FileLocation,
[Parameter(Mandatory=$True)]
[string]$password = Read-Host "Type the password you would like to set all the users to" -assecurestring
)
Run Code Online (Sandbox Code Playgroud)
我可以在必填的参数字段中使用 Read-Host CmdLet 吗?如果不是,我能做些什么来确保我采用正确类型的变量类型,以便我可以将它传递给用户创建过程?
Bar*_*ekB 17
指定正确的密码类型就足够了,请尝试:
Param (
[Parameter(Mandatory=$True)]
[string]$FileLocation,
[Parameter(Mandatory=$True)]
[Security.SecureString]$password
)
Run Code Online (Sandbox Code Playgroud)
PowerShell 将“屏蔽”密码(与 read-host -asSecureString 相同)并且结果类型将是其他 cmdlet 可能需要的类型。
编辑:在最近的评论之后:解决方案,这既提供了提供纯文本密码的选项,也提供了强制用户输入密码的选项(但以与 Read-Host -AsSecureString 相同的方式进行屏蔽),并且在这两种情况下都得到 [Security.SecureString] 最后. 而且,作为奖励,您会收到一些输入密码的奇特提示。;)
[CmdletBinding(
DefaultParameterSetName = 'Secret'
)]
Param (
[Parameter(Mandatory=$True)]
[string]$FileLocation,
[Parameter(
Mandatory = $True,
ParameterSetName = 'Secret'
)]
[Security.SecureString]${Type your secret password},
[Parameter(
Mandatory = $True,
ParameterSetName = 'Plain'
)]
[string]$Password
)
if ($Password) {
$SecretPassword = $Password | ConvertTo-SecureString -AsPlainText -Force
} else {
$SecretPassword = ${Type your secret password}
}
Do-Stuff -With $SecretPassword
Run Code Online (Sandbox Code Playgroud)
我在这里使用了 Jaykul 的技巧来提示输入安全密码。;) 它会使这个参数在 CLI 模式下很难使用(-Type 你的秘密密码不会像预期的那样工作),所以它应该强制脚本的用户要么省略密码(并获得屏蔽提示)或指定它-password 参数接受常规字符串并将其转换为脚本逻辑中的安全字符串。