【问题标题】:PowerShell to Copy To Clipboard Using -FilePowerShell 使用 -File 复制到剪贴板
【发布时间】:2020-02-23 14:12:01
【问题描述】:

我有一个应用程序能够调用/执行 Powershell 并在执行此操作时发送命令。

不幸的是,我需要它发送的部分命令包含带引号的多行文本。

因此,我的解决方案需要将该数据存储到一个变量/文件中,当应用程序发送命令参数时可以通过 powershell 引用该变量/文件。

我可以将其存储为 Copy.PS1

$command = 'Set-Clipboard -Value @"
Final text
Text also here
"@'

$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

然后我尝试调用 Powershell,同时发送参数:

powershell -ExecutionPolicy bypass -EncodedCommand $encodedCommand -File "Copy.PS1"

此过程不起作用。也没有显示任何错误。它根本不会更新剪贴板。

但是,当我打开 Powershell ISE 并在不引用文件的情况下运行它时,一切正常:

$command = 'Set-Clipboard -Value @"
Final text
Text also here
"@'

$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

powershell -ExecutionPolicy bypass -EncodedCommand $encodedCommand

谁能解释为什么这种行为如此不同?

【问题讨论】:

  • 您启动 Powershell 并提供编码命令 AND 文件?为什么?我希望其中之一 - 不是两者。我建议使用 here 字符串并将其复制到剪贴板。
  • 嗯...不确定我是否遵循。编码的命令是变量 $command 完全转义,因为它可以包含其他命令/HTML。
  • 您从哪里调用 PowerShell CLI (powershell.exe)?我以为$encodedCommandCopy.ps1 文件中,为什么还要通过CLI 传递它?请说明您的要求。

标签: powershell


【解决方案1】:

我建议让它尽可能简单。如果你想让一个字符串在复制到剪贴板的多行中运行,请执行以下操作......不要更多:

$HereString = @'
Some arbitrary
String running
accross multiple
lines
'@
Set-Clipboard -Value $HereString

将此保存到文件“Copy.PS1”并使用以下命令行运行它:

powershell -ExecutionPolicy bypass -File Copy.PS1

【讨论】:

  • OP 想要对命令进行编码。你的例子完全不同。
  • @WasifHasan 你确定 OP 想要什么吗? ;-) 我的印象是他甚至不知道自己想要什么。让我们等待他的回答。
  • 肯定只是想把它拼凑起来。感谢大家的帮助。我不需要编码信息,前提是这有助于将数据发送到 Powershell。通常需要对信息进行编码,否则特殊字符可能会出现问题。
  • @Mrbobdou 好的。那么你有没有尝试过你到目前为止得到的建议?它奏效了吗?其中之一?他们全部?你喜欢哪一款?如果没有 - 什么不起作用?你能至少给出一个状态吗?
  • 非常感谢全面的帮助。您的解决方案 Olaf 正是我需要做的。我想我的数据 $HereString 可以被编码然后发送编码,以确保如果碰巧有任何东西因为坏字符而损坏,因为它被编码了就可以了。这里不需要吗?
猜你喜欢
  • 2021-06-13
  • 1970-01-01
  • 2019-07-18
  • 2010-11-17
  • 2011-09-15
  • 2018-02-12
  • 1970-01-01
  • 2015-08-27
  • 2015-08-31
相关资源
最近更新 更多