r/PowerShell • • Jan 27 '25

Is `Get-Command` the best equivalent of `which`?

2 Upvotes

Me: How to do the equivalent of `which` in powershell?
Claude: `Get-Command program-name`

Weird syntax, but let's try: The path is too long and cuts off in the end (a path created by `winget` ...)

It turns out the equivalent of `which programm` is `(Get-Command program).Path`. Upper camel case with hyphen in brackets dot Path. Wtf microsoft?

Is `Get-Command` a weird name? Yes

Is `(Get-Command program).Path` easy to remember? No

Will I ever remember this syntax? Possibly not.

Do I feel encouraged to remember it? Definitely not.

Is there a simpler thing that does `which` on Windows/Powershell? This feels so weird.


r/PowerShell • • Jul 29 '24

Crowdstrike Installation Script

5 Upvotes

UPDATE!!!!
Below powershell commands works
C:\Users\Domain1\Desktop\Crowdstrike\WindowsSensor.MaverickGyr.exe /VERYSILENT /NORESTART /PASSIVE CID=[CID number]
I will try it now deploying to computers via sccm.

THANK YOU GUYS!

Hi. i need your help here.
I want to install crowdstrike without user interaction using powershell.
First , I run this command, it works but it have a user interaction
C:\Users\Domain1\Desktop\Crowdstrike\WindowsSensor.MaverickGyr.exe /VERYSILENT /NORESTART CID=[CID number]

The second commands i used was below:
C:\Users\Domain1\Desktop\Crowdstrike\WindowsSensor.MaverickGyr.exe /INSTALL /QUIET /NORESTART /PASSIVE CID=[CID number]
I dont know if it works because it doesnt give me any error.

Note: Once I succeeded on this. I will use the command to install crowdstrike using sccm

Thank you for any help.


r/PowerShell • • Jun 16 '17

Why PowerShell is so complicated?

1 Upvotes

Ok, this is how do you attache a disk to VM on Azure (according to Azure documentation).

$diskConfig = New-AzureRmDiskConfig -Location EastUS -CreateOption Empty -DiskSizeGB 128 $dataDisk = New-AzureRmDisk -ResourceGroupName myResourceGroup -DiskName myDataDisk -Disk $diskConfig $vm = Get-AzureRmVM -ResourceGroupName myResourceGroup -Name myVM $vm = Add-AzureRmVMDataDisk -VM $vm -Name myDataDisk -CreateOption Attach -ManagedDiskId $dataDisk.Id -Lun 1 Update-AzureRmVM -ResourceGroupName myResourceGroup -VM $vm

Why is this should be five lines? Can't it be simple? For example:

New-AzureRMVMDisk -VM nameofthevm -diskname nameofthedisk -type typeofthedisk etc.

I mean why PowerShell complicates things? After all it is command line tool that should make our life little bit easier.


r/PowerShell • • Feb 24 '25

Powershell not recognizing 'list disk' anymore

1 Upvotes

Goodmorning fellow PowerShell users,

Did you also wake up this morning with PowerShell not recognizing 'list disk' or 'list volumes' anymore as actual commands, or am I being victim of a Mandela effect?

Thank you.

EDIT: my bad. Must be sleep deprivation. I use it regularly. Completely forgot the DISKPART step. I don't know what to say. Thanks for your help guys


r/PowerShell • • May 29 '25

Question Should I learn C for learning? Where to go after finishing Powershell in a month of lunches?

0 Upvotes

So I'm close to finishing Powershell in a month of lunches and I got a lot out of it. My question is, where do I go from there? Powershell is a .net language if I remember correctly, Powershell is in itself a programing language and a lot of PS is centralized on doing some C Programming from what I have seen.

There is a follow up book called "Powershell Tooling in a month of lunches" but I guess I'm not sure if I should try to learn C first before diving into Tooling. Where can I go?


r/PowerShell • • Mar 15 '25

4x IFs statements...

1 Upvotes

Which would you do?

$age = 25
$planet = "Earth"
$isAlive = $true
$yes = $false

if ($age -ge 20) {
    if ($planet -eq "Earth") {
        if ($isAlive -eq $true) {
            if ($yes -eq $true) {
                Write-Host "Yes. This is a nested IFs statement"
            }
        }
    }
}

##########################################################################################

if (($age -ge 20) -and ($planet -eq "Earth") -and ($isAlive -eq $true) -and ($yes -eq $true)) {
    Write-Host "One-Liner if statement."
}

##########################################################################################

if (
    ($age -ge 20) -and
    ($planet -eq "Earth") -and
    ($isAlive -eq $true) -and
    ($yes -eq $true)
) {
    Write-Host "Splatter If statement"
}

I'm doing the 3rd one. My colleague prefers the 2nd one. We both hate the 1st one.


r/PowerShell • • Aug 31 '18

Why I love regex in Powershell scripts?

Thumbnail
self.sysadminblogs
0 Upvotes

r/PowerShell • • Aug 31 '19

Question I've picked up a virus/malware?

0 Upvotes

Whenever I launch powershell in Windows 10, I now get a message on screen that says:

"Try the new cross-platform PowerShell (https://)aka.ms/pscore6" - (parentheses added so that the link is not live)

As I am suspicious that powershell as a whole has been compromised, how can I download and replace powershell.exe with a valid version?


r/PowerShell • • Jun 17 '15

A MANAGER’S APPROACH TO SCRIPTING PROCESSES

Thumbnail
networksafely.wordpress.com
0 Upvotes

r/PowerShell • • Feb 23 '23

No luck with the LearnPowerShell subreddit, so...

0 Upvotes

Reposting here to try and get some help.

I need to write a script for class to create a new, local, non-admin user account. One of the requirements is that the script must accept an argument to accept the username. The example provided is: Powershell.exe -ExecutionPolicy Bypass -file .\AssignmentX.ps1 "steve"

What I'm having issue with is how to get the script to take the name argument. I was thinking that I could create a variable that contains the Read-Host cmdlet, but I haven't gotten that to work so far.

Any help would be gratefully appreciated.


r/PowerShell • • Jun 01 '23

STUPID AI IN POWERSHELL?

0 Upvotes

Hi, hello.

Some of you guys might recognize me from my previous posts, gloating on about my 3d ascii graphics I've done in PowerShell.

Me taking a break from PowerShell programming, because I was caught doing some "helpful" acts within school, I have come back!

I was bored a week ago, procrastinating my English essay, I fell into the deep rabbit hole of

Artificial intelligence!

With this sudden interest, it was evident what I wanted to make next.

Not sure if this is the first regardless considering I'm 15 and its in PowerShell 💀, idc.

Single-Nueral-PowerShell

Trained with linear regression training, and with one neuron,

It calculates the multiples of numbers,

$train = @(
    @(0, 0),
    @(1, 2),
    @(2, 4),
    @(3, 6),
    @(4, 8)
)

$train_count = $train.Length

function rand_float {
    return [float](Get-Random) / [float]::MaxValue
}

function cost($w) {
    $result = 0.0
    $n = $train_count

    for ($i = 0; $i -lt $n; $i++) {
        $x = $train[$i][0]
        $y = $x * $w
        $d = $y - $train[$i][1]
        $result += $d * $d
    }

    $result /= $n
    return $result
}

function dcost($w) {
    $result = 0.0
    $n = $train_count

    for ($i = 0; $i -lt $n; $i++) {
        $x = $train[$i][0]
        $y = $train[$i][1]
        $result += 2 * ($x * $w - $y) * $x
    }

    $result /= $n
    return $result
}

$w = rand_float * 10.0
$rate = 1e-1

Write-Host "cost = $(cost($w)), w = $w"

for ($i = 0; $i -lt 50; $i++) {
    $dw = dcost($w)
    $w -= $rate * $dw
    Write-Host "cost = $(cost($w)), w = $w"
}

Write-Host "------------------------------"
Write-Host "Made By JH1SC"
Write-Host "w = $w"

Therefore, its prediction ($w) would be 2! And not to mention works with even decimals, Even PI!!!

PSMultiNeural

It has multi-layered neural networks to calculate XOR logic gate, and or any other logic gate!

It uses backpropagation to train the neural network!!

surprisingly takes like 10 seconds to train with the defaults!

$num_inputs = 3
$num_hidden_neurons = 4
$num_outputs = 2
$learning_rate = 1
$num_iterations = 10000

Its too chunky to paste all the code but for an example:

$train = @(
    @(0, 0, 0),
    @(0, 1, 1),
    @(1, 0, 1),
    @(1, 1, 0)
      r1 r2 r3
)

Effectively, r1 and r2 being the two inputs, and then r3 being the outputs its trained on!

Here is a picture PSMultiNeuralXOR/Brains.png at main · jh1sc/PSMultiNeuralXOR · GitHub

Anyways thanks for reading lol

Staring my repo, would be kindly appreciated😀!

cause hard work and stuf


r/PowerShell • • Sep 17 '23

Question run .bat w/o a cmd window flashing

0 Upvotes

Hi,

I wrote a simple ps1 script and use a hotkey to run a .bat file that executes it.

Everything works fine, but: I'd like it to execute it in the background and not show a cmd window.

I researched and tried:

command = "powershell.exe -nologo -command C:/PS1-FILE-PATH"
set shell = CreateObject("WScript.Shell")
shell.Run command,0

And saved it as a .vbs script.

There aren't any windows popping up anymore, but the script doesn't work either.

I also tried -windowstyle hidden etc. but to no avail.


EDIT: I am curious as to why this got downvoted? Why is it frowned upon to ask questions?


r/PowerShell • • Dec 04 '23

Script to delete specified folders with input

0 Upvotes

Hey all.

We have user profiles roaming across various network shares for our virtual users, depending on their geographic location. For example:

\\share1\username\

\\share2\username\

\\share3\username\

I've been trying to figure out a script for our desktop support team so they can run it, get asked for the username and upon providing the name have it purge that profile folders at each share as shown above. This way, I don't have to rely on them remembering to clean things up at each location.

Any suggestions?


r/PowerShell • • Oct 08 '25

Effortless Directory Navigation in PowerShell

0 Upvotes

Set-FoundLocation: Effortless Directory Navigation in PowerShell

I just released Set-FoundLocation (alias: lcd) as part of my GenXdev.FileSystem PowerShell module, available on PSGallery.

Building on my recent Find-Item release (Reddit post here), this cmdlet makes changing directories a breeze. It searches for matching files or folders (with advanced filtering) and jumps to the first match's location. Great for quick navigation in large projects or drives.

Supports command completion (Tab or CTRL-SPACE) for easy discovery of matches.

Key Features

  • Fast Search: Multi-threaded, supports wildcards, recursion, content matching, file categories, size/date filters, exclusions, and more.

  • Flexible: Search directories only (default), files, or both. Handles symlinks, alternate data streams, and long paths.

Installation

Install-Module GenXdev.FileSystem
Import-Module GenXdev.FileSystem

Examples

# Jump to first directory matching pattern
lcd *.Console

# Find and change location to directory with file containing 'function'
lcd *.ps1 'function'

# Search files and change location to first match's directory
lcd *test* -File

Check out this demo video: YouTube

Full docs and source: GitHub | PSGallery

Feedback welcome!


r/PowerShell • • 12d ago

Question PowerShell rules for AI coding agent

7 Upvotes

We know that the default shell for AI coding agents is Bash/Python, but for people like me who use agents on Windows without WSL, I prefer to use PowerShell.

So I wrote these rules for AI coding agents to use PowerShell instead of Bash.

Do you think these rules are OK, or is there anything I might have missed?

# Global Rules

## Shell: PowerShell 7.x (`pwsh`) only

- ALWAYS set `shell_flavor: "powershell"` on `exec` (default is bash). Never use bash/sh/WSL/cmd; never nest shells (`bash -c`, `pwsh -Command`).
- Write PowerShell syntax. Use `workdir` instead of `cd ... &&`. Quote paths with spaces.
- Prefer native cmdlets (`Invoke-RestMethod`, `ConvertFrom-Json`, `Where-Object`, `Select-String`, `Get-ChildItem`, `Test-Path`, `Get-Content`) over `curl`, `jq`, `grep`, `ls`, `cat`, `test`.
- External tools (`git`, `mvn`, `docker`, `npm`) are fine; check `$LASTEXITCODE`.
- Bash → PowerShell: `VAR=x cmd` → `$env:VAR='x'; cmd`; `export` → `$env:`; heredoc → `@'...'@`; `/dev/null` → `$null`; escape char is backtick; single quotes = literal. Quote native args containing `,` or `.` (e.g. `"-Dtest=A,B"`).
- Complex logic: write a `.ps1` (`#Requires -Version 7.0`), never `.sh`.
- Use splatting for many parameters, `Write-Output` (not `Write-Host`), `-Encoding utf8` when writing files, `-LiteralPath` for paths with `[ ]`.
- Confirm with the user before destructive commands (`Remove-Item -Recurse -Force`); preview with `-WhatIf`.

## Token Economy

- Use dedicated `grep`, `find_file_by_name`, `read`, `edit` tools instead of shell for search/read/edit.
- Limit output: `Select-Object -First N`, `Get-Content -Tail N`, `Select-String -Pattern ... -List`/`-Context 0`. Never dump whole files or logs to the shell.
- Return only needed fields: `Select-Object Name,Length`, not full objects. Use `Format-List`/`Format-Table -AutoSize` only at the end and only when needed; avoid wide tables.
- Build/test output (`mvn`, `npm`, `docker`): add quiet flags (`mvn -q -B`, `--no-transfer-progress`, `npm --silent`), then show only failures/summary, e.g. `... 2>&1 | Select-String 'ERROR|FAIL|Tests run:' | Select-Object -Last 30`.
- Save long output to a temp file and read only the relevant lines; do not re-read files already read this session.
- Batch independent commands in one call; chain dependent ones with `&&` or `;`.
- Use `git diff --stat`, `git log --oneline -n 10`, `git status -sb` before full diffs.
- Be concise in replies: no restating the task, no summaries of unchanged code, no unrequested explanations.

r/PowerShell • • May 26 '18

Need some help with a script that will be a tattoo!

0 Upvotes

So this may sound weird but my girlfriend wants to get a tattoo and she likes the idea of powershell being on her body forever - I work in IT and she wants something that is a big part of my life to be on her. Plus she liked the color-formatting on atom. So who am I to object! The only thing is that powershell isn't exactly a romance language ...

So I have been racking my brain for something short, sweet, heartfelt, and cute.

Can anyone help me think of some things that aren't too cheeseball but maybe have some good hidden love meaning to them?

She is itching to get this done, so I can promise at least a followup with the work done within a short amount of time. Though I am not sure where she will get it done ... possibly her side I would guess so maybe we all get some powershell side-boob!

Edit:

I didn’t realize how toxic and absolutely horrible miserable assholes some of you could be. I genuinely feel sorry for you and I hope you find some kind of happiness in your lives.


r/PowerShell • • Jul 12 '26

Question Just a question.... can we use sudo on windows like i do in linux like even 70% of the way ????

0 Upvotes

I'm kinda new to homelabbing. I have one dedicated Ubuntu server and another PC that's dual booted with Windows 10 and Ubuntu. The second machine is both my workstation and a server depending on what I'm doing.

I've been spending a lot more time in Linx recently and I've gotten really used to working from the terminal. I SSH into my servers, manage Docker, edit configs, etc., so typing sudo has become second nature.

I still need Windows because of a few applications, so I can't switch completely. The thing I miss the most is being able to elevate a single command with sudo instead of opening a whole Administrator terminal.

Is there any tool or workflow you guys use to get something similar on Windows? Doesn't have to be identical, just wondering what other people who have dual booted do?


r/PowerShell • • Mar 21 '24

Question Is 'irm https://massgrave.dev/get | iex' safe?

0 Upvotes

Is running the command 'irm https://massgrave.dev/get | iex' in terminal(admin) safe at all, or is there a virus hidden somwhere in this


r/PowerShell • • Jul 05 '17

Supercharge your PowerShell scripts with these five easy tips.

2 Upvotes

I am writing this from my phone, so Google is your friend here when looking for examples on how to quickly implement these. If enough folks are drawing a blank I will update this post with examples for each.

1: Replace Get-Content and Import-CSV with .NET's StreamReader.

Examples:

https://www.google.com/amp/s/amp.reddit.com/r/PowerShell/comments/2ey9fk/using_ps_to_search_a_huge_file_for_matching_lines/

http://www.happysysadm.com/2014/10/reading-large-text-files-with-powershell.html?m=1

2: Replace Out-File and Export-CSV with .NET's StreamWriter.

Examples:

https://stackoverflow.com/questions/13855788/powershell-fastest-way-to-write-large-body-of-text-to-a-file

3: Replace Compare-Object with the Match operator using the GetHashCode() method for strings being compared, or for a RegEx generated at runtime.

Examples:

https://blogs.technet.microsoft.com/heyscriptingguy/2011/02/18/speed-up-array-comparisons-in-powershell-with-a-runtime-regex/

https://blogs.technet.microsoft.com/heyscriptingguy/2015/04/01/use-powershell-to-compare-two-files/

4: Replace Get-AD* with ADFind from JoeWare.NET.

Examples:

http://powershell-guru.com/fastest-powershell-1-count-all-users-active-directory/

5: Replace Set-AD* with ADMod from JoeWare.NET.

EDIT: Yay, downvotes because knowledge is power and power is bad.


r/PowerShell • • May 20 '23

" | Get-member" is great, but I prefer “ | format-list *" ?

0 Upvotes

This is more for beginners, like me.

Whenever I’m trying to drill down on object properties, I was told to pipe to Get-Member, but it only shows property names. I accidentally discovered that piping to Format-List * shows actual values, which is much more useful.

So

‘’’$variable | Get-Member’’’

Becomes

‘’’$variable | fl *’’’


r/PowerShell • • Feb 06 '25

Solved Creating a GPO that adds a user to localadmins

1 Upvotes

Hello, i have to give local admin rights for each user to their designated machine. for that my plan was to dynamically add a gpo for each user that gives the machines that that user "owns" that user, that user as localadmin. the wish of my superiors was to be able to manage it via the Active directory. the last hurdle is to actually dynamically set the action the gpos. i have seen that some gpo actions use registry keys but i couldnt find any for local user accounts. i already have creation and deletion and linking covered. any advice?


r/PowerShell • • Jan 28 '25

PS-based alternative to File Explorer?

1 Upvotes

In a nutshell, my work computer is massively locked down - except, strangely, for scripting.

I wasn't clear with my intiial post. I cannot install an EXE on my computer. That is why I am looking for a script-based solution.

I need the intervention of a team of IT, plus the sacrifice of a live Mountain Dew, to compile code from my company-installed Visual Studio, but I can grant myself permission to run PS scripts without any safety brakes (and Batch and VBS, for that matter).

Franky, I'm dying for a dual-window file explorer. That would be a serious upgrade to my life. Does such a thing exist?

A file-search functionality that doesn't suck as much as File Explorer's version would be nice, too. If I search for "May" in my Documents folder, I probably do not want every single file containing the verb "may" in it - but FE will return just that.

Does such a thing exist?


r/PowerShell • • Jul 02 '21

Question Powershell password manager?

1 Upvotes

Hey all. Have non-admin powershell at work. IT is slow here due to being quite busy, but PS is available. 5.x. Would like a program like keepass for my engineering group (we have a lot of logins and people write them in text files), but even the portable version is locked down (no unapproved exe) - would there be a sensible way to approximate keepass for a normal user via a PS script without admin access?


r/PowerShell • • Apr 15 '23

How to create a powershell script that will look in the eventlog for someone is authenticated from the cloud server?

1 Upvotes

I would appreciate for the help