首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将脚本添加到powershell中的文件

将脚本添加到powershell中的文件
EN

Stack Overflow用户
提问于 2017-07-05 21:15:43
回答 2查看 65关注 0票数 0

我有一个很长的脚本,需要添加到创建的文件,问题是它是一个脚本,它包含许多特殊字符。

我收到了很多错误,我把脚本放在'‘中,但它没有像我预期的那样工作。

有没有一种简单的方法可以做到这一点,比如获取一个文本并将其添加到文件中,以某种方式使用特殊字符?

代码语言:javascript
复制
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'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-05 21:27:27

您可能希望使用Here String来定义文本块。您可以使用@"开始一个here-string,使用"@结束它。

@"必须是第一行的最后一个字符,结束的"@必须是下一行的前两个字符:

代码语言:javascript
复制
$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!
"@

将其与您的脚本一起使用将如下所示:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-07-05 21:26:43

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

代码语言:javascript
复制
. "\\Path\to\Script.ps1"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44927367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档