Powershell编码命令长度问题

Powershell编码命令长度问题,powershell,Powershell,我正在尝试使用powershell.exe的-EncodedCommand参数以其他用户身份运行powershell脚本。我这样做是为了避免处理转义引号和其他特殊字符的命令行困难。我发现,当编码命令的长度超过916个字符时,它会失败,并显示以下消息: Start-Process : This command cannot be run due to the error: The stub received bad data. 以下是我使用的代码: $path = 'c:\temp' $Use

我正在尝试使用powershell.exe的-EncodedCommand参数以其他用户身份运行powershell脚本。我这样做是为了避免处理转义引号和其他特殊字符的命令行困难。我发现,当编码命令的长度超过916个字符时,它会失败,并显示以下消息:

Start-Process : This command cannot be run due to the error: The stub received bad data.
以下是我使用的代码:

$path = 'c:\temp'

$UserName = '.\someuser'
$Password = 'somepassword'
$securePassword = ($Password | ConvertTo-SecureString -AsPlainText -Force)
$credential = New-Object System.Management.Automation.PSCredential $UserName, $securePassword

$command = {& .\Restore-DatabaseFromBackupFile.ps1 -DatabaseName 'aaaaaaaaaaaaaaa' -DatabaseBackupFilePath 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' -DatabaseDataLogicalName 'aaaaaaaaaaaaaaa' -DatabaseLogLogicalName 'aaaaaaaaaaaaaaaaaaa' -DatabaseDataFilePath 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef' -DatabaseLogFilePath 'a';Start-Sleep -Seconds 2}
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
Write-Warning $encodedCommand.Length
Write-Warning $encodedCommand
Start-Process -FilePath 'powershell.exe' -ArgumentList "-ExecutionPolicy Unrestricted -EncodedCommand $encodedCommand" -WorkingDirectory $path -LoadUserProfile -Credential $Credential
此代码将失败。但是,如果从任何参数值中删除单个字符(或以任何方式缩短脚本块中的命令),它将成功执行

我发现有人提到,在Windows XP和更新版本(在Windows Server 2012 R2上运行)上,cmd.exe有8190个字符的限制,但我似乎离这个限制还有很长的路要走

有什么想法吗

**UPDATE1:此行为受-Credential参数的影响。如果我删除-Credential参数并作为当前用户运行,那么当编码的命令长度超过19000时,我就能够成功地执行该命令

**更新2:@Xalorus的评论确实解决了这个问题。将ExecutionPolicy设置为旁路。如果他/她能给出答案,我会很高兴给予表扬


谢谢

Try-ExecutionPolicy绕过而不是无限制。无限制对于设置本地或GPO的计算机或用户策略很有意义。命令行

Try
-ExecutionPolicy Bypass
而不是Unrestricted,这就没有什么意义了。无限制对于设置本地或GPO的计算机或用户策略很有意义。这对命令行来说没什么意义。如果你解决了你的问题,请将其作为你自己问题的答案发布。我没有解决我的问题,但我认为@Xalorous解决了。当我做出更改时,我能够在powershell窗口中以交互方式成功运行它。实际上,我正试图通过Azure自定义脚本扩展实现这一点,但仍然存在同样的问题。然而,Xalorus的建议似乎是我所发布问题的正确答案。我怎样才能正确地给予信任?我只是猜测,无法测试以验证我的建议是/否,所以我添加了它作为评论。我在下面复制了一个答案,可能是因为后者的字符较少,所以从“不受限制”改为“绕过”很有效。