Powershell EncodedCommand长度问题

Sea*_*ean 7 powershell

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

Start-Process : This command cannot be run due to the error: The stub received bad data.
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的代码:

$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
Run Code Online (Sandbox Code Playgroud)

此代码将失败.但是,如果从任何参数值中删除单个字符(或以任何方式缩短脚本块中的命令),它将成功执行.

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

有任何想法吗?

**UPDATE1:此行为受-Credential参数的影响.如果我删除了-Credential参数并以当前用户身份运行,那么当编码命令长度超过19,000时,我就能成功执行该命令.

**UPDATE2:@Xalorous的评论确实解决了这个问题.将ExecutionPolicy设置为Bypass.如果他/她会发布答案,我会很乐意给予肯定.

谢谢!

Xal*_*ous 0

尝试 -ExecutionPolicy Bypass 而不是 Unrestricted。无限制对于设置计算机或用户策略(本地或 GPO)有意义。对于命令行来说意义不大