TipsAndTricks
- How to Run PowerShell Code Only During Certain Times
When you have a PowerShell command running inside a loop, you may not want it to execute continuously. For example, you might want a script to run only during business hours, between scheduled maintenance windows, or during a specific overnight period.
PowerShell makes this straightforward by comparing the current time with a start and end time.
Checking Whether the Current Time Is Within a Range
The current time can be retrieved with:
- How to Update a File's Creation Time in PowerShell
PowerShell makes it easy to update the creation time for files in a directory:
Get-ChildItem -File | ForEach-Object { $_.CreationTime = Get-Date }This command finds every file in the current directory and sets its creation time to the current date and time.
But what if you only want to update a single file?
Update One File
Use
Get-Itemto reference the file directly:(Get-Item ".\example.txt").CreationTime = Get-DateReplace
example.txtwith the name of your file. You can also provide the full path: - When Environment Variables Mysteriously Reset...
Ran into a frustrating issue recently where a custom environment variable kept resetting itself every time a system rebooted. I wasn’t sure what was causing this I was notified that the team had changed all necassary items to correct this but it kept occurring. After some digging it turns out it was being overwritten by a GPO startup script.
How did I find it? PowerShell, of course:
Get-ChildItem -Path "\\domain.name\SYSVOL\domain.name\Scripts" -Recurse -File | Select-String -Pattern "MY_ENV_VAR"I searched the SYSVOL scripts directory on the domain controller, and sure enough, one of the logon scripts was setting the variable back to a default value.
- PowerShell Tip from the Trenches: Searching for Text in Files
As a sysadmin, I often find myself digging through logs, config files, and scripts to troubleshoot issues or verify configurations. One of the most useful PowerShell one-liners in my daily toolkit is this:
Get-ChildItem -Path "C:\Your\Directory" -Recurse -File | Select-String -Pattern "YourSearchText"This command recursively scans all files in the specified directory and searches for the string
"YourSearchText". It’s incredibly handy when you’re hunting down error messages, checking for legacy code, or verifying that certain settings are applied across multiple files.