/r/PowerShell

Photograph via snooOG

PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets and managing modules.

ABOUT POWERSHELL

Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.


SUBREDDIT FILTERS

Desired State Configuration

Unanswered Questions

Solved Questions

News

Information

Script Sharing

Daily Post

Misc








/r/PowerShell

244,601 Subscribers

1

How do I make my general user account my admin, I also may have accidentally used a command and made another guest account an administrator???

0 Comments
2024/04/24
03:55 UTC

0

Windows 11 on work laptop can't install RSAT

Hello,

I am currently running into an issue at work where I cannot install RSAT on my computer, can you help me.

I ran the command, "Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property DisplayName, State" on cmd and it didn't work so I tried to use settings and nothing comes up.

Has anyone had this issue and how did you fix it?

8 Comments
2024/04/23
22:03 UTC

3

GUI with parameters?

Powershell-script-menu-gui looks like the perfect tool for quickly loading up scripts with hardcoded options… or scripts having logic to collect data like a grid view popup.

I have a ton of scripts that require 1+ servers to be chosen and then a bunch more that require 1-2 params.

Anything similar but allowing for params?

If not, it’s easy enough to create a hardcoded winforms to hardcode textboxes to a few scripts, I just didn’t want to do a lame job reinventing the wheel

5 Comments
2024/04/23
21:42 UTC

4

Why am I getting access denied when searching CSV files?

I have some very basic code I use to search CSV audit files for specific strings. I'll copy the files from the device to c:\1 on my machine and then run this to search for 'STRING' in the 'path/from' column

Get-ChildItem 'C:\1' -Recurse | ForEach-Object {
  Import-Csv $_.FullName | Where-Object { $_.'path/from' -like '*STRING*' }
} | Export-Csv 'C:\1\branded.csv' -NoTypeInformation

Keep getting this though

Import-Csv : Access to the path 'C:\1\20240327' is denied.
At line:2 char:3
+   Import-Csv $_.FullName | Where-Object { $_.'path/from' -like '*/DEP ...
+   ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Import-Csv], UnauthorizedAccessException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand

Not really sure why. Running this as admin.

10 Comments
2024/04/23
20:20 UTC

1

SharePoint Online Document Library folder creation

So maybe I'm just not asking google the right questions but I'm having a hard time finding the cmdlet I'm looking for. I have multiple teams sites that I need to add folders to their document libraries. For the life of me I can't seem to find the cmdlet I'm looking for to do this in powershell. I've encountered boat loads of "How to do this with Add-PnPFolder" but I'm a little sketched out about the untrusted repository I have to accept in order to use it and I literally don't have the time to research security around it. Surely there is a regular ass PowerShell cmdlet to create a folder in a document library for a specific site??

0 Comments
2024/04/23
20:13 UTC

2

Powershell & Web

Apologies if this is a dumb question. Can I use PowerShell to extract and use data from a web system/web database? E.g. extract device info from Ivanti. How would i do this?

5 Comments
2024/04/23
19:09 UTC

1

Programmatic update of Windows Update history GUI when patching servers using PowerShell

Good evening everyone. :) We use the following approach for patching Windows Servers, using PowerShell:

https://devblogs.microsoft.com/scripting/hey-scripting-guy-how-can-i-search-for-download-and-install-an-update/

It works very well, but, I think, starting Windows Server 2019, it was noticed, that in "Update History" section of "Update & Security" recently installed updates are not shown, when script is used to perform the installation. If programmatically download updates and then press "Install now" manually, then it's fine. Does anyone know-is it possible to reflect recently installed updates in GUI section of "Windows Settings"->"Updates & Security"->"View updates history"?

0 Comments
2024/04/23
17:55 UTC

5

Script to balance AD group membership.

A team has a oddball app that requires computers be added to an AD group, but there is a maximum number of computers that can be in each group. So computers are divided between several AD groups.

This is a huge maintenance headache for both the help desk who adds them initially, and the team that is ultimately responsible for it.

They have requested a script that they can run to manage this, but I've been having a hard time finding the logic required to pull it off.

Basically it needs to take an inventory of several groups, and then distribute the members across those groups evenly (as much as possible).

Most relevant script sample I could find was this script that Google "AI search" spit out. It was a complete mess of context errors but it gave me somewhere to start. It now works up to the point of the "$MembersToAdd" line. Meaning it appears to hash the members of the groups, remove the right amount from the larger groups, but then it "Cannot validate argument on parameter 'Members'. The argument is null or empty." when trying to add the excessive computers to the other groups.

Anyone tried anything like this before, or have an idea of what I can do to achieve this goal?

Thanks!

# Import the Active Directory module
Import-Module ActiveDirectory

# Get all of the AD groups
$groups = Get-ADGroup -Filter { Name -like "TEST-ADGroupMembershipBalance*" } -Properties *

# Create a hashtable to store the group membership counts
$groupMembershipCounts = @{}

# Iterate through each group and get the membership count
foreach ($group in $groups) {
    $groupMembershipCounts[$group.Name] = $group.Members.Count
}

# Get the average group membership count
$averageGroupMembershipCount = $groupMembershipCounts.Values | Measure-Object -Average | Select-Object -ExpandProperty Average

# Iterate through each group and add or remove members to balance the group membership counts
foreach ($group in $groups) {
    Write-Host $group $group.Members.Count
    if ($groupMembershipCounts[$group.Name] -gt $averageGroupMembershipCount) {
        # Remove members from the group
        $membersToRemove = $group.Members | Sort-Object -Descending | Select-Object -First ($groupMembershipCounts[$group.Name] - $averageGroupMembershipCount)
        Remove-ADGroupMember -Identity $group -Members $membersToRemove
    } elseif ($groupMembershipCounts[$group.Name] -lt $averageGroupMembershipCount) {
        # Add members to the group
        $membersToAdd = Get-ADComputer -Filter * -SearchBase $group.DistinguishedName | Sort-Object {Get-Random} | Select-Object -First ($averageGroupMembershipCount - $groupMembershipCounts[$group.Name])
        Add-ADGroupMember -Identity $group -Members $membersToAdd
    }
}

14 Comments
2024/04/23
17:29 UTC

17

What is your scalable approach for encrypting strings within an automated powershell script while trying to stay within the confines of powershell?

This revolves around use cases in which you need to add authentication keys and\or credentials to your powershell script in order for it to be able to access a resource but don't want it to show in clear text in your script.

Key point is that it needs to be scalable.

I know of two methods of doing this.

Method 1:

Create EFS certificate with SYSTEM account.

Add password information to a text file.

Encrypt text file with EFS certificate.

Export EFS certificate with private key

Distribute EFS certificate to all target endpoints via a CertPolicy GPO

Distribute encrypted text file along with powershell script

Run powershell script via system and pull credentials from text file which will decrypt text file automatically since EFS cert will already be in certificate store, via GPO policy

Pros:

Secure

Scalable

Requires something you know (EFS password in order to export certificate private keys)

Cons:

Requires EFS certificate to be in place in certificate store in order to decrypt text file

Requires a method to distribute EFS\Powershell script to target endpoints

Method 2:

Generate your own AES key to perform encryption.

Steps are detailed here:

https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/

Pros:

Secure

Scalable

Cons:

Requires a method to distribute AES Key\Powershell script to target endpoints

AES key needs to be secured in a way that your standard user can't access it.

If AEK key is compromised than everything encrypted with it will be compromised.

With that said, those are the only methods that I know about or are familiar with.

Do you guys know of any other approach that can be used that is scalable and secure?

20 Comments
2024/04/23
16:53 UTC

2

23042024 -> 23/04/2024 how to convert this string to date

How in God's name do I convert strings that represents dates in Euro format to actual DateTime?

I've tried Parse, ParseExact. Is there a way?

2 Comments
2024/04/23
16:16 UTC

1

Opening browser using session created and populated from Invoke-WebRequest

I'm quite adept at using Invoke-WebRequest for scraping and interacting with websites/maintaining sessions headless, but a colleague has asked for a Powershell script that opens Chrome and logs in (not very secure, I know but it's InfoSec asking so hey ho), they're sending TAB keys and the password, but that doesn't work if the user interacts with the computer whilst this is running.

$pathToChrome = 'C:\Program Files\Google\Chrome\Application\chrome.exe'
$tempFolder = '--user-data-dir=c:\temp' # pick a temp folder for user data, not always needed
#$startmode = '--start-fullscreen' # '--kiosk' is another option
$startPage = 'secretURL' #--incognito before the url if desired

#Start-Process -FilePath $pathToChrome -ArgumentList $tempFolder, $startmode, $startPage.
Start-Process -FilePath $pathToChrome -ArgumentList $tempFolder, $startPage

start-sleep -Milliseconds 5000

#[Microsoft.VisualBasic.Interaction]::AppActivate("Chrome")

[System.Windows.Forms.SendKeys]::SendWait("{Tab}{Tab}{Tab}{Tab}{Tab}secretusername{Tab}")
start-sleep -Milliseconds 500
[System.Windows.Forms.SendKeys]::SendWait("secretpassword{ENTER}")

I've tried a few ways of doing it and I can't see that there's a way to pass a payload to Chrome when using Start-Process so my thought was to login to the site using Invoke-WebRequest and then open the browser using that session and it's cookies, but I can't tell if that's actually possible. My Google search hasn't found anyone ever trying this.

3 Comments
2024/04/23
16:10 UTC

0

Return an array from PSExec

When pointing a (PoSh) command at a remote computer via PSExec - Specifically one that returns a result that is an array - Capturing that returned result from PSExec is not an array - It is a simple string, with multiple lines.

Me, Google searching for a way to do this... For YEARS - Has not provided anything on how to keep that array... an array...

As it turns out - piping that array to 'ConvertTo-Csv' as part of the command being ran on the remote computer is the key!

Then capturing the returned CSV value and piping it to 'ConvertFrom-Csv' - and Ta-Da! It's an array

Below is a simple example... I show a more involved example on my (not monetized) blog, here (assuming external links are allowed on this subredits posts, that is):

http://www.somethingtoscrollthrough.com/2024/04/return-array-from-psexec-via-powershell.html

A simple example:

$Computer_Name = "<hostname>"

`$DiskInfo = (C:\SysInternals\PsExec.exe -s -nobanner \$Computer_Name /accepteula cmd /c powershell.exe ``

"& { get-WmiObject win32_logicaldisk | ? {\$_.DeviceID -eq 'C:'} | Select FreeSpace, Size | ConvertTo-Csv }"``

2> $null) | ConvertFrom-Csv

'$DiskInfo' is an array, so (of course) this will work as expected:

  • $DiskInfo.FreeSpace
  • $DiskInfo.Size

8 Comments
2024/04/23
15:39 UTC

0

Showing functions in a module that uses dynamic sripts

I have this block at the beginning of my module:

foreach ($import in (dir $PSScriptRoot\Public\ -filter *.ps1)) {
. $import.fullname
}

That reads all the scripts (PS1s) in a child directory, and executes them. Effectively importing those functions in those scripts. I do this to keep my module clean since i have so many functions that fall into sub categories.

The problem is that before you load the module explicitly, you won't see any of the functions in the child modules. You can see the functions in the primary module PSM1 file.

So my questions are these:

  1. Is there a way to list the functions in the sub-scripts without having to load the module?

  2. Is there a more elegant/approved way to use sub-scripts in a module?

4 Comments
2024/04/23
14:35 UTC

0

Question about writing a Script that disables IPV6 on certain network adapters

Hello,

Just  a quick question.  With the command disable-NetAdapterBinding -Name "Ethernet" -ComponentID ms_tcpip6.  Is there a way to write a script where it can disable IPV6 for adapters with different names? For example some users may have ethernenet 2 or 3  e.g..

We have a VPN adapter that has to have IPV6 disabled however certain machines have the VPN adapter name different. I know by running Get-NetAdapter can help with this by telling me which ethernet adapter is the VPN adapter. However was wondering if there was a script that could automate this further.  Like a script that "knows" which adapter is the VPN adapter (without me running the get-netadapter) and disabled IPV6 on only the VPN adapter.

I tried searching google but I be honest I'm very new to powershell so I got completely confused and it didn't seem possible? But thought I'll ask here to see if I can learn a thing or two.

No biggie if not. I can do it manually anyway but I just wondered.

9 Comments
2024/04/23
14:30 UTC

6

Script runs perfectly in ISE. In TaskScheduler it loops twice, then skips the API call. No output in transcript.

Okay. here's the script. It's fairly straightforward. Take list of tables, loop through it calling a vendor-provided downloader for each one and log everything for each one while doing it.

$InformationPreference = 'Continue'
#
Set-Variable -name "SyncDate" -Value (Get-Date -format "MM_dd_yyyy_HHmm")
#
Set-Variable -Name "APP_API_URL" -Value "https://api-gateway.vendorparent.com"
#
$tables='shirts','ties','belts','slacks','socks','jackets','vests','cumberbunds','shoes','cufflinks','pocketsquares','hats'
#
#Begin Loop
#
#
#
foreach ($table in $tables)

{
Set-Variable -name "SyncDate" -Value (Get-Date -format "MM_dd_yyyy_HHmm")
#
Start-Transcript -Path "C:\app_logs\${table}_${SyncDate}_output.txt"
#
#Run sync command for $table
#
app --base-url $APP_API_URL --client-id $Env:CD_API_KEY --client-secret $Env:CD_API_SECRET --loglevel debug syncdb --namespace VendorName --table $table --connection-string $Env:LOCAL_DB_CONN_STRING

Stop-Transcript

}    

In all cases, I get separate transcript files for each table.

When this is called via task scheduler:

For the first two tables (in this instance "shirts" and "ties" I get a full log of everything "app" is doing. (It's a python SQL fetch)

I have tried configuring the task as

powershell.exe

-NoProfile "& ./app_automation.ps1" with start in set to the folder the script is in.

I've tried it as

powershell.exe

"-File C:\app_logs\app_automation.ps1"

I've tried running as a user with privileges (works) running as system (doesn't work at all)

I've tried putting a sleep statement inside the loop before the stop-transcript in case the app was having some kind of speed issue.

I've tried logging the whole loop to a single file. (start-transcript and stop-transcript outside the {} brackets)

I've tried logging with

#try
#{
#	$proc = [System.Diagnostics.Process]::Start([System.Diagnostics.ProcessStartInfo]@{
#		Filename = "app.exe"
#		Arguments = "--base-url $APP_API_URL --client-id $Env:CD_API_KEY --client-secret $Env:CD_API_SECRET --loglevel debug syncdb --namespace VendorName --table $table --connection-string $Env:LOCAL_DB_CONN_STRING"
#		CreateNoWindow = $true
#		UseShellExecute = $false
#		RedirectStandardOutput = $true
#	})
#	$output = $proc.StandardOutput
#	$output.ReadToEnd()
#} finally {
#	if ($null -ne $proc) {
#		$proc.Dispose()
#	}
#	if ($null -ne $output) {
#		$output.Dispose()
#	}
#}

In the hopes it would catch some kind of error message from the app. Nope. .

.

.

The only thing I can figure is that there has to be something fundamentally different between how ISE runs the script inside of it's own window versus how powershell instantiates an instance when it's called via task scheduler.

. .

That doesn't explain why it works twice and stops on the third via task scheduler. I put in the sleep so I could view the log start and stop timestamps, so I know it wasn't (and isn't without the sleep) trying to start three or more simultaneous app calls.

Log from task scheduler success:

**********************
Windows PowerShell transcript start
Start time: 20240423040346
Username: Reddit\Kiernian
RunAs User: Reddit\Kiernian
Configuration Name: 
Machine: Kiernian (Microsoft Windows NT 10.0.22621.0)
Host Application: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.EXE -NoProfile & ./app_automation.ps1
Process ID: 44620
PSVersion: 5.1.22621.2506
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.22621.2506
BuildVersion: 10.0.22621.2506
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is C:\app_logs\shirts_04_23_2024_0403_output.txt
DEBUG:asyncio:Using selector: SelectSelector
2024-04-23 04:03:53,371 - DEBUG - Checking for valid database connection string (abstract_db_comman
d.py:14)
2024-04-23 04:03:53,371 - DEBUG - Checking connection to database (abstract_db_command.py:23)
INFO:pysqlsync.postgres:connecting to postgres@10.1.1.256:9999
INFO:pysqlsync.postgres:PostgreSQL version 11.0.14 final
2024-04-23 04:03:53,427 - DEBUG - Client region: us-best-1 (api.py:114)
2024-04-23 04:03:53,427 - DEBUG - synchronizing table: VendorName.shirts (sql.py:6
1)
INFO:pysqlsync.postgres:connecting to postgres@10.1.1.256:9999
INFO:pysqlsync.postgres:PostgreSQL version 11.0.14 final
DEBUG:pysqlsync:analyzing dataclass `database_version`:
@dataclasses.dataclass
class database_version:
    """
    Table for storing meta-information about the database schema version.

    :param version: The version of the database schema.
    """

    version: Annotated[Union[int, DefaultTag], Identity, PrimaryKey]

DEBUG:pysqlsync:analyzing dataclass `table_sync`:
@dataclasses.dataclass
class table_sync:

================================THOUSANDS OF LINES OF STUFF==============================

DEBUG:pysqlsync:upsert 6 rows into "VendorName"."shirts"
INFO:pysqlsync:6 rows have been inserted or updated into "VendorName"."shirts"
DEBUG:pysqlsync:delete 0 rows from "VendorName"."shirts"
WARNING:pysqlsync:no rows to delete
2024-04-23 04:04:27,765 - DEBUG - update meta-data about table shirts that has
 been replicated (sql_metatable_handler.py:74)
DEBUG:pysqlsync:execute SQL:
INSERT INTO "VendorParent_app"."table_sync"
("id", "source_namespace", "source_table", "timestamp", "schema_version", "target_schema", "target_
table", "schema_description_format", "schema_description") VALUES ($1, $2, $3, $4, $5, $6, $7, $8,
$9)
ON CONFLICT ("id") DO UPDATE SET
"source_namespace" = EXCLUDED."source_namespace",
"source_table" = EXCLUDED."source_table",
"timestamp" = EXCLUDED."timestamp",
"schema_version" = EXCLUDED."schema_version",
"target_schema" = EXCLUDED."target_schema",
"target_table" = EXCLUDED."target_table",
"schema_description_format" = EXCLUDED."schema_description_format",
"schema_description" = EXCLUDED."schema_description"
;
**********************
Windows PowerShell transcript end
End time: 20240423040427
**********************

Transcript log from third table in loop:

**********************
Windows PowerShell transcript start
Start time: 20240423040528
Username: Reddit\Kiernian
RunAs User: Reddit\Kiernian
Configuration Name: 
Machine: Kiernian (Microsoft Windows NT 10.0.22621.0)
Host Application: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.EXE -NoProfile & ./app_automation.ps1
Process ID: 44620
PSVersion: 5.1.22621.2506
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.22621.2506
BuildVersion: 10.0.22621.2506
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is C:\app_logs\belts_04_23_2024_0405_output.txt

**********************
Windows PowerShell transcript end
End time: 20240423040543
**********************

The third and all subsequent log files when the task is called form task scheduler resemble that "empty" one.

Where do I start looking next?

38 Comments
2024/04/23
14:00 UTC

2

Logging and column headers - how to get PoSH to spit out the headers when you want them?

So in this log, I'm getting this:

Starting CHI0923-M1 slot 10
idrac: idrac74208wg323; idrac FQDN: idrac74208wg323.myintranet.com; idrac IP: 10.10.10.11
Del idrac: False; Create idrac: True
Creating:

HostName               RecordType    Type       Timestamp         TimeToLive      RecordData
--------               ----------    ----       ---------         ----------      ----------
idrac74208wg323        A             1          0                 10:00:00        10.10.10.11
Server does not have profile.
Del idrac PTR: False; Create idrac PTR: True
Creating:
10.10.10.11		   PTR           12         0                 01:00:00        idrac74208wg323.myintranet.com.

It's some tee-objects then a add-dnsserverresourcerecord, then more tee-objects and then another add-dnsserverresourcerecord.

How can I get it to put the headers for the second add-dnsserverresourcerecord?

Edit: The code is pretty big and would be hard to sanitize, but this is it in effect:

"Starting CHI0923-M1 slot 10" | Tee-Object C:\temp\log.txt -Append
"idrac: idrac74208wg323; idrac FQDN: idrac74208wg323.myintranet.com; idrac IP: 10.10.10.11"  | Tee-Object C:\temp\log.txt -Append
"Creating:" | Tee-Object C:\temp\log.txt -Append
Add-DNSServerResourceRecordA @Params | Tee-Object C:\temp\log.txt -Append

"Server does not have profile." | Tee-Object C:\temp\log.txt -Append
"Del idrac PTR: False; Create idrac PTR: True" | Tee-Object C:\temp\log.txt -Append
"Creating:" | Tee-Object C:\temp\log.txt -Append
Add-DNSServerResourceRecordPTR @Params | Tee-Object C:\temp\log.txt -Append
6 Comments
2024/04/23
13:52 UTC

2

Basic question: running scripts locally in my home machine and execution policies.

I'm learning ps and I would like to automate some tasks to set up windows how I like in my personal home machine. Example: I like to only have shortcuts in my start menu, not folders, but everytime an app updates in puts its folder back in the menu.

Scheduled tasks and ps script could do the job. However, I struggle with PS Execution Policies. Do I run into a security problem if I just leave the policy to Unrestricted?

I've seen several solutions to the policy issue, but most are for business environments. From what I gather, signing could be an option, but from what I understand, I need to purchase a signing certificate, which I'm not looking to do.

5 Comments
2024/04/23
13:19 UTC

0

Force a package install even if Windows version is unsupported?

I get an error while installing an appbundle saying that the app is only for Windows.Holographic Windows.Team

How to fix it?

1 Comment
2024/04/23
12:20 UTC

0

How can i connect to linux server using powershell

I'm using the windows machine, I want to connect to remote Linux machine using the powershell. Can someone let me know if it is possible to connect to linux using password authentication instead of using key based authentication.

5 Comments
2024/04/23
11:27 UTC

0

Script that types something for me every (xx) minutes then sends

Want to start off by saying I am not that familiar with PowerShell, but I do know it does things like this. I was needing it to do what my title says and I am not sure where to start or where to look. Does it exist? How would I do it or where would I find it if so?

2 Comments
2024/04/23
09:43 UTC

6

Powershell scripts keeps sending the reminder several days after the user has changed their password

=== EDIT ===

This seems to be working now, i've made the changes susgested by the folks on this thread and i've removed tons of spaghetti code.

Thanks all of you guys for the patience and the willing to make me learn a bit more of Powershell.

Cheers.

So, I'm using a script I've found time ago on here, made a few changes and at first it was working as intented but, I've recibing complains about as soon the user changes their password the mail keeps sending them to them for a few days or just next day:

    $cabecera = "C:\Assets Mail\Cabecera.png"
    $footer = "C:\Assets Mail\firma.png"
    [array]$rn_all=$cabecera,$footer

	

	$users = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0} -Properties "SamAccountName", "EmailAddress", "Name", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "SamAccountName", "EmailAddress", "name", @{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} | Where-Object {$_.EmailAddress}

	# Warning Date Variables

    $FourteenDayWarnDate = (Get-Date).AddDays(14).ToLongDateString().ToUpper()
    $ThirteenDayWarnDate = (Get-Date).AddDays(13).ToLongDateString().ToUpper()
    $TwelveDayWarnDate = (Get-Date).AddDays(12).ToLongDateString().ToUpper()
    $ElevenDayWarnDate = (Get-Date).AddDays(11).ToLongDateString().ToUpper()
    $TenDayWarnDate = (Get-Date).AddDays(10).ToLongDateString().ToUpper()
    $NineDayWarnDate = (Get-Date).AddDays(9).ToLongDateString().ToUpper()
    $EightDayWarnDate = (Get-Date).AddDays(8).ToLongDateString().ToUpper()
    $SevenDayWarnDate = (Get-Date).AddDays(7).ToLongDateString().ToUpper()
    $SixDayWarnDate = (Get-Date).AddDays(6).ToLongDateString().ToUpper()
    $FiveDayWarnDate = (Get-Date).AddDays(5).ToLongDateString().ToUpper()
    $FourDayWarnDate = (Get-Date).AddDays(4).ToLongDateString().ToUpper()
	$ThreeDayWarnDate = (Get-Date).AddDays(3).ToLongDateString().ToUpper()
    $TwoDayWarnDate = (Get-Date).AddDays(2).ToLongDateString().ToUpper()
	$OneDayWarnDate = (Get-Date).AddDays(1).ToLongDateString().ToUpper()

	# Send-MailMessage parameters Variables
	$MailSender = 'sender mail'
	$SMTPServer = 'server ip'

	foreach($User in $Users) {
		$PasswordExpiry = $User.PasswordExpiry
		$days = (([datetime]$PasswordExpiry) - (Get-Date)).days
		
		$WarnDate = Switch ($days) {
			14 {$FourteenDayWarnDate}
            13 {$ThirteenDayWarnDate}
            12 {$TwelveDayWarnDate}
            11 {$ElevenDayWarnDate}
			10 {$TenDayWarnDate}
            9 {$NineDayWarnDate}
            8 {$EightDayWarnDate}
			7 {$SevenDayWarnDate}
            6 {$SixDayWarnDate}
            5 {$FiveDayWarnDate}
            4 {$FourDayWarnDate}
			3 {$ThreeDayWarnDate}
            2 {$TwoDayWarnDate}
			1 {$OneDayWarnDate}
		}

		if ($days -in 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 1) {
			$SamAccount = $user.name.ToUpper()
			$Subject    = "subject ($SamAccount)"
			$EmailBody  = @"
						<html><body> stuff </body> 
</html>

"@
			$MailSplat = @{
	            To          = $User.EmailAddress   
				From        = $MailSender
				SmtpServer  = $SMTPServer
				Subject     = $Subject
				BodyAsHTML  = $true
				Body        = $EmailBody
                Attachments = $rn_all
                Encoding =  "UTF8" 

                
             
				
			}
			
			Send-MailMessage u/MailSplat 
			#Write-Output $EmailBody
		}
	}

Any idea what could be causing this?

17 Comments
2024/04/23
09:18 UTC

2

I'm making an app and I need help with GUI

I use VSCode as my primary IDE.

However, I need help with WPF XAML thingy since VSCode doesn't support autocomplete with XAML, and I can't see how the UI looks unless I run it over and over again, it is making the UI designing a bad process.

I'm pretty sure this could be improved, if you use any WPF Designer while making GUIs with powershell please let me know.

I already tried some options in vscode marketplace and some project on github. They didn't work out for me.

Also one last question why does http://schemas.microsoft.com/winfx/2006/xaml/presentation is not accessible?? Is that the reason why VSCode can't provide autocomplete?

6 Comments
2024/04/23
08:28 UTC

2

Where-Object: -Property vs -FilterScript efficiency

A quite straightforward question: while the comparison is a simple one (es: comparing a single property), what is more efficient?

Where-Object -Property PropertyName -eq $Comparison or Where-Object -FilterScript { $_.PropertyName -eq $Comparison }

(using -eq just as example, make it any simple comparison)

the WHY would be interesting as well, as the general pros and cons

5 Comments
2024/04/23
08:15 UTC

0

Trying to enable sensitivity label support in PowerShell

Good afternoon everyone, I've spent hours trying to enable Sensitivity Labels via PowerShell. Specifically I need to set "EnableMIPLabels" to True however I keep receiving the error -

New-MgBetaDirectorySetting : Another object with the same value for property templateId already exists

I am following this Microsoft guide https://learn.microsoft.com/en-us/entra/identity/users/groups-assign-sensitivity-labels I have a Microsoft E5 license assigned to myself and also believe that I have the required privileges. Any pointers are most appreciated, thank you.

2 Comments
2024/04/23
06:24 UTC

0

Organizing my files

Hello, i just became a bit more educated about file management. Prior, id save random stuff all over my laptop. Im currently learning powershell and have a question:

  • how do i determine when files are related in some way? Example: i was cleaning out an old version of software i used years ago. But upon deleting one of the files, my new version of it does not work now. All my downloaded files up to this point were stored in one path. Im currently trying to determine how to untangle this path and remove old stuff.

I know there is software i can use but im trying to learn things via powershell from scratch so i can build a personal app.

Thank you in advanced

4 Comments
2024/04/23
06:17 UTC

1

Azure Pipeline with Powershell task

Hi everyone,

I have a task to download, configure and install the android SDK in the Windows agent via Azure Pipeline.
I have successfully configure the path variable and could run sdkmanager command in powershell.
Unfortunately, when I installing the build tools by using the command below, it asked the accept license and seem it automatically skip this step. This lead to the issue that I cannot install the build tool.
So my question is: how do we pass the "y" or "yes" to the powershell automatically when the accept license question show up?

sdkmanager "build-tools;33.0.2"

The error shows:

Accept? (y/N): Skipping following packages as the license is not accepted:
Android SDK Build-Tools 33.0.2
The following packages can not be installed since their licenses or those of the packages they depend on were not accepted:
  build-tools;33.0.2
1 Comment
2024/04/23
03:06 UTC

2

Pulling CrowdStrike Logs Using PowerShell (Cyber Security)

Does anyone have experience using powershell to pull logs from Crowdstrike? I am a new cyber security developer and my manager wants me to write a script that will allow users to pull host investigate logs from crowdstrike using my script. I have done something similar with Splunk previously but CrowdStrike seems like it will be much more complicated.

I am assuming it will involve rest requests and web requests and authentication but I am struggling with where to begin, any advice?

1 Comment
2024/04/23
00:28 UTC

41

Gotchas when removing old versions of PowerShell

I've been given a task to "remove old versions of PowerShell as they are insecure". Sounds simple, but what are the gotchas with doing this kind of thing? Can anyone point me at a cheat sheet/lessons learned from doing this removal?

I can see the following relevant PowerShell Versions introduced in different Operating Systems:

  • PowerShell v4.0 (Windows 8.1 and Windows Server 2012 R2)
  • PowerShell v5.0 (Windows 10 and Windows Server 2016)
  • PowerShell v6.0 (Windows 10 and Windows Server 2019)
  • PowerShell v7.0 (Windows 10 and Windows Server 2019)

So it would seem that PowerShell 7 is the go. Is there any "OS-level" dependency on the old versions of PowerShell?

EDIT: Well this has been the best response I've ever had to a reddit query! Thanks to all the contributors - I now have a much better understanding of what the issues here are.

27 Comments
2024/04/23
00:14 UTC

26

What’s the best way to do Windows Configuration as Code in 2024?

Is Ansible or Chef still the preferred method for CaC in 2024? I’m reading that PowerShell DSC is sort of dead for on-prem usage, am I understanding this correctly? Looking to bring some of our old fashioned setups into the current year by refactoring how we configure our windows VMs and curious about the best way to do this. Is it going to come down to having to write custom PowerShell modules?

40 Comments
2024/04/22
20:31 UTC

0

Surpress IWR error message

This url doesn't exist but it does redirect to one. However I am getting output based on that redirect, in spite of me not printing anything to the screen, I've also attempted a try/ catch.

How can I suppress this error message?

$url = "https://finviz.com/quote.ashx?t=AUTO&p=d"
$response = Invoke-WebRequest -Uri $url 

thanks,

RogueIT

3 Comments
2024/04/22
19:41 UTC

Back To Top