r/PowerShell • • 30m ago

Question InstallAnywhere logging with PS?

• Upvotes

Hey All,

Does anyone have any experience with InstallAnywhere installers? Weve got some agent upgrades to do, and during our pilot group we ran into some strange failures. We tried to setup logging, but were pretty crunched for time so decided it was a next week problem.

The issue weve found is that InstallAnywhere doesnt advertise its processes the same way an MSI does, so you have to do some janky stuff.

Ive tried passing -RedirectStandardOutput and StandardError to a log file, but theyre either empty, or dont generate at all.

If anyone has any advice or any documentation they can point to thatd be awesome.

Thanks!


r/PowerShell • • 6h ago

Solved Converting PowerShell Scripts from Search-UnifiedAuditLog

6 Upvotes

Investigating the work necessary to convert PowerShell scripts based on the Search-UnifiedAuditLog cmdlet to use the AuditLogQuery Graph API shows that it’s not easy. Running audit jobs is a multi-stage process rather than running a simple cmdlet. Parameter values are now passed in a request body or different named parameters, and the properties output in the AuditData payload use a different format. This is definitely not a drop-in exercise, so it’s time to get ready by finding scripts that need to be converted.

https://office365itpros.com/2026/10/27/auditlogquery-conversion/


r/PowerShell • • 13h ago

Information Just released Servy 10.7 - New architecture, per-service isolation, new PS module features, and bug fixes

10 Upvotes

It's been about two months of hard work since my last post about Servy here, and I wanted to share this release, which includes an architecture redesign, per-service isolation, automated ACL hardening, new PS module features, and bug fixes.

If you haven't heard of Servy before, it's a tool that lets you run any app as a native Windows service with real-time monitoring and advanced recovery options. It comes with a GUI, a CLI, and a PS module.

What I've added/updated from v10.0 (last post on r/PowerShell) to v10.7 (current version):

  • Full Per-Service Security Isolation: Custom service accounts can no longer read or modify other service configurations, runtime states, or logs. Decryption and database access are now proxied through the isolated Servy host Windows service (Servy.Host.exe) via a DACL-restricted local Named Pipe.
  • Per-Service Log Isolation: Each wrapped service now writes its wrapper and restarter logs to an isolated subfolder (%ProgramData%\Servy\logs\services\<ServiceName>\). Custom service accounts hold permissions strictly within their own log subfolder and cannot access or tamper with logs from other services.
  • Automated Vault & Binary Hardening: Servy now automatically enforces strict ACL lockdown rules on the %ProgramData%\Servy root vault and core binaries (.exe/.dll), removing the need for manual sysadmin hardening scripts or elevated permission setups.
  • New Show-ServyService and Show-ServyServices PS Functions & CLI show Command: Inspect and print service configurations directly from the terminal in a clean, human-readable format.
  • Servy Manager: Improved user experience, including the ability to show or hide columns in the Services and Logs grids by right-clicking a column header (with preferences automatically saved across sessions), an optional Display Name column in the Services grid, and double-clicking a service row to open its configuration.
  • Third-Party Tools: Replaced handle64.exe / handle64a.exe with native P/Invoke, eliminating all third-party executable dependencies and licensing constraints.
  • Bug Fixes: Fixed many issues across the CLI, PS module, Windows service wrapper, core components, and GUI.
  • Documentation Updates: Added a new walkthrough for embedding Servy into custom installers, and updated docs.

Check it out on GitHub: https://github.com/aelassas/servy

Any feedback is welcome.


r/PowerShell • • 1d ago

Question Retiring Powershell ISE

29 Upvotes

I really don't like VS Code for Powershell but PS 5.1 and PS ISE is starting to get long in the tooth. Anybody have tips, tricks, custom configs, or other recommendations?

Funny enough I really like VS code for everything else except PowerShell.


r/PowerShell • • 1d ago

Question Beginner looking for help in a sea of Regex

8 Upvotes

So I discovered how useful Powershell is about 3 weeks ago and have been playing with it and tweaking my PC with all manner of useless changes. I have reached something that has left me rather stumped even after a fair bit of Googling (AI results disclosure?) and several hundred changes of my 'script'. Posting here is probably like whacking a mole with a warhead but hey why not!

I have been attempting to change a subtitle file with several thousands of lines of text, they all follow the following pattern:

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(540*,420)}Hello world!\N*

I would like to add 140 to all of the first numbers after "{\pos(" (e.g 540 becomes 680.)

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(680*,420)}Hello world!\N*

I have been attempting to do this by loading the .ass text file in (this'll be part of a batch file so I am calling Powershell from CMD), then using the -replace function as follows:

powershell -Command "((Get-Content -path <path to sub.ass> -Raw) -replace '\{\\pos\(\d+,','\{\pos\(${140 + \d+},') | Set-Content -Path <path to sub.ass>"

However this results in the following results for all lines of dialogue:

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,\{\pos\(,420)}Hello world!\N

This is one of the more promising results where {140 + \d+} simply vanished. Without the $ in front of {140 + \d+} Powershell will simply repeat whatever code I put into into it back at me in place of \d+ like so: {\pos\({140 + \d+},420)}

I suspect that because I am attempting to isolate a number by using the surrounding punctuation the program is reading \d+ as a string rather than an integer.

TLDR: I am attempting to increase the value of the same integer on every line of text by 140 using \d+. \d+ could be any number from 0 to 1540. Not using \d+ is fine but I have no idea what other options are available.

Pointing me in the direction of what I should learn to get this to work could also be great as this is actually a pretty enjoyable program - I just think I went a little too deep too fast with this one.


r/PowerShell • • 2d ago

News PowerShell ISE

0 Upvotes

After a month of refinement, I have a new version of my App in the MS Store.
I received some feedback and a lot suggestions, plus more than a few bug issues.

It is now more like a true PowerShell console than the emulator it was before. There should not be any more unrecognized PS commands. It is still a WIP but it is definitely close to a Daily Driver for running scripts and debugging.

I actually prefer it now than opening a PWSH console.

The debugging sub-system has been hardened and more responsive. I am adding output options to make automated script running easier. The save as EXE works, I am going to be adding .NET level options to the executable next.

Once again. If anyone would like to give it a try and provide feedback, it is most welcome.

It can be found by searching for PS7ScriptDesk in the MS store.

Regards,

-Ron


r/PowerShell • • 4d ago

Question Automated QuickBooks Updates (Not Upgrades)

1 Upvotes

OK So this is going to sound crazy (kinda?) and I understand it is likely not an option based on what I know of the underlying application after nearly 10 years of working with it. I am hoping that someone in the wider world of Reddit has already come across a solution and is willing to share.

We (the company I work for) support a tax prep/accounting firm that has 2 RDS servers that are used to access accountant copies of QuickBooks Company Files. They use a variety of application versions from 2021 to 2024 (Accountant, Premier, and Enterprise distributions). During tax season, they are incredibly busy and as a result, have asked us to schedule application updates every Thursday evening along with updating their Thompson Reuters applications.

Personally, I don't like taking a couple hours out of my day when I'm on call to work after 7PM to update QuickBooks since they use all the versions depending on the client they are prepping taxes for. I am also in charge of making manual tasks automated wherever possible.

So, here's what I am looking to accomplish:

  1. Scripted updates of installed QuickBooks versions without the need to open each distro and check for updates. (automated updates are already enabled, still doesn't actually install the updates until we go in and tell it to do them which sucks hard).

  2. The script needs to be capable of recursively identifying the installed versions, exporting a response of all versions found and then go through and check for updates, install any updates found, and log any errors. It should also be capable of stopping and restarting any and all QuickBooks related services as needed and restart the server following the completion of the scripted tasks.

  3. This is for updates NOT upgrades - there is a difference.

  4. I would like to avoid using third party software to accomplish this - we already have ImmyBot but that platform appears to confuse the "upgrade" and "update" functions.

Here are the things I am already well aware of so don't comment if you feel the need to point out the below facts:

  1. QuickBooks does NOT come with known, publicly available scripted/command line options for this specific function.

  2. Non-current QuickBooks versions are not something I care about - if Intuit still pushes updates to the application, I don't care if it isn't a "current" distro version. (We are working with the last 5 years or so of distros, nothing older than that and those are still getting updates so far as I am aware.)

  3. QuickBooks online is not an option for this client's clients - please don't suggest that as an alternative, I've already been there done that.

  4. The servers are RDS servers - yes they have issues but these are not the worst of the servers we currently support.

  5. I would REALLY love to not have to take the code from a company that has a paywall to access because honestly that just feels gross. This is also why I am not taking the code I have access to via ImmyBot and running it through CoPilot or another AI platform to remove the references to another company's probably proprietary code. I don't want to steal anything from a company that has put effort into the solution.

Please let me know if you have come across this issue and/or have found a solution that you are willing to share with me via github or other sharing platform. If you are not authorized to share this info, please don't.

I would also appreciate any scripts be coded in either a batch file or (preferably) a powershell script. :) Thanks in advance!


r/PowerShell • • 4d ago

Solved Free read-only script: quick security check for small-business M365 tenants

1 Upvotes

Small M365 tenants tend to get the same handful of settings wrong: no MFA enforcement, legacy auth still open, users allowed to consent to any app, “Anyone” sharing links switched on. I wrote a script that checks eight of these and spits out an HTML report with the fix next to each failure.

It only asks for read scopes through Microsoft Graph and doesn’t change anything. It’s about 230 lines, so it’s easy to read before you run it.

https://github.com/thecyberape/m365-quick-check

Disclosure: it’s a cut-down version of a longer audit script I sell alongside a book. The README says so. The free one is MIT and complete on its own, so use it however you like.

Would appreciate feedback, especially from anyone who runs it against Business Basic/Standard tenants. I’d like to know which checks come back INFO instead of PASS/FAIL there.


r/PowerShell • • 4d ago

Question Environment stopped handling large files

1 Upvotes

Edit: To everyone who responded. You've given me some good ideas, and now I have to experiment to track down where the issue lies. Thanks to all.

I have a workflow which takes a comma delimited text file (*.txt) and updates an Azure database with the values. The workflow is called by a PowerShell script on a remote Windows Server, which looks to a folder and finds all the txt files in there, and runs the workflow against each one. This process worked fine for about two years. Then last spring, I started getting reports from our users that not all the values that should be updated in the database where. No one changed the workflow, and no one changed the PowerShell script.

After a lot of testing, we found that if the txt file was larger than 2K, only the first 2K worth of lines in the file were processed, and everything after was ignored.

On the suggestion of a consultant, he had me run the PowerShell script which calls the workflow from my own laptop. Yes, I had to duplicate the folder structure to make that happen. Much to my surprise, running the script and workflow from my laptop worked just fine.

So I started looking into what in the environment of the Windows Server would limit the ability to pass all the necessary data to the workflow. Of course our server teams swears they did nothing to the server, no updates that would cause this restriction. But I don't trust them to know what the consequences of their actions would be.

After half a year of cutting the text file down into 2K chunks every week (I automated the process, but still), I am again trying to find what the cause of this could be. Script works fine on my laptop, but choaks at 2K file size when run on a Windows Server. The server is more than powerful enough in terms of memory, processor and disk size.

If you have any clue, please pass it on.


r/PowerShell • • 4d ago

Information Struggling to learn Microsoft Graph PowerShell for IAM-how did you guys learn it

68 Upvotes

Hi everyone,

I’m currently learning PowerShell with Microsoft Graph because my goal is to become a Junior IAM / Microsoft Entra ID Administrator.
I’ve been practising in my own Microsoft Entra ID lab, and so far I’ve managed to learn some basics, such as:
1)Connecting to Microsoft Graph using PowerShell
2)Creating, updating and deleting users
3)Creating and managing security groups
4)Adding and removing users from groups
5)Retrieving and filtering users
6)Working with variables, arrays, hashtables and loops

However, I’m starting to struggle and slowly losing interest, not because I don’t want to learn, but because sometimes I feel like I’m just memorising commands without fully understanding how to use them in real-world situations.
I can follow tutorials and complete exercises, but when I try to do something on my own, I sometimes get stuck and don’t know which commands to use or where to start.
My goal isn’t just to memorise PowerShell commands. I want to understand how an IAM administrator actually uses Microsoft Graph PowerShell in their daily job.

For those of you who learned PowerShell, especially for Microsoft Entra ID or IAM:
How did you learn PowerShell and become confident using it?
Did you learn the general PowerShell fundamentals first, or did you learn while working with Microsoft Graph?
What practical projects or exercises helped you the most?
How do you remember commands and know which ones to use when solving a problem?
What would you recommend to someone preparing for their first Junior IAM Administrator role?
I’m willing to put in the time and effort. I just feel like I need a better learning approach that will help me understand what I’m doing instead of simply following instructions.
Any advice, learning resources or personal experiences would be greatly appreciated.
Thanks in advance!


r/PowerShell • • 5d ago

Question Comparing STIG CKL files with PowerShell

2 Upvotes

I'm trying to automate our monthly STIG reviews by comparing new CKL files against a known good baseline.

The goal is to generate a report showing only changed finding seo so we don't have to manually review every CKL in STIG viewer.

I'm looking at parsing the CKL XML and using Compare Object but i'm still new to XML in PowerShell.

Has anyone built something similar or know of a PowerShell module taht can compare CKL files and report changed findings?


r/PowerShell • • 5d ago

Question Exchange (Online) Powershell auto-forward and auto-reply

9 Upvotes

Ok, I need some help with Powershell.

Part of our company got sold. This weekend, the migration is set to go through. All users that are part of this transfer will login into the new owners IT infrastructure and their 365 tenant starting next monday. The mailbox contents will be synced and for the next few weeks all incoming e-mail needs to be auto-forwarded to the user's new mailbox in the other tenant. And a auto-reply will be sent to the sender informing them of the upcoming discontinuation of the old e-mail address.

So, all e-mail coming in to 'olduser' needs to be forwarded to 'newuser' and newuser is in another tenant. To prevent double e-mail, 'olduser' should not be seeing the e-mail in their inbox.

Currently this is what I have, being run from Exchange Management shell connected to Exchange Online

$Users = Import-Csv "c:\temp\usermailboxentest.csv" -delimiter ";"

foreach ($User in $Users) {

    Set-Mailbox -Identity $User.adresold `
        -ForwardingSmtpAddress $User.adresnew `
        -DeliverToMailboxAndForward $false
}

And then, I run this

$CsvPath = "C:\Temp\mailboxes.csv"

$StartTime = Get-Date
$EndTime   = [datetime]::new(2026, 12, 30, 23, 59, 59)

$Results = foreach ($CsvUser in Import-Csv -Path $CsvPath) {

    $MailboxAddress = $CsvUser.MailboxAddress.Trim()

    try {
        Write-Host "Processing: $MailboxAddress" -ForegroundColor Cyan

        # Retrieve the mailbox
        $Mailbox = Get-Mailbox -Identity $MailboxAddress -ErrorAction Stop

        # Determine the configured forwarding address
        if ($Mailbox.ForwardingSmtpAddress) {

            # Forwarding to an SMTP address
            $ForwardAddress = $Mailbox.ForwardingSmtpAddress.ToString() `
                -replace '(?i)^smtp:', ''
        }
        elseif ($Mailbox.ForwardingAddress) {

            # Forwarding to an internal Exchange recipient
            $ForwardRecipient = Get-Recipient `
                -Identity $Mailbox.ForwardingAddress `
                -ErrorAction Stop

            $ForwardAddress = $ForwardRecipient.PrimarySmtpAddress.ToString()
        }
        else {
            throw "No mailbox-level forwarding address is configured."
        }

        Write-Host "Forwarding address: $ForwardAddress" -ForegroundColor Green

        # Create the HTML automatic-reply message
        $AutoReplyMessage = @"
<p><strong>Dear Sender,</strong></p>

<p>
This email address has been discontinued etc. etc etc. and a variable for $ForwardAddress pointing the user to whatever the new e-mail address is.
</p>
"@

        # Configure automatic replies for internal and external senders
        Set-MailboxAutoReplyConfiguration `
            -Identity $MailboxAddress `
            -AutoReplyState Scheduled `
            -StartTime $StartTime `
            -EndTime $EndTime `
            -InternalMessage $AutoReplyMessage `
            -ExternalMessage $AutoReplyMessage `
            -ExternalAudience All `
            -ErrorAction Stop

        Write-Host "Automatic reply configured successfully." -ForegroundColor Green

        [PSCustomObject]@{
            MailboxAddress = $MailboxAddress
            ForwardAddress = $ForwardAddress
            Status         = "Success"
            Error          = ""
        }
    }
    catch {
        Write-Warning "Failed for $MailboxAddress`: $($_.Exception.Message)"

        [PSCustomObject]@{
            MailboxAddress = $MailboxAddress
            ForwardAddress = $null
            Status         = "Failed"
            Error          = $_.Exception.Message
        }
    }
}

# Show the results
$Results | Format-Table -AutoSize

# Export a processing report
$Results | Export-Csv `
    -Path "C:\Temp\AutoReplyResults.csv" `
    -NoTypeInformation `
    -Encoding UTF8

Now this is what happens, when I set DeliverToMailboxAndForward to $true, the autoreply works but the original e-mail is put into the old mailbox which I don't want to happen because in the new tenant users will end up with double e-mail because of the sync of mailbox contents.

When I set that to $false however, the autoreply doesn't work because 'olduser' mailbox is never 'hit'

Also, this will be for about 170 mailboxes, both user and shared boxes.


r/PowerShell • • 5d ago

Question Get current logged on User from System context script

4 Upvotes

I need to query the current logged on user and then write the info in HKLM registry for branding. Does anyone have a script or idea how this will work when the script is deployed from SCCM/Intune with System Context?


r/PowerShell • • 5d ago

AI Disclosure agent-manager runs natively on windows now (psmux + pwsh 7), a keyboard tui for running all your ai coding agents [OC, i'm the dev]

0 Upvotes

i'm the dev, so this is a show and tell. ai disclosure per rule 11, built largely with claude code, i review and test everything. agent-manager is a local terminal app that connects to your existing subscriptions and tools and runs your ai coding clis side by side, each in its own session, in one list with live status (working, waiting on you, finished, errored). it supports claude code, codex, opencode, grok build, gemini cli, antigravity cli, pi, hermes agent, muse code and oh my pi natively on windows. the 11th, command code, only works under wsl2 because its name clashes with cmd.exe.

until last week it was tmux only, so windows meant wsl. as of 0.42 you get both. natively, psmux 3.4+ stands in for tmux and powershell 7.3+ is the pane shell (a contributor, larroy, did most of the port). or keep using wsl2 like before, on tmux inside the distro.

the native install is one line, read the script first if piping to iex bothers you

irm https://raw.githubusercontent.com/YoanWai/agent-manager/main/install.ps1 | iex

it goes to %LOCALAPPDATA%\Programs\agent-manager, adds itself to your user path, and tells you the winget command for psmux, git or pwsh 7 if one is missing. windows powershell 5.1 is refused on purpose, it splits prompts containing quotes into several arguments.

what you get once it's running is keyboard driven. space sends a prompt into any agent without attaching, x kills a session to free its ram and v revives it on the same conversation, and ctrl+r opens a full-file diff review where c comments a line and C sends every comment back to the agent. it's one go binary, no electron or browser.

there's also agent-manager settings list/get/set for scripting your setup, and notify_command runs a powershell command every time an agent needs you (docs have an ntfy push example using $env:AM_BODY).

known gaps on native windows: previews poll instead of stream, and agent clis installed only as .cmd/.bat are refused (npm installs are fine). if it misbehaves with your profile or psmux version i'd like to hear about it.

https://github.com/YoanWai/agent-manager


r/PowerShell • • 6d ago

Solved PowerShell Script and Task Scheduler 0x1 2147942401

9 Upvotes

I need a sanity check, as I feel like I am missing something obvious and I'm too close or too frustrated to see it.

I have a basic scheduled task. Runs as SYSTEM, no triggers, action to run a program, PowerShell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\Tasks\MyScript.ps1"

I run this task it fails, 0x1 as last run result, event 201 action completed with return code from PowerShell of 2147942401

Things I have checked:

  • SYSTEM can access the script and directory it resides in
  • SYSTEM can execute other PowerShell scripts from task scheduler without issues
  • Tried using the full path to powershell.exe
  • Tried with and without quotes around the script path in -File parameter
  • With and without trailing '/' in the path for 'Start In'
  • Tried using -Command { } to create a file as a test
  • Removed all arguments except -File or -Command
  • Script is wrapped with Start/Stop-Transcript; never executes/no transcript is created

I don't know what else to try short of the old method of using a .bat to call PowerShell to see if that gives better clues as to what isn't working.

What am I missing that is preventing PowerShell from executing properly?

Edit: I knew it was something stupid and simple: there is a typo in -ExecutionPolicy (was spelled -ExcecutionPolicy). Found it when running the action arguments from PS as SYSTEM.

Thank you everyone for the assistance. I'm going to go sit in the corner with my dunce cap and contemplate the cobwebs.


r/PowerShell • • 6d ago

Question Methods of a class that's not instanced

3 Upvotes

Hi there,

i can't seem to find relevant informations for this particular topic using my own google skills so maybe someone here can shed some light on this.

if i use a class that doesen't provide any methods without creating an instance of it, but i skip creating an instance via "new().SomeMethod", will this leak memory?

example, sending an async ping to some host without creating a $Ping Object first:

[System.Net.NetworkInformation.Ping]::new().SendPingAsync($IPAddress)

Usually one would create a $Ping object, ping something and in the end, dispose of the $Ping to free the ressources.

If the SendPingAsync Method could work without an instance of the class, the class probably would have some static method's providing the mechanism. So an instance is probably created somewhere but that instance is probably not automatically disposed after the fact?

Can this method be used without worries or should such trickery be avoided?

thanks in advance


r/PowerShell • • 6d ago

Script Sharing EoL Dependency Auditing Script For Vulnerability Remediation Work

7 Upvotes

I've been doing a bit of vulnerability remediation work this past year or so, and I got tired of 'scream tests' across multiple environments, and was unable to affectively find a way to use something like Dependency Walker in a set-it-and-forget-it kind of way, so I built out the following:

https://github.com/cmcalgher/EoL-Dependency-Auditing

This will set the auditing-side of ACL's on specified .DLL files (configured in the CSV's), and will then allow you to parse through the last 24 hours of the security event log to pull instances of processes that touched/acted on those .DLLs.

When ran on individual machines, it will spit out a CSV with a handful of columns, that can be fed into whatever formatting/reporting you see fit.

Internally at the org I work for, we were pretty much immediately able to write off Visual C++ 2012 as accepted risk on our fully up to date on-prem Exchange SE servers, for example. Would Exchange keep working if we had ripped that off? Would we have to restore corrupted DBs? Not sure, but with how many Exchange processes were using those Visual C++ 2012 .DLL's, I'm glad I didn't have to find out.

The above was inspired by the following Microsoft article, detailing how to audit VC++ usage in coding projects:

https://learn.microsoft.com/en-us/cpp/windows/redist-version-auditing?view=msvc-170


r/PowerShell • • 7d ago

News Why the Microsoft Graph PowerShell SDK has Two Cmdlets to Add Group Members

3 Upvotes

It’s a consequence of how the Microsoft Graph PowerShell SDK is built that two cmdlets are available to add members to Entra ID groups (the same is true for group owners). The reason why the New-MgGroupMember and New-MgGroupMemberByRef cmdlets exist is down to how the Graph SDK build process constructs cmdlets from Graph metadata. The Graph exposes two ways to add new group members, so the SDK follows suit.

https://office365itpros.com/2026/10/20/group-member-sdk-cmdlets/


r/PowerShell • • 8d ago

News Microsoft to Retire the Search-UnifiedAuditLog Cmdlet in 2027

42 Upvotes

MC1505599 covers two big announcements. First, the AuditLogQuery Graph API is GA. Second, Microsoft will retire the heavily used Search-UnifiedAuditLog cmdlet in October 2027. Microsoft hasn’t said why they want to retire Search-UnifiedAuditLog and have tenants convert their PowerShell scripts to use the AuditLogQuery API but reducing engineering cost and complexity are probably at the heart of the matter. In any case, the conversion will cost Microsoft 365 development effort and money between now and October 2027, and that’s a bad thing.

https://office365itpros.com/2026/10/19/search-unifiedauditlog-retirement/


r/PowerShell • • 8d ago

Question alias ls works but alias doesn't exist anywhere — what is it?

7 Upvotes

Title:

On PowerShell 5.1 (Windows 11 24H2, build 26100.9711), running alias ls gives valid output:

PS C:\> alias ls

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ls -> Get-ChildItem

But every way I know to look it up says it doesn't exist:

Get-Alias alias          # ItemNotFoundException
Get-Command alias        # CommandNotFoundException
Get-Command -Name 'alias' -CommandType Alias, Function, Cmdlet -ErrorAction SilentlyContinue  # returns nothing
Get-Item Alias:\alias -ErrorAction SilentlyContinue  # returns nothing

No $PROFILE exists. Only standard modules are loaded. What is alias actually doing here?


r/PowerShell • • 9d ago

Script Sharing Open MS Office files in Office Online with a simple double click - NOW POSSIBLE! - Powershell to the Rescue~

0 Upvotes

I dug around the internet for a solution and couldn't find anything worth diving into. Even the one "paid" solution (Files App) that I read might be able to do it, didn't seem like it could when I tested it and it also would be a pain to deploy at any scale but your own computer.

So I did what any developer minded IT person would do and dug through open source solutions, still nothing but one for the completely wrong OS (https://github.com/bewithdhanu/office-online-bridge-macos). This project gave me the idea to try porting the same work around to Windows. I sort of did it. Basically the same idea but used the existing "View Online" function from the context menu and wrote a PowerShell script to execute it. The script was then improved with an exe wrapper to make it more user friendly.

I am pretty surprised this solution hasn't been made before, but here it is now! (AI Disclosure: I wrote the readme using AI and used it to help create my exe wrappers via the compile.ps1 script. All other components were written largely by me with some assistance from AI to grab basic methodology on getting/triggering functions from the context menu)

https://github.com/Fireant456/M365-Bridge

It is bundled with an installer that can be deployed silently. Only requirement (at the moment) is that your files you are attempting to open must be in a OneDrive synced folder. If they are not an error will tell you they need to be. I might work to add automatic handling of uploading files to a temporary OneDrive directory and writeback to the original location in order to seamlessly handle non-synced file editing, but I don't require that in my use case. Happy to take pull requests if anyone wants to give it a shot.

Would love any feedback. Enjoy!


r/PowerShell • • 10d ago

Solved Gathering meter reads from Konica printers.

12 Upvotes

(I'll start by admitting that some of my PoSh may be unconventional / and abbreviated - I have embraced it accordingly).
(Edit - I discovered some discrepancies and found additional OID's that count towards both 'Black' and 'Color' totals - Added: "ScanFax_Black" and "Copy_SingleColor")

I needed to come up with a way to create some logs of the usage on the fleet of 10 Konica printers across four locations / print servers.

These logs will be used to validate the pricing figures our printer support vendor provides (pricing is based on estimated / averaged usage per device - that data is audited on a quarterly basis, via automated auditing tools on each print server - FM Audit).

Currently - Without any of our own historical data - We have to take the vendors word, that those quarterly averages are 'OK'...

So, someone from accounting asked me for help.

The below script collects settings info for all of the Konica printers on each of the print servers, then uses the 'PortName' (IP address) to run an SNMP query on each device (SNMP must be enabled in the devices network settings).

The critical items are the OID's.

Figuring out which ones pull in the values for 'black' and for 'color' were the first challenge.

Once I got that figured out - It took me a while to find the OID that gathers the devices serial number - I could NOT find this documented anywhere, and AI (Copilot, Gemini, Claude) wasn't able to either.

For this last bit - I ended up walking (snmpwalk) through ALL 7125 OID's to locate the one that gathers the serial number.

wsl snmpwalk -v2c -c public <printer IP> 1.3.6.1 > 'C:\Users\richie\Documents\PoSh_Stuff\OID_walk.txt'

And looking for the serial number I already knew for that printer.

Select-String -Path 'C:\Users\richie\Documents\PoSh_Stuff\OID_walk.txt' -Pattern '<SerialNumber>'

OID_walk.txt:460:iso.3.6.1.2.1.43.5.1.1.17.1 = STRING: "<SerialNumber>"

Posting what I figured out.

I will pipe '$Report' to a Csv, and save it accordingly.

I'll be scheduling this to run on a quarterly basis - And handing the Csv's over to accounting when they ask for them.

$AllKonica = @()

("Site1,site2,site3,site4").Split(',') | % {
    If (Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue) {
    $AllKonica += Get-Printer -ComputerName $_ | ? { $_.DriverName -match 'Konica' -and $_.PortName -NOTmatch "portprompt|microsoft|_"} | Select ComputerName, Name, PortName, DriverName 
    } 
}

# (NOTE: You could also just list the name, and port name - This removes the need to use domain auth for the script - Since SNMP does not reqiure authentication)

<#
$AllKonica = @"
"Name","PortName"
"S1-PTR-066","192.168.1.66"
"S1-PTR-062","192.168.1.62"
"S1-PTR-061","192.168.1.61"
"S1-PTR-060","192.168.1.60"
"S1-PTR-064","192.168.1.64"
"S2-PTR--034","192.168.2.34"
"S3-PTR-060","192.168.3.60"
"S3-PTR-061","192.168.3.61"
"S4-PTR-068","192.168.4.68"
"S4-PTR-066","192.168.4.66"
"@ | ConvertFrom-Csv
#>

$OIDs = [Ordered]@{
    "Model"            = ".1.3.6.1.4.1.18334.1.1.1.3.5.2.2.0"
    "SerialNo"         = ".1.3.6.1.2.1.43.5.1.1.17.1"
    "Total"            = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.1.1.0"
    "Print_Black"      = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.1.2"
    "Copy_Black"       = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.1.1"
    "ScanFax_Black"    = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.3.1.7.1"
    "Copy_SingleColor" = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.3.1"
    "Print_Color"      = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.2.2"
    "Copy_Color"       = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.2.1"
    "Print_2Color"     = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.4.2"
    "Copy_2Color"      = ".1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.4.1"
}

$Report = @()
$SNMP_Community = "public"
$AllKonica | % {

$PrinterIP = $_.PortName  
$PrinterName = $_.Name

If (Test-Connection $PrinterIP -Count 1 -ErrorAction SilentlyContinue) {

$snmp = New-Object -ComObject OlePrn.OleSNMP

try {
    $snmp.Open($PrinterIP, $SNMP_Community, 2, 1200)
    $Data = [Ordered]@{ "Printer" = "$PrinterName - $PrinterIP" }

foreach ( $Key in $OIDs.Keys ) {
    try { $Value = $snmp.Get($OIDs[$Key])
         if ( $null -eq $Value -or $Value -eq "" ) 
         { $Data[$Key] = 0 }
         #{ $Data[$Key] = $null }
          else { $Data[$Key] = $Value }
    } # END 'try' # 2
    # catch { $Data[$Key] = $null }
    catch { $Data[$Key] = 0 }
} # END 'foreach ($Key in $OIDs.Keys)'

$TotalColor = 0; $OIDs.Keys | ? { $_ -match "color" } | %  { $TotalColor += [int]$Data["$_"] }
$TotalBlack = 0; $OIDs.Keys | ? { $_ -match "black" } | %  { $TotalBlack += [int]$Data["$_"] }

$Report += [PSCustomObject][Ordered]@{
"Model"    = $Data["Model"]
"SerialNo" = $Data["SerialNo"]
"Printer"  = $Data["Printer"]
"Total"    = $Data["Total"]
"Black"    = $TotalBlack
"Color"    = $TotalColor
    }
} # END 'try' # 1

catch { Write-Host "Connection failed: $PrintServer -> $PrinterIP ($PrinterName)" -F 14 }
finally { $snmp.Close() }

} # END 'If (Test-Connection...'

else {
    $Report += [PSCustomObject][Ordered]@{
        "Model"    = "Unk"
        "SerialNo" = "Unk"
        "Printer"  = "$PrinterName - Unreacheable"
        "Total"    = "NULL"
        "Black"    = "NULL"
        "Color"    = "NULL"
    }
} # END 'else'

} # END '$AllKonica | %'

$Report | ft

r/PowerShell • • 11d ago

Question REPOST Issue with $PROFILE function

2 Upvotes

Hello everyone. I hope you are having a good time.

function gethash {

param([string]$string = "")

if ($string -eq [string]::Empty -or $string -isnot [string])

{

Write-Output "input not valid"

}

else

{

(Get-FileHash -algorithm sha256 $string).Hash | tee -Variable b

}

}  

I Have this function in my $Profile script. when i run gethash something it returns the hash string as expected, but when I try to print the variable containing the hash i just obtained from the piped command: tee, (alias of Tee-Object) with `$b

it prints nothing, the variable is not saved.

on the other hand, if i copy the exact same command from the $profile function directly through the terminal, $b prints what expected: the hash of the file.

I haven't used this function so much, but I'm pretty sure it worked before today.

Thanks in advance to any who will respond.


r/PowerShell • • 11d ago

Question Function Issue in $PROFILE path

1 Upvotes

Hello everyone. I hope you are having a good time.

```powershell

function gethash {

param([string]$string = "")

if ($string -eq [string]::Empty -or $string -isnot [string])

{

Write-Output "input not valid"

}

else

{

(Get-FileHash -algorithm sha256 $string).Hash | tee -Variable b

}

}
```

I Have this function in my $Profile script. when i run gethash something it returns the hash string as expected, but when I try to print the variable containing the hash i just obtained from piped command tee, (alias of Tee-Object) as an input with `$b

it prints nothing, the variable is not saved.

on the other hand, if i copy the exact same command from the $profile function directly through the terminal, $b prints what expected: the hash of the file.

I haven't used this function so much, but I'm pretty sure it worked before today.

Thanks in advance to any who will respond.


r/PowerShell • • 11d ago

Information agent manager 0.42 runs natively on Windows with psmux and PowerShell 7

2 Upvotes

we released 0.42 of agent manager. we are the creators. it is a free open source go TUI that runs coding agent CLIs side by side, each in its own session, with live status and diff review.

this one is Windows. we added support for running natively on Windows with psmux 3.4 or newer in place of tmux and PowerShell 7.3 or newer as the pane shell. you do not need WSL for the TUI itself. Command Code on native Windows still uses WSL2.

also added a notify_command setting that runs a shell command on every notification, and an agent-manager settings CLI to read or change any setting from the shell.

Windows install irm https://raw.githubusercontent.com/YoanWai/agent-manager/main/install.ps1 | iex

https://github.com/YoanWai/agent-manager/releases/tag/v0.42.0