2013-03-15 55 views
1

我知道如何使用貓文件如何從PowerShell中的文本文件內容設置變量?

cat file.txt 

,但我有可變

[string]$body = "Body message here" 

我需要幫助改變它擺脫file.txt

我試過的文本內容,但它沒」工作。

[string]$body = $cat file.txt 

這裏是完整的腳本,我正在嘗試更改param部分。

param 
(  
    [string]$email = $(read-host "Enter a recipient email"), 
    [string]$subject = $(read-host "Enter the subject header"), 
    [string]$body = $(read-host "Enter the email text (optional)") 
) 

param 
(  
    [string]$email = "[email protected]", 
    [string]$subject = "server", 
    [string]$body = gc C:\Users\myuser\Documents\somefolder\GnuWin32\bin\status.txt 
) 

# ========================================================================== 
# Functions 
# ========================================================================== 

function Send-Email 
(
    [string]$recipientEmail = $(Throw "At least one recipient email is required!"), 
    [string]$subject = $(Throw "An email subject header is required!"), 
    [string]$body 
) 
{ 
    $outlook = New-Object -comObject Outlook.Application 
    $mail = $outlook.CreateItem(0) 
    $mail.Recipients.Add($recipientEmail) 
    $mail.Subject = $subject 
    $mail.Body = $body 

    # For HTML encoded emails 
    # $mail.HTMLBody = "<HTML><HEAD>Text<B>BOLD</B> <span style='color:#E36C0A'>Color Text</span></HEAD></HTML>" 

    # To send an attachment 
    # $mail.Attachments.Add("C:\Temp\Test.txt") 

    $mail.Send() 
    Write-Host "Email sent!" 
} 

Write-Host "Starting Send-MailViaOutlook Script." 

# Send email using Outlook 
Send-Email -recipientEmail $email -subject $subject -body $body 

Write-Host "Closing Send-MailViaOutlook Script." 

回答

2

變化:

[string]$body = (gc C:\Users\myuser\Documents\somefolder\GnuWin32\bin\status.txt) 

注意括號。

+0

謝謝,對不起,我希望他們允許我們接受2個答案。 – Mowgli 2013-03-15 16:02:35

+0

@Mowgli很高興幫助!下次發佈錯誤的PowerShell也給你,它可以幫助我們給予答案 – 2013-03-15 16:04:24

+0

我也想自己做,但我不知道如何暫停PS腳本。我已經2天了。 – Mowgli 2013-03-15 16:06:21

3

請嘗試以下

[string]$body = gc file.txt 

命令gcGet-Content的別名,這將獲得指定項目的內容,並返回它作爲一個string

編輯

由於C.B.指出,在你的例子中你試圖用$cat而不是cat$cat嘗試指的是沒有定義的變量,但cat是另一個別名Get-Content

EDIT2

它看起來像你正試圖初始化設置了一個param。如果是這樣,你需要做以下

[string]$body = $(gc "C:\Users\myuser\Documents\somefolder\GnuWin32\bin\status.txt") 
+2

此外'cat'是'get-content'的別名,在OP代碼中錯誤是'$ cat file.txt',其中'$ cat'是一個不存在的變量,而不是'get-內容cmdlet'。 – 2013-03-15 15:54:33

+0

get-content也是貓的別名,所以他可以保留它。只需要失去$。 – mjolinor 2013-03-15 15:55:06

+0

我也嘗試過'gc',但它沒有奏效。請在我的問題中看到更新的代碼,在我的另一個腳本'cat file.txt'中工作。我不知道爲什麼它在這裏不起作用。 – Mowgli 2013-03-15 15:55:44

相關問題