在PowerShell中将脚本添加到文件中

时间:2017-07-05 13:15:43

标签: 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'

2 个答案:

答案 0 :(得分:1)

您可能希望使用Here String来定义文本块。您可以使用@"开始使用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 :(得分:0)

您应该点源外部脚本。这有效地将该脚本的内容转储到您的工作脚本中。在顶部(或您希望代码初始化的任何地方):

. "\\Path\to\Script.ps1"