Error: Missing expression after unary operator '-'.At line:1 char:2+ -E
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎01-30-2020 10:18 AM
Error: Missing expression after unary operator '-'.At line:1 char:2+ -E <<<< xecutionPolicy ByPass -NonInteractive -WindowStyle Hidden -command & {mode con lines=1 cols=9999; Set-Variable -Name 'SNC_isWmi' -Value $true -Scope Global; function printValues{Process{foreach-object{if($_.Properties){$a=$_.Properties}else{$a=$_.PsObject.Properties}foreach($p in $a){$o=$p.Name+' : ';if ($p.Value -is [Array]){$o+=[string]::Join(',', $p.Value);}else{$o+=$p.Value;}$o;if($p.Value -is [System.Management.ManagementBaseObject] -or $p.Value -is [System.Management.ManagementBaseObject[]]){'_EXTENDED_START:';$p.Value|printValues;'_EXTENDED_END!';}}}}}gwmi -namespace root/MSCluster MSCluster_Cluster -EA SilentlyContinue|select __CLASS,Name|printValues|format-list;gwmi -namespace root/MSCluster MSCluster_ClusterToResource -EA SilentlyContinue|select __CLASS,GroupComponent,PartComponent|printValues|format-list;gwmi -namespace root/MSCluster MSCluster_ClusterToNode -EA SilentlyContinue|select __CLASS,Antecedent,Dependent|printValues|format-list;gwmi -namespace root/virtualization/v2 Msvm_ComputerSystem -EA SilentlyContinue|select __CLASS,Name|printValues|format-list;gwmi -namespace root/virtualization Msvm_ComputerSystem -EA SilentlyContinue|select __CLASS,Name|printValues|format-list;gwmi -namespace root/MSCluster MSCluster_Resource -EA SilentlyContinue|select __CLASS,PrivateProperties,Name,Type|printValues|format-list;gwmi -namespace root\cimv2 Win32_ComputerSystem -EA SilentlyContinue|select __CLASS,Domain,Name|printValues|format-list;gwmi -namespace root\cimv2 Win32_OperatingSystem -EA SilentlyContinue|select __CLASS,Caption,Version|printValues|format-list;gwmi -namespace root/MSCluster MSCluster_Node -EA SilentlyContinue|select __CLASS,Name|printValues|format-list;'---SNC-SEPERATOR---REGISTRY-SECTION---';Get-ItemProperty -Path 'HKLM:/SYSTEM/CurrentControlSet/Services/Tcpip/Parameters' -EA SilentlyContinue|select PSPath,Domain,Hostname|format-list;}HRESULT: [-2147024894]
MID server Powershell version is 4.0
Here is the script Service Now is running:
- function getConfigurableParm {
- param([string]$variable, [string]$defaultValue)
- $value = [Environment]::GetEnvironmentVariable($variable)
- if (-not $value) {
- $value = $defaultValue;
- }
- return $value;
- }
- <# Benjamin Phan:
- This function should probably not be called outside of executeRemote, since this function depends on variables being set
- by executeRemote. We might want to refactor executeRemote so that this part is placed inline rather than in this function.
- I originally made it this way because it seemed easier to read, but really it should not be a function in case someone
- comes across it and tries to use it standalone.
- #>
- function launchWMI {
- param([string]$computer, [System.Management.Automation.PSCredential]$cred, [string]$sourceScript, [string]$scriptBlock, [switch]$copyScriptToTarget)
- $context = startImpersonation $cred
- $cmdLongline = "mode con lines=1 cols=9999";
- $cmdPowerShellPrefix = "powershell -ExecutionPolicy ByPass -NonInteractive -WindowStyle Hidden";
- # set some useful variables
- $varString = "Set-Variable -Name 'SNC_isWmi' -Value `$true -Scope Global; "
- # check if we have any variables we need to send to the remote session
- $remoteVarsVariable = Get-ChildItem -Path Env:SNCExecuteRemoteVars 2> $null
- if ($?) {
- $paramNamesString = $remoteVarsVariable.Value
- $vars = ($paramNamesString -split ",")
- # build up command containing variables and values to pass to remote session
- Foreach ($var in $vars) {
- $varObj = Get-Variable -Name $var
- $varName = $varObj.Name
- $varVal = $varObj.Value
- # only need to escape single quotes, double quotes are passed properly without escaping
- $escapedVarVal = $varVal -replace "'","''"
- $varString += "Set-Variable -Name '$varName' -Value '$escapedVarVal' -Scope Global; "
- }
- }
- # If we got a sourceScript as a file path and we should not copy the script to the target, run the script as script block.
- if ($sourceScript -and -not $copyScriptToTarget) {
- $scriptBlock = (Get-Content -path $sourceScript)
- }
- if ($scriptBlock){
- # If we get a string as a script block, attach the the command to make sure that the windows is large enough for long line and pass is as the powerlshell command
- $varCommand = "& {$cmdLongline; $varString $scriptBlock}";
- # escape the command for cmd
- # for sequences of backslashes followed by double quote, double the number of quotes
- # also convert any " to \""
- $escapedCommand = $varCommand -replace '(\\*)"', '$1$1\""'
- $command = "$cmdPowerShellPrefix -command `"$escapedCommand`""
- }
- else {
- # Create directories as needed and copy script to directory
- $pathExists = Test-Path -Path $remoteHomeDir
- if (-not $?) {
- throw "Failed to test the path $remoteHomeDir"
- }
- if (-not $pathExists) {
- New-Item -ItemType directory -Path $remoteHomeDir -Force > $null
- if (-not $?) {
- throw "Failed to create directory $remoteHomeDir"
- }
- }
- Copy-Item -Path $sourceScript -Destination $remoteScriptPath -Force -Recurse
- if (-not $?) {
- throw "Failed to copy script $sourceScript to target $remoteScriptPath"
- }
- # create a script on the target that contains the commands to set powershell params
- $paramFileGuid = [System.Guid]::NewGuid()
- $targetParamFileName = "executeRemote_params_$paramFileGuid.ps1"
- $remoteParamScript = "$remoteHomeDir\$targetParamFileName"
- $localParamScript = "$localHomeDir\$targetParamFileName"
- # add the home directory and script path to the parameters that are passed to the remote powershell process
- $varString += "Set-Variable -Name 'SNC_remoteScriptDirectory' -Value '$localHomeDir' -Scope Global; "
- $varString += "Set-Variable -Name 'SNC_remoteScriptPath' -Value '$localScriptPath' -Scope Global; "
- New-Item -ItemType "file" -Path $remoteParamScript -Force > $null
- Set-Content -Value $varString -Path $remoteParamScript -Force -Encoding UTF8
- $hasParams = $true
- $runParamsScript = "try { & $localParamScript; } catch {}"
- # Potential security issue: passing parameters to target through plain text
- $varCommand = "& {$cmdLongline; $runParamsScript & $localScriptPath $localParamScript}"
- $command = "$cmdPowerShellPrefix -command `"$varCommand`""
- }
- # Run script remotely
- try {
- # call launchProcess with -UTF8 so that unicode characters are brought back and put into the payload properly
- if ($launchProcessWaitTime) {
- launchProcess -computer $computer -cred $cred -command $command -UTF8 -secondsToWait $launchProcessWaitTime
- } else {
- launchProcess -computer $computer -cred $cred -command $command -UTF8
- }
- } catch [System.IO.FileNotFoundException] {
- throw;
- } catch {
- write-error $_.Exception.Message
- } finally {
- if (-not $scriptBlock){
- Remove-Item -Path $remoteScriptPath -Force
- if ($hasParams) {
- Remove-Item -Path $remoteParamScript -Force
- }
- }
- }
- endImpersonation $context
- }
- function executeRemote {
- Param([string]$computer, [string][Parameter(ParameterSetName='filePath')]$filePath, [string][Parameter(ParameterSetName='scriptBlock')]$scriptBlock, [boolean] $wmi, [System.Management.Automation.PSCredential]$cred, [switch]$copyScriptToTarget, [int]$launchProcessWaitTime)
- $targetBaseDir = getConfigurableParm -variable "SNC_base_dir" -defaultvalue "admin$\temp"
- $instanceName = getConfigurableParm -variable "SNC_instance" -defaultvalue "unregistered"
- $targetFileGuid = [System.Guid]::NewGuid()
- $targetFileName = "psscript_executeRemote_$targetFileGuid.ps1"
- $homeDir = "$targetBaseDir\$instanceName"
- $localHomeDir = "\\127.0.0.1\$homeDir"
- $localScriptPath = "$localHomeDir\$targetFileName"
- $remoteHomeDir = "\\$computer\$homeDir"
- $remoteScriptPath = "$remoteHomeDir\$targetFileName"
- if ($wmi) {
- launchWMI -computer $computer -cred $cred -sourceScript $filePath -scriptBlock $scriptBlock -copyScriptToTarget:$copyScriptToTarget;
- } else {
- $remotePs = CreatePSSessionWithComputerName -host $computer -credential $cred
- if ($remotePs) {
- # pass powershell_param_ variables to the remote session
- if ($SNC_REMOTE_VARIABLES) {
- $varNames = $SNC_REMOTE_VARIABLES -split ","
- Foreach ($varName in $varNames) {
- $value = (Get-Variable $varName).Value
- # only need to escape single quotes, double quotes are passed properly without escaping
- $escapedValue = $value -replace "'","''"
- $sbString = "Set-Variable -Name '$varName' -Value '$escapedValue'"
- $paramsSb = [scriptblock]::Create($sbString)
- Invoke-Command -Session $remotePs -ScriptBlock $paramsSb
- }
- }
- if ($copyScriptToTarget) {
- # copy the script to the target
- SendFileExecuteRemote -Path $filePath -Destination $localHomeDir -Name $targetFileName -Session $remotePs > $null
- # pass the directory of the script on target to the remote session
- $sbString = "Set-Variable -Name 'SNC_remoteScriptDirectory' -Value '$localHomeDir'"
- $paramsSb = [scriptblock]::Create($sbString)
- Invoke-Command -Session $remotePs -ScriptBlock $paramsSb
- # pass the path of the script on target to the remote session
- $sbString = "Set-Variable -Name 'SNC_remoteScriptPath' -Value '$localScriptPath'"
- $paramsSb = [scriptblock]::Create($sbString)
- Invoke-Command -Session $remotePs -ScriptBlock $paramsSb
- # Tell the remote that we're not using WMI
- $sbString = "Set-Variable -Name 'SNC_isWmi' -Value `$false"
- $paramsSb = [scriptblock]::Create($sbString)
- Invoke-Command -Session $remotePs -ScriptBlock $paramsSb
- # execute the script on the target
- $executeScriptSb = [ScriptBlock]::Create("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; & `"$localScriptPath`"")
- $output = Invoke-Command -Session $remotePs -ScriptBlock $executeScriptSb -ErrorAction Continue
- #remove the script on the target
- $removeFileSb = [ScriptBlock]::Create("Remove-Item $localScriptPath -Force")
- Invoke-Command -Session $remotePs -ScriptBlock $removeFileSb > $null
- } else {
- # execute the script on the target
- $output = Invoke-Command -Session $remotePs -FilePath $filePath -ErrorAction Continue
- }
- foreach ($out in $output) {
- # must use [Console]::WriteLine because [Console]::OutputEncoding is properly set to UTF8
- # Write-Host and Write-Output do not correctly pass unicode characters back to MID Java code
- [Console]::WriteLine($out)
- }
- } else {
- Write-Error "Failed to create remote Powershell Session"
- }
- }
- }
- function SendFileExecuteRemote
- {
- <#
- Author: Benjamin Phan
- 10/12/18
- Ripped from LaunchProc.psm1 with modifications.
- This Send-File takes in a Destination directory and a Name, which allows us to change the resulting file's name.
- The original Send-File sets the resulting file's name to be the same as the source file.
- Another difference is that this function does not use using:$variables, since this functionality does not seem
- to be supported in Powershell 2.0.
- We need this function inside this module because LaunchProc.psm1 is not imported into the Powershell session
- when we are on the WinRM code path.
- #>
- [CmdletBinding()]
- param
- (
- [string[]]$Path,[string]$Destination, [string]$Name, [System.Management.Automation.Runspaces.PSSession]$Session
- )
- process
- {
- foreach ($p in $Path)
- {
- try
- {
- if ($p.StartsWith('\\'))
- {
- Write-Verbose -Message "[$($p)] is a UNC path. Copying locally first"
- Copy-Item -Path $p -Destination ([environment]::GetEnvironmentVariable('TEMP', 'Machine'))
- $p = "$([environment]::GetEnvironmentVariable('TEMP', 'Machine'))\$($p | Split-Path -Leaf)"
- }
- if (Test-Path -Path $p -PathType Container)
- {
- Write-Log -Source $MyInvocation.MyCommand -Message "[$($p)] is a folder. Sending all files"
- $files = Get-ChildItem -Path $p -File -Recurse
- $sendFileParamColl = @()
- foreach ($file in $Files)
- {
- $sendParams = @{
- 'Session' = $Session
- 'Path' = $file.FullName
- }
- if ($file.DirectoryName -ne $p) ## It's a subdirectory
- {
- $subdirpath = $file.DirectoryName.Replace("$p\", '')
- $sendParams.Destination = "$Destination\$subDirPath"
- }
- else
- {
- $sendParams.Destination = $Destination
- }
- $sendFileParamColl += $sendParams
- }
- foreach ($paramBlock in $sendFileParamColl)
- {
- Send-File @paramBlock
- }
- }
- else
- {
- Write-Verbose -Message "Starting WinRM copy of [$($p)] to [$($Destination)]"
- # Get the source file, and then get its contents
- $sourceBytes = [System.IO.File]::ReadAllBytes($p);
- $streamChunks = @();
- # Now break it into chunks to stream.
- $streamSize = 1MB;
- for ($position = 0; $position -lt $sourceBytes.Length; $position += $streamSize)
- {
- $remaining = $sourceBytes.Length - $position
- $remaining = [Math]::Min($remaining, $streamSize)
- $nextChunk = New-Object byte[] $remaining
- [Array]::Copy($sourcebytes, $position, $nextChunk, 0, $remaining)
- $streamChunks +=, $nextChunk
- }
- $remoteScript = {
- param($dest, $fname, $len)
- if (-not (Test-Path -Path $dest -PathType Container))
- {
- $null = New-Item -Path $dest -Type Directory -Force
- }
- $fileDest = "$dest\$fname"
- ## Create a new array to hold the file content
- $destBytes = New-Object byte[] $len
- $position = 0
- ## Go through the input, and fill in the new array of file content
- foreach ($chunk in $input)
- {
- [GC]::Collect()
- [Array]::Copy($chunk, 0, $destBytes, $position, $chunk.Length)
- $position += $chunk.Length
- }
- [IO.File]::WriteAllBytes($fileDest, $destBytes)
- Get-Item $fileDest
- [GC]::Collect()
- }
- # Stream the chunks into the remote script.
- $Length = $sourceBytes.Length
- $streamChunks | Invoke-Command -Session $Session -ScriptBlock $remoteScript -ArgumentList $Destination,$Name,$Length
- Write-Verbose -Message "WinRM copy of [$($p)] to [$($Destination)] complete"
- }
- }
- catch
- {
- Write-Error $_.Exception.Message
- }
- }
- }
- }
- Labels:
-
Discovery
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎01-30-2020 10:38 AM
What version are you? If it's the lower versions of Madrid before I think patch 4 it could be related to the WMI change. There was a HI KB for it but they seem to have made it private:
But there were numerous issues due to a change to powershell 2.0. If you aren't on that version that I strongly recommend you open up a HI ticket as it's going to be very difficult to figure that out.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎01-30-2020 11:25 AM
New York. We haven't seen this error before upgrade...MID server is running 4.0 Powershell