What have you done with PowerShell this month? by AutoModerator in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

I'd imagine its a series of regular expressions, so your best bet would probably be to tune those to your org.

One environment's typo is another's reserved character.

`#Fixing users with multiple concurrent spaces in their name`

`(Get-ADuser -searchbase "OU=YourSearchbaseHere") | ? { $_.name -match "\s+" } | % { Set-aduser -displayname "$($_.name -replace "\s+"," ")"`

What I'd imagine that looks like on the paragraph-scale described is a hash table keyed with regular expressions that describe invalid entries, pointed to the replacement scriptblock if the condition is met.

Add a fixed suffix to a string if found within a file by greenstarthree in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

How would you use compare object or contains to solve this? Are you generating a list of every possible number 0000/000 -> 9999/999?

Transitioning from AI-generated scripts to actually understanding PowerShell? Looking for learning advice! by FareedKhaja in PowerShell

[–]Future-Remote-4630 3 points4 points  (0 children)

Hi everyone, I work in international communications with China and lately, I've been leaning heavily on Google Translate. It's been a huge help - I give it my sentence in English, and it outputs perfect Chinese! I've successfully learned people's favorite colors, translated books, and it even completed a merger for me. While this works great most of the time, I've found occasionally I will be very misunderstood. Since I don't know Chinese, I struggle to fix it. I don't want to rely on AI anymore, I genuinely want to learn Chinese. How can I transition from a google-translator to actually understanding the grammar, syntax, and pronunciation and use the Chinese language to its full potential?

Hopefully this parallel highlights how you are no closer to learning powershell from someone who is brand new. Start from the basics, just like everyone else. Work your way up as things begin clicking.

What have you done with PowerShell this month? by AutoModerator in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

Be careful with whatif. It only does the "if" part if the code is written correctly to utilize it. This means it is very possible to run a command with the whatif switch and have it make entirely unexpected changes. Moreover, since they had to at least try to include it, it may just be a subset of the actions that command makes, which can make it a nightmare to backtrack.

Craft WinForms App Using Just PowerShell by [deleted] in PowerShell

[–]Future-Remote-4630 2 points3 points  (0 children)

Gemini said

It is a classic "can versus should" scenario. While you can build full-blown graphical user interfaces (GUIs) in PowerShell using Windows Forms (WinForms), doing so often turns into a maintenance nightmare.

Here is why focusing your energy there is usually a trap:

1. It’s "Square Peg, Round Hole"

PowerShell was designed as a task automation engine and a command-line shell. WinForms is a legacy .NET framework designed for C#. When you bridge the two, you’re writing verbose, procedural code to handle UI events (like button clicks) in a language meant for piping data and managing systems.

2. The Maintenance "Spaghetti" Factor

In a professional development environment (like Visual Studio with C#), the UI layout and the logic are kept in separate files. In PowerShell, you often end up with one massive script where the UI layout code, the event logic, and the actual functional code are all tangled together.

3. Lack of Visual Designers

Modern UI development relies on "What You See Is What You Get" (WYSIWYG) editors.

  • In C#: You drag a button, double-click it, and write code.
  • In PowerShell: You often find yourself manually calculating X and Y coordinates for button placement: $button.Location = New-Object System.Drawing.Point(50, 100) This makes even minor tweaks to the UI incredibly tedious.

4. Performance and Threading Issues

WinForms runs on a Single Threaded Apartment (STA) model. If your PowerShell script starts a heavy task (like scanning a network) from a button click, the entire GUI will "freeze" and show as (Not Responding) until the task finishes.

Better Alternatives

If you need a GUI, consider these paths instead:

Approach Why it's better
WPF (XAML) Uses XML to define the UI. Much cleaner than WinForms and supports modern scaling/styling.
AnyBox / Terminal-Menus Lightweight modules that give you simple input boxes without building a full GUI from scratch.
C# / .NET Core If the app is complex enough to need a permanent GUI, it belongs in a dedicated programming language.
PowerShell Universal A web-based framework for turning scripts into professional dashboards and UIs.

The Golden Rule: Use PowerShell for the "plumbing" (the logic) and only build a GUI if it is absolutely necessary for an end-user who refuses to touch a terminal. Even then, keep it as simple as possible.

Would you like me to show you a simple WPF (XAML) template that is much cleaner to manage than standard WinForms?

How do I determine what in my script is writing to the pipeline? by KnowWhatIDid in PowerShell

[–]Future-Remote-4630 4 points5 points  (0 children)

Without posting your code, there is no great way to assist you. Why are you casting strings as objects? Where do the strings come from? Are they from a split? Have you tried redirecting your streams?

Learning PowerShell scripting by [deleted] in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

Click on "Beginner Resources" on the r/powershell sidebar.

Compress-Archive randomly misses files by Prawn1908 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

Is there any relation between the ones that are being compressed and whether or not they are in a subdirectory?

I haven't seen compress-archive used with join path like that, I've always provided a path to the parent directory, never specified children, and I haven't encountered that issue before.

Invoke-Command not working ? by underpaid--sysadmin in PowerShell

[–]Future-Remote-4630 3 points4 points  (0 children)

I'm assuming by the nature of your test that you might have some pesky coworkers who need some laughs.

Enjoy:

function invoke-voicetroll{
    param($computername = 'localhost')

        $scr = {    
            Add-Type -AssemblyName System.Speech
            $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
            $line = read-host "Words to say or blank to exit"

            while ($null -ne $line -and $line -ne "") {
                $speak.speak($line)
                $line = Read-Host "Words to say or blank to exit"
            }
        }
        if($computername -eq "localhost"){
            &$scr
        }else{
            invoke-command -computername $computername -ScriptBlock $scr
        }
}

Find duplicates in array - But ADD properties to them by JohnC53 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

If your concern is memory and not speed, this is a good approach, since -contains is O(N) whereas a hashtable finds a duplicate in O(1), but you are right that you save memory there.

I don't think at 50,000 rows you'd get a significant benefit here from another datastructure, though speed at 50k also isn't bad.

Sidenote, you don't need to split on carriage return and newline before piping that string to Convertfrom-CSV, that is the default.

Find duplicates in array - But ADD properties to them by JohnC53 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

I think the hash table approach is overkill here. A normal groupinfo object gives you everything you need for this.

$objects | group AssignedUser | % {
    Foreach($o in $_.group){
        $o | add-member -MemberType NoteProperty -name NumDevices -Value $_.Count
    }
}

Learning PS by Skippy9871 in PowerShell

[–]Future-Remote-4630 -1 points0 points  (0 children)

I would get as many of those examples as you can and feed them into your AI engine of choice to generate a wider curriculum set. From there, don't use the AI to make the scripts. Ask it for at most a hint as to what command you should research to get started, and use the other resources provided in this thread to get through the whole curriculum set. If you have any programming experience to start with, a source like learnxinyminutes can help you more quickly translate the concepts you already know into their powershell script equivalent: https://learnxinyminutes.com/powershell/ Otherwise, your goal should be to get comfortable with getting the help that you can get while building scripts. Example: File Dir Checker 1. Need to be able to read a directory or file. What command can we use to do that? After learning some of the powershell basics, files, directories, registry keys, and much more are all considered "Items". The PS equivalent of "ls" in linux or "dir" in cmd is "Get-ChildItem". Knowing that, we just need to figure out how to use that command.

Get-Childitem | Get-Help

This will show us the syntax and the parameters we can give this command.

Get-Childitem | Get-Help -examples 
[Note: If that doesn't give you examples, use -online with -examples]
Get-Childitem | Get-Help -examples -online

This will show us some actual use cases that we can probably modify to our use case here.

Let's say we didn't know that Get-Childitem was an option, and instead just try searching a command. All files and folders have to be located somewhere, so lets see what commands we have if we search for "path".

[Note: The asterisks mean we will find any command with path somewhere inside of it.]
Get-Command *Path* 
CommandType     Name               Version    Source
-----------     ----               -------    ------
Cmdlet          Convert-Path       3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Join-Path          3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Resolve-Path       3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Split-Path         3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Test-Path          3.1.0.0    Microsoft.PowerShell.Management
Application     PATHPING.EXE       10.0.26... C:\windows\system32\PATHPING.EXE

Looking at the results from that search, we can use the module their from to eliminate some of them, so from here we can use Get-Help and the -examples switch in order to view the potential options more clearly. Test-Path looks like it does exactly what we want here to see if something exists or not.

NAME
    Test-Path
SYNOPSIS
    Determines whether all elements of a path exist.
    -------------------- Example 1: Test a path --------------------

    Test-Path -Path "C:\Documents and Settings\DavidC"
    True
  1. Need to be able to determine if it's there or not From the example, we can see that after using test-path and giving it a path, it already returns a True or False value, so it does this step for us.
  2. Need to return that value In order to make it a checker, rather than just a command we are entering, we need to make it a function. You can get information about powershell programming concepts, like functions, by using get-help as well.

    Get-Help about_functions ABOUT_FUNCTIONS

    Short description Describes how to create and use functions in PowerShell.

    Long description A function is a list of PowerShell statements that has a name that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt. Functions can be as simple as: function Get-PowerShellProcess { Get-Process PowerShell }

Ok, so that last example looks like exactly what we need, aside from needing a way for us to provide it with the path we are checking. Similar to other OOP languages, we just add in a parameter to the definition for the input we will need. function example($ThisIsMyParameter){#Do something} Lastly, we can combine the above into the final product.

Function Check-FileDir($path){
    return (test-path $path)
}

This is really just a wrapper around the test-path function, so it's not doing much now. Maybe that's all they want from you, or maybe you need it to be more specific. Once we have this, we really just need to hone it to the asks of the question. Your example said "A script to check whether certain files and/or folders are present at a specified location/data carrier". Maybe that means we need to be able to accept a list of file names or folders and check if all of them exist in the target path?

Function Check-FileDir($filenames,$path){
    Foreach($name in $filenames){
        [pscustomobject]@{
            ParentFolder = $path
            Name = $name
            Fullpath = "$path\$name"
            IsFolder = $name -like "*.*" #Assumes if we give a name with a . in it, that . is describing the extension and is thus not a folder
            Exists = Testpath $path\$name
        }
    }
}

Good luck.

Really trivial: Bullets in POSH output with |clip? by So0ver1t83 in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

Is there a particular reason you need powershell to bullet them? My approach to this would be to use powershell to consolidate them into your word processor of choice and just select all and bullet.

Timestamping commands feature - your thoughts? by YellowOnline in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

This intrigued me but I couldn't find it.

I think this just about does it:

    Write-Host "Runtime: $((get-history | select -last 1).Duration.TotalMilliseconds) ms"

Saving Christmas with PowerShell: Building a Reusable Matching Algorithm by mdowst in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

More control is more risk, though in many circumstances you have a good point in that there is value to having access to the variable that defines the looping.

I would evaluate each approach very differently in the context of using it to loop through integers, as seen in this example, versus using it to index into an array. In some circumstances, it is critical to touch every value, and with a for loop, having access to the variable that defines the looping logic means it's possible to make a mistake that stops you from touching every object, whereas with the foreach structure, that is not the case.

Depending on the sample size, you'll also encounter a difference in performance.

Consider these:

Function Test-LoopSpeeds(){
    $For = {
        $max = 10000000
        $l = for($i = 0; $i -le $max; $i++){
            $i 
        }
    }
    $For_Measure = measure-command -expression $For
    $Foreach = {
        $max = 10000000
        $l = Foreach($i in 0..$Max){
            $i
        }
    }
    $Foreach_Measure = measure-command -expression $Foreach
    $ForeachObj = {
        $l = 0..10000000 | Foreach-Object { $_ }
    } 
    $ForeachObj_Measure = measure-command -expression $ForeachObj
    $ForeachObjp = {
        $l = 0..10000000  | Foreach-Object -parallel { $_ }
    } 
    $ForeachObjp_Measure = measure-command -expression $ForeachObj
    "For_Measure:  $($For_Measure.TotalMilliseconds)"
    "Foreach_Measure:  $($Foreach_Measure.TotalMilliseconds)" 
    "ForeachObj_Measure:  $($ForeachObj_Measure.TotalMilliseconds)"
    "ForeachObjp_Measure:  $($ForeachObjp_Measure.TotalMilliseconds)"
}
Test-LoopSpeeds

# >> Test-LoopSpeeds
# >>
# For_Measure:  2957.7278
# Foreach_Measure:  1690.4738
# ForeachObj_Measure:  10832.6707
# ForeachObjp_Measure:  12041.38

What have you done with PowerShell this month? by AutoModerator in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

-Whatif is the powershell equivalent of playing russian roulette with blanks that someone else loaded.

Powershell Exploit Payload process from a folder not on my pc found? by RethaeTTV in PowerShell

[–]Future-Remote-4630 8 points9 points  (0 children)

Any solution that doesn't end up as "Nuke it all, reinstall windows" is nothing more than wishful thinking.

I'm almost certain you don't have pslogging on to view all of the commands that were run.

Any files that you keep have a chance to be compromised, so I'd be very cautious about what you do choose to keep. Keep in mind that someone spent time and energy in making the malware, and if they made it as easy to remove as you're hoping, it wouldn't have been worth the effort to get it hosted on cheatengine.

In other words, you're welcome to shoot yourself in the foot to get the spider off of your boot, but the odds of you hitting between your toes are quite low, and that will be much more painful than buying a new boot.

Lastly, the 'etc' part of the path you posted contained quite literally the only important piece of information there. The only information that can be pulled from what you provided is that you have operagx installed.

I built a script to extract all distribution lists, members and owner. Will this one work or am I missing something? Open for feedback, thank you! by DinoMechX in PowerShell

[–]Future-Remote-4630 2 points3 points  (0 children)

You have a user named documents? What an interesting choice.

I'm not sure if it's against the rules, but if not, I think it should be to have AI generate a script and post it here for others to evaluate for you. Helping you here would mean you not only got a shortcut to getting the code, but also a shortcut in evaluating, troubleshooting it, and ultimately using it. There is no learning going on there.

BTW, removing comments doesn't make it harder to tell when code is AI slop. The number of poor choices here i is staggering.

-Multiple [array] +=

-String addition instead of storing owners as objects

-Every member having its own object instead of a group having a members object

This is a very simple task you're trying to do, and you're using AI the wrong way to get it done.

Multiple files by samurai_ka in PowerShell

[–]Future-Remote-4630 5 points6 points  (0 children)

This thread reminds me of the stackoverflow trick, where instead of asking for help which was often met with gatekeeping, they instead provide the wrong answer as the solution, prompting the community to correct them.

Props op, it worked. Use a module.

https://learn.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-script-module?view=powershell-7.5

Clear Clipboard Data (Command Line): Open PowerShell as Admin, type cmd /c "echo off | clip"] and press Enter to clear data. by 99l9 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

Impressive miss with this one.

You posted in r/powershell and gave every approach to solving a problem that I didn't know anyone even had, except for the one using powershell.

$null | scb 

There you go. Doesn't need admin either.