【问题标题】:Powershell passing array to other script, turns to system hastable? Fix?Powershell将数组传递给另一个脚本,转向系统哈希表?使固定?
【发布时间】:2019-06-04 03:28:41
【问题描述】:

在 Powershell 中,我试图将数组作为参数传递给第二个脚本,但是根据调试器,这由第二个脚本作为 system.collection.hashtable 对象进行管理。我该如何解决这个问题?

调用脚本代码

$images = @{ 
   image1 = "$dir\welcomeMessageAtaP1_files\image001.jpg" 
}  
..\sendmail.ps1 –subject $subject1 –body $fixed3 -recipient $personalemail -images $images

sendmail.ps1 代码

 param (
    [string]$subject = "** EMPTY **",
    [string]$body = "** EMPTY **",
    [string]$recipient = "email@somedomain",
    [string[]] $images=@()
 )
$params = @{ 
    InlineAttachments = $images 
    Body = $body 
    BodyAsHtml = $true 
    Subject = $subject 
    From = "emailsender@somedomain"
    To = $recipient 
    SmtpServer = 'smtp.gmail.com' 
    Port = 587 
    UseSsl = $true 
} 

Send-MailMessage @params -Credential $cred

引发错误“Send-MailMessage:无法处理参数“InlineAttachments”的参数转换。无法将“System.String[]”类型的“System.String[]”值转换为“System.Collections.Hashtable”类型.

还尝试将参数更改为[string] $images=@()

【问题讨论】:

  • 您将$images 定义为一个哈希表,但您的脚本需要一个字符串数组 作为参数-images。你预计会发生什么?
  • @AnsgarWiechers,当使用[string[]] $images=@() 时,被调用的脚本不是需要一个哈希表吗??
  • 为什么会这样? @() 是数组子表达式运算符,它为您提供一个空数组,[string[]] 无论如何都会强制您的参数类型为“字符串数组”。
  • 那么如何将哈希表从一个脚本传递到另一个脚本?它是否正确? [string]$images = @{}
  • 你还是不明白。参数块中的[Type]$ParameterName 定义了特定类型 的参数。 hashtablestring 在你看来是不是同一类型?

标签: arrays powershell parameter-passing


【解决方案1】:

你确实传递了一个哈希表。 @{} 确实创建了一个哈希表,并且您有一个键 Image1 和一个值 "$dir\welcomeMessageAtaP1_files\image001.jpg"

$images = @{ 
   image1 = "$dir\welcomeMessageAtaP1_files\image001.jpg" 
} 

而是传递一个数组@():

$images = @( 
       "$dir\welcomeMessageAtaP1_files\image001.jpg" 
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2013-07-08
    • 2016-10-26
    相关资源
    最近更新 更多