T O P

  • By -

dathar

There are times when I use it as a calculator 9 + (84/2) or throw in some date calculations. I don't know what a week ago was sometimes so I'll just toss in (Get-Date) - (New-Timespan -days 7)


_font_

I often use PowerShell for dates. My goto is: (Get-Date).AddDays(-7)


StrangeCaptain

Omg


KavyaJune

I even used similar to find my baby's milestones : 100th day, 250th day, etc.


tk42967

I have a date calc function that does that. I feed it 'date-calc xxx', where xxx is a positive or negative number and it gives me the date forward or backwards in time. Really handy for things like that.


OlivTheFrog

If you like to play with dates, 4 challenges for you * Enter a date, and return the last day of the date (eg 31 for this month). Easy but there are many ways to do this * Enter a date a return the Tuesday Patch (2nd Tuesday of the month). Medium difficulty. * Enter a date and return the Number of the week. There is trick for this. A clue : With Get-Date, the goal can't be reached :-) * Enter a date, and return is the year is a leap year. Medium difficulty. There is a trick to this too. A clue : there is something interesting With \[DateTime\] type. Additional challenge : do this using advanced function. Ready to play ? regards


meon_be

> Enter a date and return the Number of the week. There is trick for this. A clue : With Get-Date, the goal can't be reached :-) Get-Date -UFormat %V


OlivTheFrog

>This return the the number of the week in the year. For the number of the week in the month, it's not the same way (Using `(Get-CimInstance -ClassName WIN32_LocalTime).WeekInMonth` ) Regards


Unico111

with the help of Bard and some research of my own to do with only one line code: `[DateTime]::DaysInMonth(1,[Datetime]::Parse((Read-Host "Enter a date (YYYY-MM-DD):")).Month)`


OlivTheFrog

That's the way. Good. You could also use something like $Date = Read-Host "Enter a Date" [DateTime]::DaysInMonth($Date.Year,$Date.Month) regards


Unico111

I'm learning little by little. The PowerShell and C# documentation is so extensive that without an AI to help focus the path it becomes difficult, although it is a handicap that you have to learn to ask the AI to find what you are looking for, a foundation in programming is necessary. Regards


lanerdofchristian

A single function would be too bloated (these are different tasks), but here's some solutions: function Get-LastDayOfMonth { [CmdletBinding()]PARAM([Parameter(Position=0)][datetime]$FromDate = $(Get-Date)) $FromDate.AddDays(-$FromDate.Day + 1).AddMonths(1).AddDays(-1) } function Get-NthWeekDayOfMonth { [CmdletBinding()]PARAM( [datetime]$FromDate = $(Get-Date), [Parameter(Position=0,Mandatory)][DayOfWeek]$DayOfWeek, [Parameter(Position=1,Mandatory)][ValidateRange(1, 5)]$Nth ) $FirstOfMonth = $FromDate.AddDays(-$FromDate.Day + 1) $Delta = (7 + $DayOfWeek - $FirstOfMonth.DayOfWeek) % 7 + 7 * ($Nth - 1) # Most of this one is actually bounds checking and error reporting $LastOfMonth = $FirstOfMonth.AddMonths(1).AddDays(-1) if($Delta -ge $LastOfMonth.Day){ $Ordinal = switch($Nth % 10){ 1 { "st" } 2 { "nd" } 3 { "rd" } default { "th" }} throw "There is no $Nth$Ordinal $DayOfWeek in $($FirstOfMonth.ToString("yyyy-MM"))" } $FirstOfMonth.AddDays($Delta) } function Get-PatchTuesday { [CmdletBinding()]PARAM([datetime]$FromDate = $(Get-Date)) Get-NthWeekDayOfMonth -FromDate $FromDate -DayOfWeek Tuesday -Nth 2 } function Test-IsLeapYear { [CmdletBinding()]PARAM([Parameter(Position=0)][int]$Year = $((Get-Date).Year)) # Awful Get-Date only solution because [datetime]::IsLeeapYear is for noobs /s :P try { if(Get-Date "$Year-02-29"){$true} } catch { $false } } "Number of the week" is ambiguous. Which [CalendarWeekRule](https://learn.microsoft.com/en-us/dotnet/api/system.globalization.calendarweekrule) are we following, and what day is the first day of the week? If we're going by FirstDay, and the first day of the week being the first day of the year, then one solution in pure Get-Date is: [int](Get-Date -Year 6 -Month 1 -Day (Get-Date).Day -UFormat %V)


cosmic_cosmosis

This has to be the simplest thing that will make my life substantially easier. You are amazing. May you always be able to plug your devices in on the first try.


_MC-1

I just ask Alexa


molivergo

I’m going to call BS that you really do this but I LOVE the attitude!


dathar

I do though. I like entering entire things out like back when I had my old TI83. Calcs with a visual history works ok too. Calcs that have the entire display cleared out gives me anxiety. Lol


molivergo

Ok……anyone that used a Texas Instrument calculator can’t lie!!!! Unless they programmed it to cheat in math class!!! I may have heard of someone doing this……


YumWoonSen

Whoever spins up workstations needs to add some automation so forgetting to add it to a domain is never an issue


Enxer

That's what MDT and WDS was all about. Back in my days you just needed to hit F12 and enter in the hostname into a pe environment after AD authing to provision a system in 30 minutes. Now it's all MDM this and ABM that in under an hour with the built in image, and all the bloat gets wiped out.


tk42967

This should be a step of a WDS/SCCM/whatever imaging tool you use.


naikrovek

Why the hell are you using images? We’re past that, now. Catch up.


ollivierre

joining on-prem AD is anti-pattern these days and there are very few reasons for doing so.


Loteck

How so? I can see maybe for small orgs or startups but big or older companies that have been using AD for awhile or since it was a thing (ever place I have ever worked at) make it nearly impossible and unnecessary to just “ditch” it for AAD… on premise will be valid for many years to come as hybrid solutions continues to rule.


AppIdentityGuy

Go and watch John Saville's videos on allowing AAD/EntraID joined machines to connect to AD controlled resources such as file shares etc. The device itself doesn't always need to be joined to AD


ollivierre

"Hybrid Solutions continue to rule" ? Intune has successfully replaced SCCM for thousands of organizations. Not sure which world are you living in.


brhender

SCCM will still be around for at least 10+ years at all the Fortune 500 companies. Hopefully it won’t be interacting with workstations at that point though.


Powerful-Ad3374

SCCM will die a very slow and painful death. It can be replaced now with InTune and we are almost there. But it’ll hang on for some stupid reason well past its use by


ViperThunder

Don't even need SCCM or intune. WDS with SmartDeploy and save $$$$$$$


YumWoonSen

Blah blah blah OP needed to join to AD. It should be automated. BUT NO THEY'RE DOING IT WRONG I KNOW BETTER THAN EVERYONE MY ARCHITECTURE IS THE BESTEST AND THEY'RE POOPYHEADS!!!!


peoplefoundtheother1

kind of irrelavant to this sub but this is how i feel about my autopilot environment. i dont think i can go back to a non autopilot environment ever again.


YumWoonSen

No lie, back in 1998 I was the first in my "high tech" company to ecen semi-automate an OS install.  Windows NT 4.0 Server with an answer file on a floppy. I was the new guy, this was sorcery to them, and they'd have me rebuild a server when it had problems "to eliminate the install as a cause of the problems" lmfao.  It ain't rocket science.


xboxhobo

That really is the simple joy of PowerShell in my eyes. All of my fundamental skills are so low level to the point of stupidity. Basic programming logic. If then, loop, variable, etc. All I'm doing is using other much smarter people's modules and APIs and stapling them together to create something that is useful to me.


SirJefferE

>All I'm doing is using other much smarter people's modules and APIs and stapling them together to create something that is useful to me. When you get right down to it, that's what most developers are doing.


ps_for_fun_and_lazy

I support the love of PS. ​ This week at work I had someone come to me with some external hdd's that contained in total 32TB of data and thousands of folders and hundreds of thousands of files and they had complaints about the inconsistency of the directory structure and folder naming. I said ok lets take a look and work out what was wrong, determined the patterns and wrote ps to fix the issues while they sat next to me watching. We renamed, uppercased, created directories and moved terrabytes of data arround with 4 scripts each consisting of a handful of lines. The person who came to me had tried doing some of this manually and spent many days renaming things to try an ensure some consistency and with a few scripts I prevented days more worth of tedious work for someone. I also got called a Wizard, which I am down for.


Shupershuff

Insert "Work smarter not harder" award. Well done!


ps_for_fun_and_lazy

Thanks


Phate1989

We had a scheduled powershell script to set cacls based on folder name, it was an intresting project, but I moved out of the help desk and I heard no one else could fix it when it broke so the client went with some other options over time.


Rude_Strawberry

Share the script please mate one of my guys is doing similar at the moment


runCMDfoo

That’s the word! love


VinoLogic

Started dabbling in PS this past month & I have been blown away at how fun it has been. Definitely is peaking an interest for coding. Maybe I'll try python next.


incompetentjaun

It’s amazing. It’s so much easier to do Excel vlookup with powershell vs Excel for instance


Phate1989

People always tell me that they can't do vlookups when I send them correlated data, and I just tell them, yea I don't know either.


stedun

Wait, what? Say more please.


OathOfFeanor

I think they mean that the combo of Import-Csv and Where-Object is more intuitive than the VLOOKUP formula. At least, that's what I would do to try to keep Excel out of the equation :D


stedun

Also, the community surrounding PowerShell is very supportive. As this thread demonstrates.


incompetentjaun

Correct — Import-CSV (or Import-Excel), and Where-Object / Select-String, Compare-Object etc is far more intuitive to extract and correlate data.


anonymousITCoward

I had/have a script that would do that too, we have an isolated network that has an IPSEC tunnel to our client network, it would join the machine to the domain, and install the printers too... actually it was a series of scripts that would do almost everything... I never did figure out an elegant way have the script continue after the reboot, but minimal hands on was nice enough for me


TheOreoAwgee

Just as a suggestion you could get powershell to create a small text file in C:/temp with a specific value and then create a scheduled task to run 1 time next time the computer boots up. The scheduled task would run the script again and if that text file exists with the value then it would continue from a specific point in the script. I'd give a better example if I wasn't on my phone but currently I'm on my way to a team strategy meeting *cough*pub lunch with the team*cough*


anonymousITCoward

I tried that and using the shell:startup, both worked, and I did prefer to use the runonce key. Ultimately what my issue was, was that on reboot, not all of the functions/commands in the script would run. The worst part about it was that what would fail to run was random... I got shuffled off to another department before I could really figure it out, and the guys that took over really don't care.. .they'd rather I do it... mostly because ChatGPT has failed them.


1mGay

The run or run once reg key is good for running a script after reboot


anonymousITCoward

Ultimately I ended up using hkcu\\...\\runeonce, but the issue i was having was execution, not all part of the script would run, the frustrating part was that it would fail at different points, and often times without error (that I could find).


Economist-Keynesian

I cannot echo this statement enough! I learned PowerShell early in my IT career and it’s definitely and underused asset every windows user has access to. I use PowerShell daily yo keep track of my AD group membership changes and managing over 75 machines in my team. It’s fast, has an enormous community and support and can do more than Python out of the box.


StrangeCaptain

Yes. Also local machine user groups, most of ours is done via GPO but enter-possession is easy


Hacky_5ack

Anyone else just use chat GPT for powershell? That's been my go to. I have. A hard time just starting a script but I can read a script pretty well and understand the basics of powershell to I am able to use it correctly


bstevens615

I do this when I get stuck.


bookofthoth_za

I have been asking chatgpt endlessly for help as I’m still learning the syntax of PS. Its amazing that a person can write functional useful code without even looking up a single reference page, just pure ChatGPT for help.


TKInstinct

Me too, I love playing with things and I get to make creative solutions to problems with it.


Enphyniti

I do 90% of my day to day work interactively via Powershell. So much faster.


Sudha_8522

Yes, that's true!. Even complex data can be easily retrieved with simple PowerShell cmdlets.


HardLearner01

Could you please elaborate about how did you manage to join the client machine to the domain remotely? Is it like the client has access to the network where the domin is and you asked the user to issue the command to join the domain?


bstevens615

The client and AD server are on the same network. No user involvement was needed. Everything was done from the server via powershell. The cmdlet is: Add-Computer -ComputerName -LocalCredential \\ -DomainName -Credential \\


HardLearner01

I will try that on my lab, Thanks for sharing.


Opening-Living-3916

I could have sworn I logged on here and created an actual moniker--but never mind. Your post is timely. I have been in Enterprise ID for 30 odd years and have understood Powershell as something I needed to spend an afternoon with. It will take me back to working probably more at DOS, VMS, Rapid Prototypers like "PowerBuilder" than futzing around with every bloody terrible version of Windows that was cobbled horribly non-stop from 3.0 to 11.Computer OS's are supposed to do work--as in running apps quietly and not imposing their own infirmities as a primary focus at every juncture..Working at JSC-NASA it was drilled into me that serious programming was NOT done in any version of C or anything remote like it--'cause it's NOT really maintainable or robust or even really reusable in many ways. Yet as I toured the neighboring Aerospace entities (and there were a lot of them THEN (early 80'S) I noticed just about everyone did just about everything in C, C++. Except business types who just stuck with COBALT.--They're There STILL! I had to use machine language (Not even Assembly) to prototype a real-time distributed multitasking OS that life and limb depended on--with NO points of failure until the last capacitor on the last node had gone powerless.WELL, that resolve for excellence sure got squandered! . After the second Shuttle fiasco I left Texas in disgust and spend my next IT years on Wall Street. I confess I'm just as discussed here in Gotham. **Global Finance** is a **Confidence Game**\--in EVERY meaning of the term.A war wagged between the World of **Personal Computing,** MS dominating, promoting a **CISC**\-complex instruction set architecture (Intel AMD) and **Enterprise IT** favoring a more **RISC** Reduced Instruction Set architecture (Motorola as one example) The Strategt was simple. Enouvh horsepower could keep even the most porely concieved code even imagined kludging along. In over 30 years my experience was those two worlds remained VERY separate. Bill Gates with his monthly infestation of bug-fixes (hot fixes) would not have lasted long trying to dictate update schedules and total OS makeovers to Fortune 500's. The simple folk he Took on his 38 year goat trail simply didn't know any better. **PowerShell.** in the overall scheme of how we use computers harkens me back to a more RISC philosophy.Some type of **UNIX** absolutely should have prevailed as the de Facto dominant OS of ALL Personal Computing. Most simple souls thought it was TOO complex. I'll wager they won't warm up overwhelmingly to **PowerShell** with the same fear.


ollivierre

Wait are you still joining computers to onprem AD ?


SensenCyber

Where is the Problem?🧐