Powershell参数

我的脚本中有一个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 ) 

我可以在必需的参数字段中使用读主机CmdLet吗? 如果不是我能做些什么来确保我采用正确types的variablestypes,那么我可以将其传递给用户创build过程?

指定正确的密码types应该足够了,请尝试:

 Param ( [Parameter(Mandatory=$True)] [string]$FileLocation, [Parameter(Mandatory=$True)] [Security.SecureString]$password ) 

PowerShell将“掩码”密码(与read-host -asSecureString一样),结果types将是其他cmdlet可能需要的。

编辑:在最近的意见:解决scheme,这将提供两个选项提供纯文本密码,或强制用户input密码(但掩盖它相同的方式读取主机-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 

我已经使用Jaykul的技巧来骗取安全密码的提示。 ;)这会使得这个参数在CLI模式下很难使用( – input你的秘密密码将不会按预期工作),所以它应该强制脚本的用户忽略密码(并且得到掩码提示)或者用-password参数,接受常规string并将其转换为脚本逻辑内的安全string。

要破译你想做的事有点难

编辑; 就像Ryan所提到的,你现在已经把它指定为一个string了…

但是在一些代码中,当使用Read-Host和SecureStrings时,我使用了下面的函数

 function AskSecureQ ([String]$Question, [String]$Foreground="Yellow", [String]$Background="Blue") { Write-Host $Question -ForegroundColor $Foreground -BackgroundColor $Background -NoNewLine Return (Read-Host -AsSecureString) } 

在你的情况下,你可以通过下面的方式来调用它。

 Param ( [Parameter(Mandatory=$True)] [string]$FileLocation, [Parameter(Mandatory=$True)] [string]$password = AskSecureQ "Type the password you would like to set all the users to" ) 

编辑:给出评论,只是为了它的地狱…这里是另一种方法用于转换上面的安全string为Powershell内的纯文本;

 # Taking a secure password and converting to plain text Function ConvertTo-PlainText( [security.securestring]$secure ) { $marshal = [Runtime.InteropServices.Marshal] $marshal::PtrToStringAuto( $marshal::SecureStringToBSTR($secure) ) } 

你会这样使用它;

 $PWPlain = ConvertTo-PlainText $password 

总而言之,您将密码设置为masked,这是一个安全的string,然后您可以将其分解为纯文本以供别处使用,如果某些CLI程序只接受以纯文本forms传递给它们的密码,有助于自动化,你不想硬编码密码到你的脚本..

我不确定我是否理解……看起来你已经这么做了。 通过将该参数设置为强制性的,Powershell会在命令行中提示您,如果您没有在命令行上提供该参数,则使用[string]确保唯一可以进入该variables的数据types是System.string。

编辑:build立在Bartek的答案,在你的脚本中做到这一点:

 Param ([Parameter(Mandatory=$true,ValueFromPipeline=$true)][Security.SecureString]$Password) 

然后你必须像这样传递一个SecureString对象的脚本:

 PS:> Read-Host -AsSecureString | .\YourScript.ps1