Powershell - possible to insert variable or character in the middle of a variable result? - powershell

I'm trying to work out how to insert a variable that contains one character in the middle of a variable
For example:
$fullnameresult = 'John doe'
$comma = ','
write-output $full$($comma)nameresult
I am hoping for the output to be:
John,Doe
Apart from the obvious inserting comma into the $fullnameresult variable, is there another way of doing it? I know this might sound silly but theres a long story behind it and this is the easiest way I could think of explaining it

Related

How to identify a character in a string?

I am trying to write a Powershell code to identify a string with a specific character from a filename from multiple files.
An example of a filename
20190902091031_202401192_50760_54206_6401.pdf
$Variable = $Filename.Substring(15,9)
Results:
202401192 (this is what I am after)
However in some instances the filename will be like below
20190902091031_20240119_50760_54206_6401.pdf
$Variable = $Filename.Substring(15,9)
Results:
20240119_ (this is NOT what I am after)
I am trying to find a code to identify the 9th character,
IF the 9th character = "_"
THEN Set
$Variable = $Filename.Substring(15,8)
Results:
20240119
All credit to TheMadTechnician who beat me to the punch with this answer.
To expand on the technique a bit, use the split method or operator to split a string every time a certain character shows up. Your data is separated by the underscore character, so is a perfect example of using this technique. By using either of the following:
$FileName.Split('_')
$FileName -split '_'
You can turn your long string into an array of shorter strings, each containing one of the parts of your original string. Since you want the 2nd one, you use the array descriptor [1] (0 is 1st) and you're done.
Good luck

Powershell confusion about Variable

I am confused regarding variables.
I have code, where I have the following line:
$search = $Name.SelectedItem.Split('-')[$($Name.SelectedItem.Split('-').Count-1)]+'*'
This line does nothing else, as split up a selected item (I am working with a Dropdownbox) and transfers it to $search.
The funny thing is, it does exactly that, what I want it to do.
When I type $search, the result can be for example:
Rue de Rivoli*
When I continue in the code and use $search through several arrays, for some reason, it does not function, because it does not find anything in a foreach loop. I have no error message and even the Rue de Rivoli* existing in one of the arrays, it does not find anything.
When I replace the above code and give directly the name to the variable $search, as seen below
$search = 'Rue de Rivoli*'
my search in the array works.
What am I missing here? I am doing something wrong, but I do not know what it is, can someone help me please to understand?
Thank you very much,
Mike
As requested, here more of the code. It is a lot to deal with, that is why I shorten it.
Clear-Host
$search = $CreateNewUserFormDropDownBoxLocation.SelectedItem.Split('-')[$($CreateNewUserFormDropDownBoxLocation.SelectedItem.Split('-').Count-1)]+'*'
#$search = 'Rue de Rivoli*'
$AllLocations = (get-variable -Include USPennsylvaniaAve, USSixthStreet, USRodeoDrive, USOneMicrosoftWay,`
USNorthTantauAvenue, USMarketStreet, USMainStreet, USEmilyDrive,`
USCalle8, USBroadway, US18thStreetNW, UKOxfordStreet, UKDowningStreet,`
UKBondStreet, FRRuedeRivoli, FRChampsElysees, CHBahnhofstrasse,`
CA17thAvenue) | ? {$_.value -is [array]}
Foreach ($Array in $AllLocations)
{
if ($array.value -like $search)
{break}
}
$result = "`$$($array.name)"
$result
This is about to become a function and does nothing else, as from the selecteditem, it takes it apart and add's the * behind it, so I can search
for a name with a wildcard.
I have several arrays and therefore I included only the necessary ones. Next step is to loop through the arrays and as soon as it found the item, it stops and gives the result to result.
This is my test code and it runs and does what I want, besides the line after Clear-Host. The code is correctly resolved and added to $search but does not work.
Below that code of line, I have my cheat line, where I add directly the correct result to the variable and it works fine.
As commented, this should solve the problem.
(I'm adding this as answer too, so the OP can accept it. Otherwise this question will remain seemingly unsolved)
When hardcoding the search string $search = 'Rue de Rivoli*' works, but using a Split() to get the search string does not, then usually the string you obtain using the split is surrounded by whitespace characters. If you leave these in, the string will appear to look just fine, but when using as comparison it won't work.
If for instance the complete $CreateNewUserFormDropDownBoxLocation.SelectedItem string is:
"François Exemple - Rue de Rivoli"
Then, using $CreateNewUserFormDropDownBoxLocation.SelectedItem.Split("-")[-1] will return:
" Rue de Rivoli"
Note the space in front.
By simply performing a Trim() you will get rid of that space.
The line therefore should be:
$search = ($CreateNewUserFormDropDownBoxLocation.SelectedItem.Split('-')[-1]).Trim() + '*'

How to parse logs and mask specific characters using Powershell

I have a problem that I really hope to get some help with.
It's rather complex but I will try and keep my explanation as simple and objective as possible. In a nutshell, I have log files that contain thousands of lines. Each line consists of information like date/time, source, type and message.
In this case the message contains a variable size ...999 password that I need to mask. Basically the message looks something like this (its an ISO message):
year-day-month 00:00:00,computername,source, info,rx 0210 22222222222222333333333333333333444444444444444444444444455555008PASSWORD6666666666666666677777777777777777777777ccccdddddddddddffffffffffffff
For each line I need to zero in on password length identifier (008) do a count on it and then proceed to mask the number of following characters, which would be PASSWORD in this case. I would change it to something like XXXXXXXX instead so once done the line would look like this:
year-day-month 00:00:00,computername,source, info,rx 0210 22222222222222333333333333333333444444444444444444444444455555008XXXXXXXX6666666666666666677777777777777777777777ccccdddddddddddffffffffffffff
I honestly have no idea how to start doing this with PowerShell. I need to loop though each line in the log file, and identify the number of characters to mask.
I've kept this high level as a starting point, there are some other complexities that I hope to figure out at a later time, like the fact that there are different types of messages and depending on the type the password length starts at another character position. I might be able to build on my aforementioned question first but if anyone understands what I mean then I would appreciate some help or tips about that too.
Any help is appreciated.
Thanks!
Additional information to original post:
Firstly, thank you to everyone for your answers thus far, its been greatly appreciated. Now that I have a baseline for how your answers are being formulated based on my information I feel I need to provide some more details.
1) There was a question about whether or not the password starting position is fixed and the logic behind it.
The password position is not fixed. In an ISO message (which these are) the password, and all information in the message, is dependent on the data elements present in the message which are in turn are indicated by the bitmap. The bitmap is also part of the message. So in my case, I need to script additional logic above and beyond the answers provided to come full circle.
2) This is what I know and these are the steps I hope to accomplish with the script.
What I know:
- There are 3 different msg types that contain passwords. I've figured out where the starting position of the password is for each msg type based on the bitmap and the data elements present.
For example 0210 contains one in this case:
year-day-month 00:00:00,computername,source, info,rx 0210 22222222222222333333333333333333444444444444444444444444455555008PASSWORD6666666666666666677777777777777777777777ccccdddddddddddffffffffffffff
What I need to do:
Pass the log file to the script
For each line in the log identify if the line has a msg type that contains a password
If the message type contains a password then determine length of password by reading the preceding 3 digits to the password ("ans ...999" which means alphanumeric - special with length max of 999 and 3 digit length info). Lets say the character position of the password would be 107 in this case for arguments sake, so we know to read the 3 numbers before it.
Starting at the character position of the password, mask the number of characters required with XXX. Loop through log until complete.
It does seem as though you're indicating the position of the password and the length of the password will vary. As long as you have the '008' and something like '666' to indicate a starting and stopping point something like this should work.
$filePath = '.\YourFile.log'
(Get-Content $filePath) | ForEach-Object {
$startIndex = $_.IndexOf('008') + 3
$endIndex = $_.IndexOf('666', $startIndex)
$passwordLength = $endIndex - $startIndex
$passwordToReplace = $_.Substring($startIndex,$passwordLength)
$obfuscation = New-Object 'string' -ArgumentList 'X', $passwordLength
$_.Replace($passwordToReplace, $obfuscation)
} | Set-Content $filePath
If the file is too large to load into memory then you will have to StreamReader and StreamWriter to write the content to a new file and delete the old.
Assuming a fixed position where the password-length field starts, based on your sample line (if that position is variable, as you've hinted at, you need to tell us more):
$line = '22222222222222333333333333333333444444444444444444444444455555008PASSWORD6666666666666666677777777777777777777777ccccdddddddddddffffffffffffff'
$posStart = 62 # fixed 0-based pos. where length-of-password field stats
$pwLenFieldLen = 3 # length of length-of-password field
$pwLen = [int] $line.SubString($posStart, $pwLenFieldLen) # extract password length
$pwSubstitute = 'X' * $pwLen # determine the password replacement string
# replace the password with all Xs
$line -replace "(?<=^.{$($posStart + $pwLenFieldLen)}).{$pwLen}(?=.*)", $pwSubstitute
Note: This is not the most efficient way to do it, but it is concise.

Substitute only one part of a string using perl

I have an array that have some symbols that I want to remove and even thought I find a solution, I will like to know if this is the right way because I'm afraid if I use it with array will remove the character that I might need on future arrays.
Here is an example item on my array:
$string1='22 | logging monitor informational';
so I try the following:
$string1=~ s/\s{6}\|(?=\s{6})//;
So my output is:
22 logging monitor informational
Is the other way that best match "|". I just want to remove the pipe character.
Thanks in advance
"I want to remove just the pipe character."
OK, then do this:
$string1 =~ s/\|//;
This will remove the first pipe character in the string. (You said in another comment that you don't want to remove any additional pipe characters.) If that's not what you want, then I'd suggest telling us exactly what you do want. We can't read minds, you know.
In the mean time, I'd also strongly recommend reading the Perl regular expressions tutorial.

removing commas in postgresql query

I have a query:
SELECT phone,
to_char(appt_date,'MM/DD/YYYY'),
time_text,
staff_email || subject_line as title,
staff_wav,
agency_wav
FROM phone_dialer
that is sent to a csv file
That results in
9105554444,07/01/2011,08:30am,me#myemail.orgGADK082493,staffid0827,Coastal Counseling
or
9105554444,07/01/2011,08:30am,me#myemail.orgGADK082493,staffid0827,Smith, Bob
The "agency_wav" column could have a name of company. I have tried several ways to remove the comma between Smith, Bob and am failing miserably.
Can anyone steer me to a resolution?
Answer to title, since the body of the question is unclear.
Fastest way to remove commas from a string:
SELECT translate('Smith, Bob, foo,,,bar', ',', '');
Related answer addressing translate() / replace():
Looking for phone number containing a minus, like "123-456789"
If your surround your query with the syntax COPY () TO STDOUT WITH CSV; then it will construct the CSV output and automatically quote the field values that contain commas.
If you want to manually do it in the query, try replace(agency_wav,',','').
The preferred way to create CSV is to use COPY command.
If by some reason you don't want or can't use it, you just need make value returned in the column CSV friendly that is enclose value in double quotes and escape existing double quotes by duplicating them in the string. This will preserve correct value (that is all commas) but will not break CSV format.
SELECT phone,
to_char(appt_date,'MM/DD/YYYY'),
time_text,
staff_email || subject_line as title,
staff_wav,
'"' || replace(agency_wav, '"', '""') || '"'
FROM phone_dialer
This will produce the following line
9105554444,07/01/2011,08:30am,me#myemail.orgGADK082493,staffid0827,"Smith, Bob"
Note quoted value which has comma.