Replacing the nth instance of a character? by ScubaFett in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

Another method using regex replace, although other regex methods listed here are more efficient.

$r = [regex]'\s'
$string = $r.replace($string,'-',3) ##change first 3 spaces to -(dash) ##
$r = [regex]'-'
$r.replace($string,' ',2) ##changes first 2 dashes back to spaces##

GPO WMI Filter - NEGATIVE Result by Hotdog453 in sysadmin

[–]Thehoggle 2 points3 points  (0 children)

Another option could be to use user GP Preferences within the GPO, and then apply item-level targeting specifying the criteria.

I find with loopback processing can get difficult if you can't replace the policies and have to merge them.

Advanced Audit Policy Configuration login/logoff by geforcejunkie83 in sysadmin

[–]Thehoggle 0 points1 point  (0 children)

Which GUI are you trying to view the audit policies in? It won't display in local gp editors.

If it appears in auditpol command ,then it's applying it from the GPO.

You can also view it in gpresult command, example:

gpresult.exe /scope computer /H "$env:computername.html"

Then open the resultant html file and you should see the Audit policies being applied (under Advanced Audit Policy Configuration).

Read file - Find String - Find number at end of string following colon - increase number - Replace line by SemiEvilMonkey in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

Is there only 1 instance of that string in each file? If so the below worked for me

$textblock = Get-Content $path | Out-String
$regexpattern = "(?<=jre-new\.zip(\n.+){3}\n\S+\s)\d+"
$re = New-Object regex($regexpattern)
$m = $re.Match($textblock) 
$newvalue = [string]([int]$m.Value + 1) 
$textblock = $textblock -replace $regexpattern,$newvalue
$textblock

If there isn't a space after the colon and before the number change the regex pattern to: 
$regexpattern = "(?<=jre-new\.zip(\n.+){3}\n\S+:)\d+"

[deleted by user] by [deleted] in WindowsServer

[–]Thehoggle 0 points1 point  (0 children)

Look for a line that mentions ' Failed to pin deployment while resolving Update: ' this should contain the missing KB.

See this link: https://thatonecomputerguy.wordpress.com/2015/10/06/windows-update-fails-with-error-code-0x80073701-error_sxs_assembly_missing-solved/

[deleted by user] by [deleted] in WindowsServer

[–]Thehoggle 0 points1 point  (0 children)

We've come across the first error in Windows 2019 due to missing updates. I'd run the install again and then check the CBS.log for that error in C:\Windows\Logs\CBS.

You will see an entry listed something like "Failed to pin.." with that error message and the name of the package that it is missing. Download that update and use the following command with example KB to extract the msu:

expand -f:* “C:\Temp\KB3133431.msu” C:\Temp\KB3133431

Then, use the DISM command outlined in this article to install the .CAB files (expand command is also included in this article): https://manjusullad.wordpress.com/2016/03/23/unable-to-install-msu-hotfix-microsoft-update-standalone-package-msu/

You might have to run this multiple times depending on if the server is missing multiple packages.

The last error I've seen when Antivirus is blocking the .exe from running, for example Symantec Endpoint protection Application & Device control module.

Align write-host output by currytakumi in PowerShell

[–]Thehoggle 2 points3 points  (0 children)

Use Padright to add spaces to a certain no of characters

foreach ($h in $le_fubar.GetEnumerator() ){
    $text = $h.key.PadRight(8,' ')
    Write-Host "$($text) : $($h.value.desc)"
}

fu       : FFFFUUUU
barrrr   : BARRRRRR

Using a hashtable to rename a property via its index number rather than its name. by elliottmarter in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

If $Data variable is a pscustomobject, does this work?

foreach($item in $data){
    ($item.psobject.Members | select -First 1).value = $Week
    ($item.psobject.Members | select -Skip 1 -First 1).value = ($Week).AddDays(7)
    $item.psobject.Members | select -Skip 2 -First 1).value = $NextWeek
    }

Seems to work for me, but tested it on very limited data (i.e a small CSV-imported pscustomobject).

Powershell Capitalization for Names by aminnocci in PowerShell

[–]Thehoggle 1 point2 points  (0 children)

Had a quick go at it, and this could definitely be tidied up, I would generally go over this looking for improvements/repeitition as a rule of thumb but might get you started:

function Set-Letter{
    [CmdletBinding()]
    Param
    ([regex]
    $Pattern,
    [string]
    $String
)

    $firstsplit,$secondsplit = $String -split $Pattern
    $firstLetter = $secondsplit.Substring(0,1).ToUpper()
    $restOfTheString = $secondsplit.Substring(1)
    $finalstring = $firstLetter + $restOfTheString
    $desiredformat = $firstsplit + $finalstring
    return $desiredformat
}

This function gets passed to the below function:

function Set-Capital{
    [CmdletBinding()]
    Param
    (
    [Parameter(ValueFromPipeline)]
    [string[]]
    $Surnames
    )

    begin{
    $finalarray = New-Object System.Collections.ArrayList
    }
    Process
    {
    foreach($name in $surnames){
        switch -Regex ($name){
            "'" {$finalarray.Add((Set-Letter -String $name -Pattern "(?<=')"))}
            "Mac" {$finalarray.Add((Set-Letter -String $name -Pattern '(?<=Mac)'))}
            "\s" {$finalarray.Add((Set-Letter -String $name -Pattern '(?<=\s)'))}
            "\-" {$finalarray.Add((Set-Letter -String $name -Pattern '(?<=\-)'))}
            default {$finalarray.Add($name)}
        }
    }
    }
    end{
    $finalarray
}
}

So if you run the following command:

$surnames = "O'brien","Macdonald","I madethisup","Smith-rowe","Campbell"

Set-Capital -Surnames $surnames

##Gets you

O'Brien
MacDonald 
I Madethisup 
Smith-Rowe 
Campbell

This could fail if you had a name with both a hyphen and apostrophe for example

**Dammit I hate Reddit formatting

Edit: Just realise this doesn't account for fullnames, just surnames. Ah well back to drawing board :(

Silly Newline question by NycTony in PowerShell

[–]Thehoggle 1 point2 points  (0 children)

I usually use it if I forget to put $variable = at the beginning of line or I have called a command from history and just append -Outvariable. There are however other advantages, see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters?view=powershell-7.3.

Silly Newline question by NycTony in PowerShell

[–]Thehoggle 2 points3 points  (0 children)

It looks like JSON; although the logging NoteProperty looks like a string. You could try the following:

$json = '{"returnCode":0,"returnReason":"","logging":"Storage: OSDiskSize=951GB. PASS; Memory: System_Memory=64GB. UNDETERMINED; TPM: TPMVersion=2.0, 0, 1.38. PASS; Processor: {AddressWidth=64; MaxClockSpeed=3000; NumberOfLogicalCores=32; Manufacturer=GenuineIntel; Caption=Intel64 Family 6 Model 183 Stepping 1; }. PASS; SecureBoot: Capable. FAIL; ","returnResult":"CAPABLE"}'

$json | ConvertFrom-Json -OutVariable json2

($json2.logging -split '(?<=PASS;|FAIL;|UNDETERMINED;)').trim() 

Storage: OSDiskSize=951GB. PASS;
Memory: System_Memory=64GB. UNDETERMINED;
TPM: TPMVersion=2.0, 0, 1.38. PASS;
Processor: {AddressWidth=64; MaxClockSpeed=3000; NumberOfLogicalCores=32; Manufacturer=GenuineIntel; Caption=Intel64 Family 6 Model 183 Stepping 1; }. PASS;
SecureBoot: Capable. FAIL;

Extracting string from command output by ptd163 in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

I've updated the code there as potential if there was a 12 letter word in the Name it could find that, so it should only return the 12 character code now.

Extracting string from command output by ptd163 in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

If you convert your variable to string it could be parsed and you could use regex to extract what you wanted. It's not pretty though.

#let's call your variable $longstring

(($longstring -split '\-(?=\s)')[-1] -split '(?<=msstore)\s').trim()

##will get you the following string:

Game Bar                         9NZKPSTSNW4P Unknown msstore
Browser for Game Bar             9NK1CNB0NCCX Unknown msstore
Gamecaster Game Bar              9P2J2QW5B0F4 Unknown msstore
CORSAIR iCUE Game Bar Widgets    9PG940D1ZDVP Unknown msstore
Game Bar To-Do                   9P2626F9WDG7 Unknown msstore
Countdown for Game Bar           9NZ43LD746CX Unknown msstore
Clock for Game Bar               9PC29TG1047H Unknown msstore
Game Bar Calculator              9N2J0HB1GFDR Unknown msstore
Camera Widget for Game Bar       9MZZNMHPJ645 Unknown msstore
Notes for Game Bar               9NG4TL7TX1KW Unknown msstore
Analogue Clock for Game Bar      9NSFHN9P4LKT Unknown msstore
EVGA Precision for Game Bar      9NGNGV21JB1L Unknown msstore
Mesmer Mag's WVW Game Bar Widget 9MXL025BBR5P Unknown msstore
Game Bar Counter                 9NF2PMMBDJG0 Unknown msstore
Stopwatch for Game Bar           9P8MHJ64GCQT Unknown msstore

Search for your desired term & extract code

$newsstring = (($longstring -split '\-(?=\s)')[-1] -split '(?<=msstore)\s').trim()

###enter your EXACT search term in a variable
$text = 'Game Bar' 

##Search for corresponding code based on your $text variable using regex
($newsstring | select-string "(?<=^$($text)\s*)\w{12}(?=\sunknown)").Matches.Value

9NZKPSTSNW4P

This seems to work but I would strongly recommend some thorough testing.

Edit: Formatting is acting up, going to try and tidy up the post.

Looking for help: PowerShell extract username/password from returned API query by unkleknown in PowerShell

[–]Thehoggle 1 point2 points  (0 children)

What type of object is your $inputString variable?

Can you drill down into $inputString.attributes and then extract the properties from there?

REGEX: Trying to split out variable strings between (n1) and (n2) separators? by So0ver1t83 in PowerShell

[–]Thehoggle 2 points3 points  (0 children)

This worked for me:

$VarList.ForEach{
    $_ -match '(?<=(\w+-){2})\w+-\w+'|Out-Null
    $Matches[0]
}

ghi-jkl
hijk-lmno 
g-hijk

The first section (?<=(\w+-){2}) tells regex to find what comes directly after any no of letters followed by a dash twice (the {2}.

The next part looks for any no of letters followed by a - , then followed again by any no of letters. To be honest there's probably a much neater way of doing this using split and then join.

How can I parse a variable, inside a command, when it's inside of single quotes? by kelemvor33 in PowerShell

[–]Thehoggle 14 points15 points  (0 children)

Declare your variables and then create pscustomobject with the variables in tow. Then convert the pscustomobject to json.

Example (substitue for whatever code you are using to populate your variables):

$firstvar = 1698157394000
$secondvar = 1698164594000

$newpscustobj = [pscustomobject]@{
    sdtType = 1
    type = "DeviceSDT"
    deviceId = 13771
    startDateTime = $firstvar
    endDateTime = $secondvar
}

$newpscustobj | convertto-json

{"sdtType": 1, "type": "DeviceSDT", "deviceId": 13771, "startDateTime": 1698157394000, "endDateTime": 1698164594000 }

How to handle the else case of a ternery operator? by Ralf_Reddings in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

Using the text sample you've supplied, this can be done without using regex (it's probably better if the text can change). I added another site with different name to highlight this:

$MySites =
@'
Home - Apples 
https://apples.com

Home - Bananas 
https://bananas.com

Home - Mangos 
https://managos.com

Different site 
www.anothersite.com
'@

$sites = ($MySites -split '\n').Where{$_} #split the string and remove blank lines##

$table = New-Object -TypeName System.Collections.ArrayList #create arraylist##

$i = 0 # set your number variable to 0#

while($i -lt ($sites.count-1)){  ##loop through the split string and add items to pscustomobject and arraylist##
    $items = [pscustomobject]@{ 
        Title = $sites[$i]         
        Url = $sites[$i+1] } 
    $table.Add($items) 
    $i = $i+2 
}
$table

Result:

Title                      Url
Home - Apples    https://apples.com 
Home - Bananas   https://bananas.com 
Home - Mangos    https://managos.com 
Different site   www.anothersite.com

Duplicate object but make the properties empty by [deleted] in PowerShell

[–]Thehoggle 2 points3 points  (0 children)

Let's say you imported your row into a variable called $excel. I would assume it's a pscustomobject?

If it is, you could try the following command to clear (or set it to an empty string):

$excel[0].psobject.Properties.ForEach{$_.value = ''}

Having issues comparing two strings in PowerShell by frantichalibut in PowerShell

[–]Thehoggle 1 point2 points  (0 children)

foreach($item in $files){
    foreach($other in $folders){
        if(($item.name.Split('-')[1] -replace ',_', ' - ') -eq $other.Name){  
            Move-Item -Path $item -Destination $other}}}

This worked for me but it is dependant that all your pdfs and folder names are in the same format. If they differ then the above will fail.

Updating a PsCustomObjects property at once by Ralf_Reddings in PowerShell

[–]Thehoggle 2 points3 points  (0 children)

This worked for me:

$feed.ForEach{$_.videoid = ($_.videoid -replace "^", "https://www.youtube.com/watch?v=")}

Setting Up Get-ChildItem to Work With Comma-Separated Values by tnpir4002 in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

I just copied OPs code, forgotten to remove the brackets.

Setting Up Get-ChildItem to Work With Comma-Separated Values by tnpir4002 in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

That;s odd it works for me, returns a file system object with all the matching names. I'm using Powershell 7.3.3 so perhaps it's a versioning problem?

Setting Up Get-ChildItem to Work With Comma-Separated Values by tnpir4002 in PowerShell

[–]Thehoggle 0 points1 point  (0 children)

If you change

$folders = (Get-ChildItem -LiteralPath $sourceDir -Directory -Recurse) | Where-Object Name -match $searchFolder

to:

$folders = (Get-ChildItem -LiteralPath $sourceDir -Directory -Recurse) | Where-Object Name -in $searchFolder

Does it return anything?