簡體   English   中英

如何在 docker 容器中運行這個 PowerShell 腳本?

[英]How is it possible to run this PowerShell script inside a docker container?

我正在嘗試在 Windows Docker 容器中運行以下腳本 (myscript.ps1),而不實際將腳本文件復制到容器中。

$Source =  @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

public static class Imagehlp
{
    [DllImport("imagehlp.dll", CharSet = CharSet.Auto)]
    public static extern int MapFileAndCheckSum(string Filename, out int HeaderSum, out int CheckSum);
}
"@
Add-Type -TypeDefinition $Source

[int] $headerSum = 0;
[int] $checkSum = 0;
$result = [Imagehlp]::MapFileAndCheckSum(
    "C:\Program Files\Internet Explorer\iexplore.exe",
    [ref] $headerSum,
    [ref] $checkSum
    )

 if ($result -ne 0) {
     Write-Error "Error: $result"
    }
 $headerSum, $checkSum

首先,我在網上搜索了答案並在這里嘗試了解決方案 但是,當我嘗試給定的解決方案時,出現以下錯誤。

docker exec my-windows powershell -command "C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1"

C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1 : The term 
'C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1' is not
recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:1
+ C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\abc...yscript.p
   s1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

這個錯誤的原因可能是因為腳本在宿主機中而不是在容器中。 因此,我嘗試將腳本內容保存到 PowerShell 中的變量中,然后嘗試使用該變量運行命令。

$script1 = Get-Content ('C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1')
docker exec my-windows powershell -command $script1

這次我收到以下錯誤。

At line:1 char:15
+ $Source =  @" using System; using System.Diagnostics; using System.Ru ...
+               ~
No characters are allowed after a here-string header but before the end of the
line.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : UnexpectedCharactersAfterHereStringHeader

它說我的腳本的 here-string 部分沒有正確輸入, @"之后還有另一個字符,但之后沒有字符。我猜這與換行符或回車符有關,但我不是當然可以。你能幫幫我嗎?非常感謝!

為此,我建議利用powershell.exe-EncodedCommand開關

# Load script contents from disk
$script1 = Get-Content 'C:\Users\abc\Desktop\PowerShellScripts\myscript.ps1' -Raw
# UTF16LE-encode the script
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script1)
# Convert encoded byte string to b64
$encodedCommand = [Convert]::ToBase64String($bytes)

docker exec my-windows powershell -encodedcommand $encodedCommand

請注意,Windows 的進程 API 將命令行參數的長度限制為 8191 個字符,因此它僅適用於少於約 3050 個字符(包括空格)的腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM