gpt4 book ai didi

c# - 如何在Docker容器中运行此PowerShell脚本?

转载 作者:行者123 更新时间:2023-12-02 19:15:24 25 4
gpt4 key购买 nike

我试图在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
首先,我在网上搜索了答案,并在 here.中尝试了解决方案。但是,当我尝试使用给定的解决方案时,出现了以下错误。
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 switch

# 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的process API将命令行参数的长度限制为8191个字符,因此它仅适用于少于3050个字符(包括空格)的脚本

关于c# - 如何在Docker容器中运行此PowerShell脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63789814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com