Using Powershell to find only those global holidays that occur today - powershell

I'm new to using Powershell and I'm trying to scrape a website to find ONLY those global holidays occurring today, using the website below.
https://eresearch.fidelity.com/eresearch/markets_sectors/global/holidayCalendar.jhtml
Here is what I've got so far, any help would be greatly appreciated!
$a = Get-Date -UFormat "%m/%d/%y" #to get the date in mm/dd/yy format
$source = "https://eresearch.fidelity.com/eresearch/markets_sectors/global/holidayCalendar.jhtml"
$result = Invoke-WebRequest $source
$d = $result.AllElements | Where Class -eq "layout-calendar-content-column" | Select -ExpandProperty innerText
echo $d
Ideally, it would only show those holidays that match the date contained in the variable $a.

Your script is almost complete. Instead of your echo statement, try this:
$d -split "`n" | ? { $_ -like "*$a*" }
Update: For your use-case
($d | Out-String) -split "`n" | Where-Object { $_ -like "*$a*" }

Related

Powershell - Check if Value in CSV exists

I want to check if a string exists in a csv file.
I'm trying to use if ($PCname -in $logFileLocation) { write-output "true" } else { write-output "false" }
However this always returns false.
How can I check for a value within a csv file?
You can integrate a query within the result of dir ( Get-Childitem )
$Query = "yourString"
$List = Get-Childitem *.CSV |
Select-Object Name,#{Name="MatchesQuery"; Expression={($_ | Get-Content -raw) -match $Query}}
$List
Attention: $Query will be interpreted as regular expression
That way you get a list of all files with the information that it is matching your cirteria or not. That way you can filter afterwards like that:
$List | where {$_.MatchesQuery -eq $true}
Depending in your CSV it might be better and more relyable if you do not only Get-Content but use ConvertFrom-CSV and select the column you want to search in.
This version reads CSV and searches the column "ComputerName" for your $Query
$Query = "yourString"
$List = Get-Childitem *.CSV | Select-Object Name,#{Name="MatchesQuery"; Expression={($_ | Get-Content -raw | ConvertFrom-CSV -Delimiter ";" | where {$_.ComputerName -eq "$Query").Count -gt 0}}}
$List
this could be helpful:
$find = "some_string"
Get-Content C:\temp\demo.csv | Select-String $find

Powershell Select-String how to filter by date?

I have a log file that starts with date format, I want to filter out lines that were added in the past 5min and work on them, but when I run my code it gives me wrong data
Log file Syntax
01/12/2020 00:00:00 log info
Code
$referenceTime = '{0:dd/MM/yyyy HH:mm:ss}' -f (Get-Date).AddMinutes(-5)
Get-Content -Path 'C:\..\data.log' |
Where-Object { (($_ -split '\s')[0] + " " + ($_ -split '\s')[1]) -gt $referenceTime } |
ForEach-Object {
#DO SOMETHING..
}
Dates should be compared to other dates, so you should not stringify them.
Try
$referenceTime = (Get-Date).AddMinutes(-5)
Get-Content -Path 'C:\..\data.log' |
Where-Object { $_ -match '^(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2})' } |
Where-Object { [datetime]::ParseExact($matches[1], 'dd/MM/yyyy HH:mm:ss', $null) -gt $referenceTime } |
ForEach-Object {
$_
#DO SOMETHING.. For demo just output the line(s) that matched
}
The first Where-Object matches any line that starts with what looks like a date in the given format and captures that part of the line in $matches[1].
The second Where-Object parses this matched date into a real [DateTime] object, so you can compare it with the date in $referenceTime

PowerShell script to delete lines with timestamp and blank lines

I'm very new to PowerShell and i'm looking a way to read a file and delete the line if the timestamp is more than 20 days old or blank, and then rewrite it into a new file.
My script is working but if I have a blank line, it fails. Here's the script.
$Culture = [System.Globalization.CultureInfo]::InvariantCulture
$Format = 'dd/MM/yyyy HH:mm:ss'
$Paths = "D:\xxx\yyyy\log.txt","D:\xxx\zzzz\log.txt"
$Day = "20"
Foreach ($Path in $Paths)
{
Get-Content $Path | where { [datetime]::ParseExact(([string]$_).Substring(0,19), $format, $culture) -ge (Get-Date).AddDays(-$Day) } | set-content $Path".new"
}
I try to check if string is null before the where like this
Get-Content $Path | if(!([string]$_)::IsNullOrEmpty) | where { ([datetime]::ParseExact(([string]$_).Substring(0,19), $format, $culture) -ge (Get-Date).AddDays(-$Day)) } | set-content $Path".new"
But it is not working.
if() can't be piped.
You need to use Where-Object similar to the way you already have done:
Get-Content $Path |
Where-Object {$_} |
Where-Object { ([datetime]::ParseExact(([string]$_).Substring(0,19), $format, $culture) -ge (Get-Date).AddDays(-$Day)) } |
Set-Content $Path".new"
Note that {$_} is shorthand for "this has a value"

PowerShell Script to add date to folder name in list of home directories saved in variable

I am a PowerShell newbie. I have a .csv file of users that I pulled a list of home directories for using the following:
$hdirpath = Get-Content C:\Temp\UserList.csv | ForEach {Get-ADUser $_ -properties HomeDirectory | Select HomeDirectory}
Output example of the above looks something like this:
HomeDirectory
\servername\Users\roc03\username
\servername\Users\nov01\username
\servername\Users\roc05\username
Now I want to check if a folder exists in each users path and if it exists, i want to add today's date to the end of that folder name. I know there's a If-Exist-Then command that I might be able to use but I'm not sure how to use it with the information saved in $hdirpath.
Any help would be greatly appreciated. Thanks in advance.
Newbie myself so please forgive any mistakes.
From the top of my head I've got this in mind:
foreach ($path in $hdirpath) {
$folders = Get-ChildItem $_ -Recurse | Where-Object {$_.PSIsContainer -eq $True} | Select-Object FullName
$folders | if ($_.Name -eq "Folder Name") {Rename-Item "Folder Name" + Get-Date}
}
Someone will probably correct me, but if they don't give it a go and let me know if you have any problems.
Also - just for future reference, make sure you include code you have tried before posting a question.
EDIT
So, I've now got the following:
$hdirpath = Get-Content C:\temp\dir.txt
$fullDate = Get-Date
$date = $($fullDate.ToShortDateString())
$day = $date -replace "/", "."
foreach ($path in $hdirpath) {
Get-ChildItem -Path $_ -Recurse | Where-Object {$_.PSIsContainer -eq $true} |
Rename-Item -NewName {if ($_.Name.StartsWith('target') -and $_.Name.EndsWith('folder')) {$_.Name + " " + $($day)}}
}
This returns multiple errors saying that it Cannot evaluate parameter 'NewName' because its argument input did not produce any output., but it works and appends the folder name with the current date.
Line 3-5 get the date and format it with "." rather than "\". You can format this however works for you obviously.
My test structure was "C:\temp\roc6\username1" - with multiple subfolders and multiple 'usernameX'. My test folder to re-name was called "targetfolder". End result ended with "targetfolder 08.03.2017".
Revision
This would be my final run of the script - with my limited knowledge this is the best I can do.
$ErrorActionPreference = "SilentlyContinue"
$hdirpath = Get-Content C:\temp\dir.txt
$fullDate = Get-Date
$day = $($fullDate.ToShortDateString()) -replace "/", "."
foreach ($path in $hdirpath) {
Get-ChildItem -Path $_ -Recurse | Where-Object {$_.PSIsContainer -eq $true} |
Rename-Item -NewName {if ($_.Name.StartsWith('target') -and $_.Name.EndsWith('folder')) {$_.Name + " " + $($day)}}
}

Powershell get-content where-object

Morning, I am new to the world of Windows PowerShell and wondered if someone could advise on the following.
I am searching a txt file for a certain string of text.
Get-Content -Path "filepath" | Where-Object {
$_ -like '*string*'
} | Out-File c:\output.txt
This works OK for me but I want to be a little smarter and only pull back the string for that particular day.
I've tried to use the following
Get-Content -Path "filepath" | Where-Object {
$_ -like Get-Date -DisplayHint Date -UFormat "%d/%m/%y" + '*string*'
} | Out-File c:\output.txt
The line in the text file always starts with the date in that format but then I need to check for a string in the same line?
You need to put the Get-Date in parentheses:
Get-Content -Path "filepath" | Where-Object {
$_ -like (Get-Date -DisplayHint Date -UFormat "%d/%m/%y") + '*string*'
} | Out-File c:\output.txt
So, after trying several attempts, I've noticed that the file I am querying has the date format in MM/dd/yyyy format so this was why I wasn't finding anything.
Also, I needed to look for the previous day as well so added a little bit more in.
Tweaked it slightly and works now
get-content -path "location of text file" | where-object {$_ -like ("{0:MM/dd/yyyy}" -f (get-date).AddDays(-1)) + 'Sqlserver'} | out-file filename
Thanks everyone for your help