将凭据从一个PowerShell脚本传递到另一个

时间:2015-06-30 10:05:24

标签: powershell

我试图将凭据传递给另一个PowerShell脚本,但我收到错误

  

“无法转换”System.Management.Automation.PSCredential“值   键入“System.String”类型   “System.Management.Automation.PSCredential”“

这是调用psscript的脚本

param(
$vcenterserver,
[System.Management.Automation.Credential()]$vccredential
)


#New-Item C:\dcpromotxt\1.ps1 -ItemType file -Force


#Start-Process powershell.exe -ArgumentList "-NoExit -File '& 'C:\dcpromotxt\1.ps1''" -vcenterserver $vcenterserver -vccredential $vccredential


Start-Process powershell -ArgumentList "-NoExit -File '& 'C:\dcpromotxt\1.ps1''","$vcenterserver","$vccredential"

这是1.ps1

param(
$vcenterserver,
$vccredential
)

Connect-VIServer $vcenterserver -Credential $vccredential


start-sleep 120

3 个答案:

答案 0 :(得分:2)

您无法通过命令行传递Powershell对象,这些对象将被转换为字符串并变得无法使用。更糟糕的是," $ vccredential"由于toString()实现,返回类型名称。如果在当前会话中调用它,可以将PSCredential对象传递给脚本,如下所示:

& 'C:\dcpromotxt\1.ps1' $vcenterserver $vccredential

这样您的参数就不会被转换并保留内部结构。

但是,如果您需要单独的Powershell流程来处理新脚本,则可以将PSCredential转换为两个字符串,即$cred.username(ConvertFrom-SecureString $cred.password),您可以在目标端重新组合通过$cred=new-object PSCredential($username,(convertto-securestring $password))。此过程的限制是您的其他Powershell进程应在同一用户帐户和同一台计算机上运行。但您可以选择为转换cmdlet提供包含128,192或256位(可能在Win8 +上为384)的-key参数,这些参数将用于AES加密算法,这将允许您以另一个用户身份运行该Powershell进程或在另一台PC上使用共享密钥加密/解密敏感数据。作为额外的预防措施,您可以使用this module添加额外的"盐" (在该文章中命名为#34; entropy")加密,以便即使拦截安全字符串和密钥也不会使攻击者在没有已知熵的情况下解密您的数据。

答案 1 :(得分:1)

然后你可以尝试这种方法,用不同的密钥将信用卡保存到磁盘,然后修改ps1文件以从磁盘加载信号,如下所示:

首先:将Cred保存到磁盘

$credential = Get-Credential
$Key = [byte]1..16
$credential.Password | ConvertFrom-SecureString -Key $Key | Set-Content c:\cred.key

然后像这样编辑ps1文件:

param(
$vcenterserver
)

Add-PSSnapin VMware.VimAutomation.Core
$Key = [byte]1..16
$username = "type the username"
$encrypted = Get-Content c:\cred.key | ConvertTo-SecureString -Key $Key
$credential = New-Object System.Management.Automation.PsCredential($username, $encrypted)

Connect-VIServer $vcenterserver -Credential $credential

然后运行它:

Start-Process powershell -ArgumentList "-noExit -File c:\vcenter.ps1 -vcenterserver vcenter"

答案 2 :(得分:0)

您无法在参数字符串中传递凭据对象。像这样调用你的第二个脚本:

& 'C:\dcpromotxt\1.ps1' $vcenterserver $vccredential

通过Start-Process运行第二个脚本的要求没有意义。