簡體   English   中英

如何從命令提示符將命名數組參數傳遞給其中包含空格的powershell腳本?

[英]How can I pass a named array parameter to a powershell script that has a space in it from the command prompt?

我正在嘗試將幾個參數傳遞給$ attachments參數中的以下腳本,這似乎適用於單個附件,或者當路徑中沒有空格時,但是當將多個值傳遞給數組時一個或多個腳本在路徑中有空格失敗,並顯示錯誤,指示找不到指定的文件。

為了增加難度,這是從c#啟動的。 我已經嘗試了以下命令的幾種排列。 整個命令行看起來像這樣:

powershell.exe -executionpolicy unrestricted -file "c:\program files (x86)\App\Samples\SendEmail.ps1" -attachments "c:\Program Files (x86)\App\Logs\1234.log,c:\Program Files (x86)\App\Logs\12345.log"

劇本:

param(
    [array]$attachments,
    [string]$from = 'test@test.com',
    [array]$to = 'test@test.com',
    [string]$subject = 'Threshold Exceeded',
    [string]$body = 'Testing. Please ignore.',
    [string]$smtpServer = 'testsmptserver.com'
)

$mailParams = @{
    From = $from
    To = $to
    Subject = $subject
    Body = $body
    SMTPServer = $smtpServer
}

if ($attachments)
{
    Get-ChildItem $attachments | Send-MailMessage @mailParams
}
else
{
    Send-MailMessage @mailParams
}   

有人遇到過這樣的事嗎? 你是怎么解決的?

您需要拆分$ attachments變量,因為它被視為單個文件。

代替

Get-ChildItem $attachments

嘗試

Get-ChildItem ($attachments -split ',')

您只將一個(引用的)字符串傳遞給“附件”數組,因此您只填充附件[0]。 嘗試傳遞多個字符串:

    PS C:\Windows\system32> [array]$wrong="there,you,go"

    PS C:\Windows\system32> $wrong
    there,you,go

    PS C:\Windows\system32> $wrong[0]
    there,you,go

    PS C:\Windows\system32> $wrong[1]

    PS C:\Windows\system32> $wrong[2]

    PS C:\Windows\system32> [array]$right="there","you","go";

    PS C:\Windows\system32> $right
    there
    you
    go

    PS C:\Windows\system32> $right[0]
    there

    PS C:\Windows\system32> $right[1]
    you

    PS C:\Windows\system32> $right[2]
    go

    PS C:\Windows\system32> 

從那里應該很清楚,你可以包括這樣的前導或尾隨空格:

    -attachments "value 1 has a trailing space "," value 2 has a leading space"

要得到:

    attachments[0]="value 1 has a trailing space ";
    attachments[1]=" value 2 has a leading space";

你提到你是在C#中運行它的,所以我會提醒讀者也要在包含這個命令的C#字符串中轉義每個引號(“ - > \\”)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM