【问题标题】:Using Wild Cards in Powershell variables在 Powershell 变量中使用通配符
【发布时间】:2019-02-05 15:52:40
【问题描述】:

我有一个包含每周报告的文件夹。每个报告在名称示例“report-A_2_05_19.pdf”、“report-B_2_05_19.pdf”等中都有创建日期。我想为这些创建变量,但由于每周报告名称的日期都会发生变化我试图这样做:

$rA = "c:\reports\report-A*.pdf"
$rb = "C:\reports\report-B*.pdf

当我这样做并尝试使用通配符打开报告时,它只会打印到屏幕上:

c:\reports\report-A*.pdf

$pw = Get-Content C:\MailPW.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential name@domain.com, $pw
Send-MailMessage -To name@domain.com -from name@domain.com -Subject "Attachments" -Body "Attachments." -attachments $rA, $rB -Smtpserver mail.domain.com -UseSsl -credential $cred

【问题讨论】:

  • How to AskEdit 问题并显示您的 minimal reproducible example 和一些显示问题的示例输出。
  • 我对这个问题感到困惑。比如你在哪里使用变量$rA$rb
  • $pw = 获取内容 C:\MailPW.txt | ConvertTo-SecureString;$cred = 新对象 System.Management.Automation.PSCredential name@domain.com, $pw;发送邮件消息 -至 name@domain.com -来自 name@domain.com -主题“附件” -正文“附件”。 -attachments $rA, $rB -Smtpserver mail.domain.com -UseSsl -credential $cred;

标签: powershell variables wildcard


【解决方案1】:

如果您查看 Send-MailMessage 的文档,您会发现 -Attachments 确实支持通配符

类型:字符串[]

别名:PsPath

职位:已命名

默认值:无

接受管道输入:True (ByValue)

接受通配符:False

因此,您可以改为合并 Resolve-Path,它会根据通配符字符串推断路径。

Send-MailMessage .... -attachments (Resolve-Path $rA, $rB).Path

请注意,这可能会超出您的预期。您可能需要在附加文件之前验证结果。


如果提供大量参数和值,我也会推荐splatting

$sendMailMessageParameters = @{
    To          = "name@domain.com"
    from        = "name@domain.com" 
    Subject     = "Attachments" 
    Body        = "Attachments." 
    attachments = (Resolve-Path $rA, $rB).Path
    Smtpserver  = "mail.domain.com "
    UseSsl      = $true
    credential  = $cred
}

Send-MailMessage @sendMailMessageParameters

【讨论】:

  • 实际上我最终没有使用变量,只是使用了带有通配符的 -attachments 中的报告文件路径,这很有效。我的问题不在于发送邮件消息,而是试图让通配符在变量中工作。
  • @irishombian 那时我不明白。您是否希望 PowerShell 将您的 string 完全解释为文件路径?您需要告诉 PowerShell 如何处理它。 Get-Item 也可以使用
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2013-10-10
  • 2014-06-26
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2021-12-22
相关资源
最近更新 更多