PowerShell script to find all maintenance windows in an SCCM environment:
Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts
Wednesday, July 24, 2024
Tuesday, August 14, 2018
Powershell script to determine OS architecture (32bit or 64bit)
This will return either "32" or "64" depending on the OS architecture.
Write-Host (Get-WmiObject -Class Win32_Processor | Select-Object AddressWidth).AddressWidthNOTE: this is OS architecture, not CPU architecture. That is not relevant on 64bit machines, but if you have 32bit Windows running on a 64bit CPU it will return 32.
Labels:
32bit,
64bit,
Architecture,
OS,
PowerShell,
WMI,
x64,
x86
Thursday, February 23, 2017
Powershell Function - Get Occurance of Days of the Week
If you are like me, you keep running into people asking you to set their maintenance windows to the 3rd Saturday of the month or to the 2nd & 4th Friday of each month. To help make it a little easier I've created this function that will return what the 3rd Saturday or the 4th Friday is. Use this to help automate creation of those Maintenance Windows that don't easily fall into SCCM's normal parameters from the console. Enjoy!
<#
.Synopsis
Get-OccuranceOfDayOfWeek returns a specific occurance of a day of the week such as 3rd Saturday
.DESCRIPTION
Get-OccuranceOfDayOfWeek returns a specific occurance of a day of the week
such as the 3rd Saturday or the 1st Friday. Useful for dealing with
maintenance windows that occur on specific occurances of days of the week.
The function only returns occurances within the current month, you will
need to modify it if you need to project further into the future.
It is possible that the 4th or 5th occurance may return a date in the
following month. This is not uncommon with the 5th occurance.
.EXAMPLE
Get-OccuranceOfDayOfWeek -DayOfWeek Tuesday -Occurance 4
Returns: Tuesday, February 28, 2017 11:28:54 PM
.EXAMPLE
Get-OccuranceOfDayOfWeek -DayOfWeek Saturday -Occurance 2
Returns: Saturday, February 11, 2017 11:39:37 PM
.INPUTS
String - Full name of a day of the week (Monday, Tuesday, etc)
Integer - Which occurance to return (1-4)
.OUTPUTS
DateTime - The date of the specified occurance within the current month
.NOTES
# Script by Mark Randol
# randoltech.blogspot.com
#>
function Get-OccuranceOfDayOfWeek{
[CmdletBinding(DefaultParameterSetName='OccuranceOfDayOfWeek',
SupportsShouldProcess=$true,
PositionalBinding=$false)]
[OutputType([DateTime])]
Param(
# Day of the Week
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0,
ParameterSetName='OccuranceOfDayOfWeek')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[ValidateLength(0,15)]
[ValidateSet("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")]
[Alias("day","dayname","dow")]
[String]
$DayOfWeek,
# Occurance
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=1,
ParameterSetName='OccuranceOfDayOfWeek')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[ValidateSet(1,2,3,4)]
[Alias("occ")]
[Int]
$Occurance
)
Begin{
}
Process{
[Int]$TestDayNum = 0
[Arr]$OccuranceDates = @()
do
{
$TestDayNum = $TestDayNum + 1
$TestDayName = (Get-Date -Day $TestDayNum).DayOfWeek
}
until ($TestDayName -eq $DayOfWeek)
$OccuranceDate = $TestDayNum
do{
$OccuranceDates += @($OccuranceDate)
$OccuranceDate = $OccuranceDate + 7
}
while ($OccuranceDate -lt 32)
}
End{
[Int]$OutputInt = $Occurance - 1
[DateTime]$MyOutput = (Get-Date -Year (Get-Date).Year -Month (Get-Date).Month -Day $OccuranceDates[$OutputInt]).Date
Return $MyOutput
}
}
[DateTime]$MyDate = (Get-OccuranceOfDayOfWeek -DayOfWeek Saturday -Occurance 2)
Write-Output $MyDate
Tuesday, March 22, 2016
Determine if a computer is connected via Wired or Wireless network (or both)
This is not the first time this has come up for me and it is not a trivial thing to determine. So here's the PS script to do it. Please give me a thumbs up, a comment, or a link back to this blog if you use it.
There are quite a few lines commented out, they can be uncommented to give you more information about the variables within the script (or you can just delete them if you don't care). I left them there mostly for myself in case I find a use case that I need to know more about the adapters.
There are quite a few lines commented out, they can be uncommented to give you more information about the variables within the script (or you can just delete them if you don't care). I left them there mostly for myself in case I find a use case that I need to know more about the adapters.
#Get-NetConnectionType.ps1
#by Mark Randol
#randoltech.blogspot.net
cls
#PhysicalAdapter cannot be only criteria because, for no apparent reason, some virtual adapters set this to true. Especially VPN adapters.
#AdapterType eliminates anything that is not TCP/IP
#NetConnectionStatus of 2 = connected
$AdapterTypes = (Get-WmiObject -Namespace "root/WMI" -Query "SELECT * FROM MSNdis_PhysicalMediumType")
$Adapters = (Get-WmiObject -class win32_networkadapter | Where-Object {$_.PhysicalAdapter -eq "True" -and $_.AdapterType -eq "Ethernet 802.3" -and $_.NetConnectionStatus -eq "2"})
$NetworkConnected = $false
$WiredConnected = $false
$WirelessConnected = $false
#Spit out a header line with how many adapters are connected
$AdaptersCount = ($Adapters | measure).count
if ($AdaptersCount -lt 1)
{
$HeaderString = "There are no adapters connected"
}
if ($AdaptersCount -eq 1)
{
$HeaderString = "There is $AdaptersCount adapter connected"
}
if ($AdaptersCount -gt 1)
{
#Two or more connected adapters means one of two things:
# a. Both your wired and wireless NICs are currently connected.
# b. You have multiple NICs (generally a server like a Virtual Server Host may have multiple NICs on multiple networks simultaneously).
$HeaderString = "There are $AdaptersCount adapters connected"
}
#Loop through all of the adapters and for each one check its type to see if it is wired or wireless
#Only return those that are connected and are TCP/IP wired or wireless adapters
foreach ($Adapter in $Adapters)
{
foreach ($AdapterType in $AdapterTypes)
{
if ($AdapterType.InstanceName -eq $Adapter.Name)
{
if ($AdapterType.NdisPhysicalMediumType -eq 0)
{
#$AdapterType | format-list -Property [a-z]*
<#write-host ("-------------------------------------------")
$AdapterSettings = (Get-WmiObject -Class win32_NetworkAdapterSetting | where-object {$_.Element -eq $Adapter.Path})
$AdapterOutput = $Adapter.ProductName
$AdapterOutput = $AdapterOutput + ", "
$AdapterOutput = $AdapterOutput + $Adapter.NetConnectionID
$AdapterOutput = $AdapterOutput + ", Wired"
write-host $AdapterOutput
write-host ("-------------------------------------------")#>
$NetworkConnected = $true
$WiredConnected = $true
}
if ($AdapterType.NdisPhysicalMediumType -eq 9)
{
#$AdapterType | format-list -Property [a-z]*
<#write-host ("-------------------------------------------")
$AdapterSettings = (Get-WmiObject -Class win32_NetworkAdapterSetting | where-object {$_.Element -eq $Adapter.Path})
$AdapterOutput = $Adapter.ProductName
$AdapterOutput = $AdapterOutput + ", "
$AdapterOutput = $AdapterOutput + $Adapter.NetConnectionID
$AdapterOutput = $AdapterOutput + ", Wireless"
write-host $AdapterOutput
write-host ("-------------------------------------------")#>
$NetworkConnected = $true
$WirelessConnected = $true
}
}
}
}
write-host ("Network connected = $NetworkConnected - $HeaderString")
write-host ("Connected via a wire = $WiredConnected")
write-host ("Connected wirelessly = $WirelessConnected")
Thursday, March 17, 2016
Determining which users are using offline files
One of my colleagues came to me today seeking advice on how to check which users are using offline files. I honestly don't know why he needs to know this but, according to him, it is something that quite a lot of people on the Internet need to know.
Here's what we came up with...
He provided a registry area:
HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\NetCache\SyncItemLog
Apparently this registry area is something that he found and it is not well known. What he had discovered is that if a user has chosen to use offline files there will be sub-keys generated here. If the user has not turned on offline files then there will not be any sub-keys. The sub-key names are UNC paths to offline file locations.
So, this is where he came to me and said "How do we gather up this information on all of our users?"
What I came up with is two-fold. First I created the PowerShell script below to gather the information into a log file. The problem, however, is that the script must run under the user context of whichever user you want to check. You can't run it as yourself or as system because it would not be able to read items from the other user's HKEY_CURRENT_USER hive.
The solution to the problem of running it as the local user is simply change the $OutputLog variable to point to a central share to which all of the users can write and then create a package with the script. Have the package execute once per user per machine, under the user credentials, and only if a user is logged in.
Hopefully others find this useful. If so, please +1, leave a commment, and/or link back to this blog.
Here's the script:
#Test-OfflineFileUse.ps1
#by Mark Randol
#randoltech.blogspot.net
new-psdrive -Name O -PSProvider FileSystem -Root "\\server\share"
$OutputLog = "O:\OfflineFilesCheck.csv"
Clear-Host
Set-Location -Path "Registry::HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\NetCache"
$SyncItemLogRegKey = (Get-ChildItem -Path . -Name)
IF ($SyncItemLogRegKey -like 'SyncItemLog')
{
$SyncKey = (Get-ChildItem -path .\$SyncItemLogRegKey -Name)
foreach ($SubKey in $SyncKey)
{
if ($SubKey -ne $null)
{
$LogOutputString = $env:USERDOMAIN + '\' + $env:USERNAME + ',' + $env:COMPUTERNAME + ',' + $SubKey
Out-File -FilePath $OutputLog -Append -InputObject $LogOutputString
}
}
}
ELSE
{
$SyncKey = "SyncItemLog registry key does not exist"
$LogOutputString = $env:USERDOMAIN + '\' + $env:USERNAME + ',' + $env:COMPUTERNAME + ',' + $SyncKey
Out-File -FilePath $OutputLog -Append -InputObject $LogOutputString
}
Here's what we came up with...
He provided a registry area:
HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\NetCache\SyncItemLog
Apparently this registry area is something that he found and it is not well known. What he had discovered is that if a user has chosen to use offline files there will be sub-keys generated here. If the user has not turned on offline files then there will not be any sub-keys. The sub-key names are UNC paths to offline file locations.
So, this is where he came to me and said "How do we gather up this information on all of our users?"
What I came up with is two-fold. First I created the PowerShell script below to gather the information into a log file. The problem, however, is that the script must run under the user context of whichever user you want to check. You can't run it as yourself or as system because it would not be able to read items from the other user's HKEY_CURRENT_USER hive.
The solution to the problem of running it as the local user is simply change the $OutputLog variable to point to a central share to which all of the users can write and then create a package with the script. Have the package execute once per user per machine, under the user credentials, and only if a user is logged in.
Hopefully others find this useful. If so, please +1, leave a commment, and/or link back to this blog.
Here's the script:
#Test-OfflineFileUse.ps1
#by Mark Randol
#randoltech.blogspot.net
new-psdrive -Name O -PSProvider FileSystem -Root "\\server\share"
$OutputLog = "O:\OfflineFilesCheck.csv"
Clear-Host
Set-Location -Path "Registry::HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\NetCache"
$SyncItemLogRegKey = (Get-ChildItem -Path . -Name)
IF ($SyncItemLogRegKey -like 'SyncItemLog')
{
$SyncKey = (Get-ChildItem -path .\$SyncItemLogRegKey -Name)
foreach ($SubKey in $SyncKey)
{
if ($SubKey -ne $null)
{
$LogOutputString = $env:USERDOMAIN + '\' + $env:USERNAME + ',' + $env:COMPUTERNAME + ',' + $SubKey
Out-File -FilePath $OutputLog -Append -InputObject $LogOutputString
}
}
}
ELSE
{
$SyncKey = "SyncItemLog registry key does not exist"
$LogOutputString = $env:USERDOMAIN + '\' + $env:USERNAME + ',' + $env:COMPUTERNAME + ',' + $SyncKey
Out-File -FilePath $OutputLog -Append -InputObject $LogOutputString
}
Wednesday, March 9, 2016
Powershell - Ping test a list of servers
It amazes me that if you search "Powershell Ping List Servers" it doesn't return something like this. So, here you go...
# Script by Mark Randol
# randoltech.blogspot.com
# edit the input and output file paths/names at the end of script
# the first line of input file MUST BE ComputerName
# then the list of whatever computers you want to test after that
function Test-ListOfServers
{
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false,
HelpUri = 'http://www.microsoft.com/',
ConfirmImpact='Medium')]
[OutputType([String])]
Param
(
# Computer Name
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0)]
[Alias("computer","comp")]
[String]
$ComputerName
)
Begin
{
}
Process
{
if (test-connection $ComputerName -Count 1 -Quiet)
{
$PingResult="$ComputerName,responds to ping"
}
else
{
$PingResult="$ComputerName,does not respond to ping"
}
out-file -Append -Encoding "Default" -FilePath $OutputFile -InputObject $PingResult
}
End
{
}
}
$InputFile="H:\WindowsPowerShell\PingThese.csv"
$OutputFile="H:\WindowsPowerShell\PingResults.csv"
Import-Csv $InputFile | Test-ListOfServers
Tuesday, March 1, 2016
Loading the SCOM PowerShell Module
Loading the SCOM PowerShell Module
This is a little script that I got from cchamp over on Technet that will allow you to load up the SCOM module into your local PowerShell without having to load the entire SCOM console.-----------------------------------------------------------
-----------------------------------------------------------
$OMCmdletsTest = (Get-Module|% {$_.Name}) -Join ' ' If (!$OMCmdletsTest.Contains('OperationsManager')) { $ModuleFound = $false $SetupKeys = @('HKLM:\Software\Microsoft\Microsoft Operations Manager\3.0\Setup', 'HKLM:\SOFTWARE\Microsoft\System Center Operations Manager\12\Setup') foreach($setupKey in $SetupKeys) { If ((Test-Path $setupKey) -and ($ModuleFound -eq $false)) { $setupKey = Get-Item -Path $setupKey $installDirectory = $setupKey.GetValue('InstallDirectory') $psmPath = $installdirectory + '\Powershell\OperationsManager\OperationsManager.psm1' If (Test-Path $psmPath) { $ModuleFound = $true } } } If ($ModuleFound) { Import-Module $psmPath } else { Import-Module OperationsManager } }
-----------------------------------------------------------
-----------------------------------------------------------
Thanks cchamp.
Subscribe to:
Posts (Atom)