2017-07-05 97 views
0

我有很長的腳本需要添加到創建的文件,問題是它的腳本,它包含大量的特殊字符。在powershell中添加腳本到文件

而且我收到很多錯誤,我已經把腳本放在''中,但它沒有按照我的預期工作。

有沒有一種簡單的方法來做到這一點,比如拿一個文本,然後將它添加到文件,以某種方式與特殊的字符?

powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 - 'Function Press-Button 
{ 
    Add-Type -AssemblyName System.Windows.Forms 
    [System.Windows.Forms.SendKeys]::SendWait('~'); 
} 

Function Resize-Window 
{ 
    $pshost = get-host 
    $pswindow = $pshost.ui.rawui 

    $newsize = $pswindow.buffersize 
    $newsize.height = 300 
    $newsize.width = 128 
    $pswindow.buffersize = $newsize 

    $newsize = $pswindow.windowsize 
    $newsize.height = 5 
    $newsize.width = 128 
    $pswindow.windowsize = $newsize 
} 

Function Run-Tool 
{ 
    $ps = new-object System.Diagnostics.Process 
    $ps.StartInfo.Filename = "C:\Testing\bin.exe" 
    $ps.StartInfo.RedirectStandardInput = $true 
    $ps.StartInfo.UseShellExecute = $false 

    $ps.start() 

    while (! $ps.HasExited) { 
     Start-Sleep -s 5 
     write-host "I will press button now..." 
     Press-Button 
    } 

    Write-Output "Default key was pressed" 
    Write-Output "exit code: $($ps.ExitCode)" 
} 

Resize-Window 
Run-Tool' 
+0

由於您在代碼中使用單引號,因此不能只是簡單地使用它們來包含整個事物。如果在PowerShell中執行此操作,請使用[herestring](https://technet.microsoft.com/en-us/library/ee692792.aspx)''@''nThext和stuff'n「@''。你似乎也有一個浮動連字符。你爲什麼試圖完全做到這一點。你從哪裏做這個? – Matt

回答

1

你想使用Here String定義文本塊。您使用@"開始這裏字符串,並使用"@結束。

@"必須在第一行的最後一件事,截止"@必須在下一行的前兩個字符:

$a = @" 
This is a here-string. I can type "anything" I want, 
even carriage returns, and it will all be preserved. 
No need to escape! 
"@ 

與你的腳本使用它應該是這樣的:

powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 @" 
Function Press-Button 
{ 
    Add-Type -AssemblyName System.Windows.Forms 
    [System.Windows.Forms.SendKeys]::SendWait('~'); 
} 

Function Resize-Window 
{ 
    $pshost = get-host 
    $pswindow = $pshost.ui.rawui 

    $newsize = $pswindow.buffersize 
    $newsize.height = 300 
    $newsize.width = 128 
    $pswindow.buffersize = $newsize 

    $newsize = $pswindow.windowsize 
    $newsize.height = 5 
    $newsize.width = 128 
    $pswindow.windowsize = $newsize 
} 

Function Run-Tool 
{ 
    $ps = new-object System.Diagnostics.Process 
    $ps.StartInfo.Filename = "C:\Testing\bin.exe" 
    $ps.StartInfo.RedirectStandardInput = $true 
    $ps.StartInfo.UseShellExecute = $false 

    $ps.start() 

    while (! $ps.HasExited) { 
     Start-Sleep -s 5 
     write-host "I will press button now..." 
     Press-Button 
    } 

    Write-Output "Default key was pressed" 
    Write-Output "exit code: $($ps.ExitCode)" 
} 

Resize-Window 
Run-Tool 
"@ 
+1

這將只適用於1)如果你已經*在* PowerShell中,並且2)如果你使用@ @ @ @ @(單引號),因爲替換在@ @ @ @ @ @ @中仍然是活動的,這幾乎肯定不是當文本是腳本時你想要什麼。 –

0

你應該點源你的外部腳本。這有效地將該腳本的內容轉儲到您的工作腳本中。在頂部(或任何你想要進行初始化代碼):

. "\\Path\to\Script.ps1" 
相關問題