PowerShell使用-File复制到剪贴板



我有一个应用程序,它能够调用/执行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

有人能解释为什么这种行为如此不同吗?

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

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

将其保存到文件"Copy.PS1"中,并使用以下命令行运行:

powershell -ExecutionPolicy bypass -File Copy.PS1

最新更新