1
0
mirror of https://github.com/jaapbrasser/SharedScripts.git synced 2026-06-14 00:14:16 +02:00

Added all scripts from the TechNet Scripting Gallery to this repository

This commit is contained in:
Jaap Brasser
2016-07-21 13:35:17 +02:00
parent 9e02dda590
commit 61d0164b66
37 changed files with 3189 additions and 5 deletions
@@ -0,0 +1,93 @@
<#
.SYNOPSIS
Script that compares group membership of source users and destination user and adds destination user to source user group
.DESCRIPTION
This script compares the group membership of $sourceacc and $destacc, based on the membership of the source account the destination account is also to these groups. Script outputs actions taken to the prompt. The script can also be run without any parameters then the script will prompt for both usernames.
.PARAMETER Sourceacc
User of which group membership is read
.PARAMETER DestAcc
User that becomes member of all the groups that Sourceacc is member of
.PARAMETER MatchGroup
Supports regular expressions, uses the -match operator to make a select a subset of source user groups to copy to the destination user
.PARAMETER Noconfirm
No user input is required and the script runs automatically
.NOTES
Name: Compare-ADuserAddGroup.ps1
Author: Jaap Brasser
Version: 1.2.0
DateCreated: 2012-03-14
DateUpdated: 2016-01-12
.EXAMPLE
.\Compare-ADuserAddGroup.ps1 testuserabc123 testuserabc456
Description
-----------
This command will add testuserabc456 to all groups that testuserabc123 is a memberof with the exception of all groups testuserabc456 is already a member of.
.EXAMPLE
.\Compare-ADuserAddGroup.ps1 -SourceAcc testuserabc123 -DestAcc testuserabc456 -MatchGroup 'FS_'
Description
-----------
This command will add testuserabc456 to the groups that contain the FS_ string that testuserabc123 is a memberof with the exception of all groups testuserabc456 is already a member of.
#>
param(
[Parameter(Mandatory=$true)]
[string] $SourceAcc,
[Parameter(Mandatory=$true)]
[string] $DestAcc,
[string] $MatchGroup,
[switch] $NoConfirm
)
# Retrieves the group membership for both accounts
$SourceMember = Get-AdUser -Filter {samaccountname -eq $SourceAcc} -Property memberof | Select-Object memberof
$DestMember = Get-AdUser -Filter {samaccountname -eq $DestAcc } -Property memberof | Select-Object memberof
# Checks if accounts have group membership, if no group membership is found for either account script will exit
if ($SourceMember -eq $null) {'Source user not found';return}
if ($DestMember -eq $null) {'Destination user not found';return}
# Uses -match to select a subset of groups to copy to the new user
if ($MatchGroup) {
$SourceMember = $SourceMember | Where-Object {$_.memberof -match $MatchGroup}
}
# Checks for differences, if no differences are found script will prompt and exit
if (-not (Compare-Object $DestMember.memberof $SourceMember.memberof | Where-Object {$_.sideindicator -eq '=>'})) {write-host "No difference between $SourceAcc & $DestAcc groupmembership found. $DestAcc will not be added to any additional groups.";return}
# Routine that changes group membership and displays output to prompt
compare-object $DestMember.memberof $SourceMember.memberof | where-object {$_.sideindicator -eq '=>'} |
Select-Object -expand inputobject | foreach {write-host "$DestAcc will be added to:"([regex]::split($_,'^CN=|,OU=.+$'))[1]}
# If no confirmation parameter is set no confirmation is required, otherwise script will prompt for confirmation
if ($NoConfirm) {
compare-object $DestMember.memberof $SourceMember.memberof | where-object {$_.sideindicator -eq '=>'} |
Select-Object -expand inputobject | foreach {add-adgroupmember "$_" $DestAcc}
}
else {
do{
$UserInput = Read-Host "Are you sure you wish to add $DestAcc to these groups?`n[Y]es, [N]o or e[X]it"
if (('Y','yes','n','no','X','exit') -notcontains $UserInput) {
$UserInput = $null
Write-Warning 'Please input correct value'
}
if (('X','exit','N','no') -contains $UserInput) {
Write-Host 'No changes made, exiting...'
exit
}
if (('Y','yes') -contains $UserInput) {
compare-object $DestMember.memberof $SourceMember.memberof | where-object {$_.sideindicator -eq '=>'} |
Select-Object -expand inputobject | foreach {add-adgroupmember "$_" $DestAcc}
}
}
until ($UserInput -ne $null)
}
@@ -0,0 +1,105 @@
<#
.SYNOPSIS
Script that compares group membership of source user to destination user, changes destination user group membership
.DESCRIPTION
This script compares the group membership of $SourceAccount and $DestinationAccount, based on the membership of the
source account the destination account is also added to these groups. Script outputs actions taken to the prompt.
The script can also run without any parameters then the script will prompt for both usernames. The GUI is intended
to simplify this process and to give a better overview of the action the script intends to perform.
.PARAMETER SourceAccount
User of which group membership is read
.PARAMETER DestinationAccount
User of which group membership will be changed by comparing it to source user
.PARAMETER ComputerName
The netbios name or FQDN of the domain controller which will be queried for the respective users
.NOTES
Name: Compare-ADuserAddGroupGUI.ps1
Author: Jaap Brasser
DateCreated: 2015-03-10
Version: 1.1
Blog: www.jaapbrasser.com
.EXAMPLE
.\Compare-ADuserAddGroupGUI.ps1 testuserabc123 testuserabc456
Description
-----------
This command will add&remove from groups testuserabc456 to match groups that testuserabc123 is a member of the user is
prompted by user interface to confirm these changes.
.EXAMPLE
.\Compare-ADuserAddGroupGUI.ps1
Description
-----------
Will use GUI to prompt for confirmation
#>
param(
$SourceAccount,
$DestinationAccount,
$ComputerName
)
# Load Visual Basic assembly
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
# Load Active Directory Module
Import-Module ActiveDirectory
# Create hashtable for splatting in the Get-ADUser cmdlet
$ADUserSplat = @{
Property = 'memberof'
}
# Checks if both accounts are provided as an argument, otherwise prompts for input
if (-not $SourceAccount) { $SourceAccount = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the name of the account to read the groups from...", "Source Account", "") }
if (-not $DestinationAccount) { $DestinationAccount = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the name of the account to set the groups to...", "Destination Account", "") }
if ($ComputerName) {$ADUserSplat.Server = $ComputerName}
# Retrieves the group membership for both accounts, if account is not found or error is generated the object is set to $null
try { $sourcemember = get-aduser -filter {samaccountname -eq $SourceAccount} @ADUserSplat | select memberof }
catch { $sourcemember = $null}
try { $destmember = get-aduser -filter {samaccountname -eq $DestinationAccount} @ADUserSplat | select memberof }
catch { $destmember = $null}
# Checks if accounts have group membership, if no group membership is found for either account script will exit
if ($sourcemember -eq $null) {[Microsoft.VisualBasic.Interaction]::MsgBox("Source user not found",0,"Exit Message");return}
if ($destmember -eq $null) {[Microsoft.VisualBasic.Interaction]::MsgBox("Destination user not found",0,"Exit Message");return}
# Checks for differences, if no differences are found script will prompt and exit
if (-not (compare-object $destmember.memberof $sourcemember.memberof)) {
[Microsoft.VisualBasic.Interaction]::InputBox("No difference between $SourceAccount & $DestinationAccount groupmembership found. $DestinationAccount will not be added to any additional groups.",0,"Exit Message");return
}
# Prompt for adding user to groups, only prompt when there are changes
if (compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'}) {
$ConfirmAdd = [Microsoft.VisualBasic.Interaction]::MsgBox("Do you want to add `'$($DestinationAccount)`' to the following groups:`n`n$((compare-object $destmember.memberof $sourcemember.memberof |
where-object {$_.sideindicator -eq '=>'} | select -expand inputobject | foreach {([regex]::split($_,'^CN=|,.+$'))[1]}) -join "`n")",4,"Please confirm the following action")
}
# Prompt for removing user from groups, only prompt when there are changes
if (compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '<='}) {
$ConfirmRemove = [Microsoft.VisualBasic.Interaction]::MsgBox("Do you want to remove `'$($DestinationAccount)`' from the following groups:`n`n$((compare-object $destmember.memberof $sourcemember.memberof |
where-object {$_.sideindicator -eq '<='} | select -expand inputobject | foreach {([regex]::split($_,'^CN=|,.+$'))[1]}) -join "`n")",4,"Please confirm the following action")
}
# If the user confirmed adding the groups to the account, the user will be added to the groups
if ($ConfirmAdd -eq "Yes") {
compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} |
select -expand inputobject | foreach {add-adgroupmember "$_" $DestinationAccount}
}
# If the user confirmed removing any groups not present on the source account, the user will be removed from the groups
if ($ConfirmRemove -eq "Yes") {
compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '<='} |
select -expand inputobject | foreach {remove-adgroupmember "$_" $DestinationAccount -Confirm:$false}
}
# Prompt after executing script
[void][Microsoft.VisualBasic.Interaction]::MsgBox("Script successfully executed",0,"Exit Message")
exit
@@ -0,0 +1,24 @@
# Script to move files if the same file is found in folder1 and folder2.
# It recursively goes through both folders and compares the base filename, filename without extension, of
# each file in the first folder. If a match is found both files are moved to a third folder, the
# destination, $destinationfolder.
# Created by Jaap Brasser
$folder1 = ls "e:\1" -recurse
$folder2 = ls "e:\2" -recurse
$destinationfolder = "e:\3"
$folder1count = $folder1.count
$folder2count = $folder2.count
for ($j=0;$j -lt $folder1count;$j++) {
for ($k=0;$k -lt $folder2count;$k++) {
if (compare-object $folder1[$j].basename $folder2[$k].basename -excludedifferent -includeequal) {
move-item $folder1[$j].fullname $destinationfolder -force
move-item $folder2[$k].fullname $destinationfolder -force
$copycount = $copycount + 2
}
}
}
write-host "$copycount Files moved"
+5 -5
View File
@@ -183,12 +183,12 @@ An remote desktop session to server01 will be created using the credentials of c
begin {
[string]$MstscArguments = ''
switch ($true) {
{$Admin} {$MstscArguments += '/admin '}
{$MultiMon} {$MstscArguments += '/multimon '}
{$Admin} {$MstscArguments += '/admin '}
{$MultiMon} {$MstscArguments += '/multimon '}
{$FullScreen} {$MstscArguments += '/f '}
{$Public} {$MstscArguments += '/public '}
{$Width} {$MstscArguments += "/w:$Width "}
{$Height} {$MstscArguments += "/h:$Height "}
{$Public} {$MstscArguments += '/public '}
{$Width} {$MstscArguments += "/w:$Width "}
{$Height} {$MstscArguments += "/h:$Height "}
}
if ($Credential) {
@@ -0,0 +1,195 @@
function Connect-Mstsc {
<#
.SYNOPSIS
Function to connect an RDP session without the password prompt
.DESCRIPTION
This function provides the functionality to start an RDP session without having to type in the password. This version is PowerShell 2 compatible.
.PARAMETER ComputerName
This can be a single computername or an array of computers to which RDP session will be opened
.PARAMETER User
The user name that will be used to authenticate
.PARAMETER Password
The password that will be used to authenticate
.PARAMETER Credential
The PowerShell credential object that will be used to authenticate against the remote system
.PARAMETER Admin
Sets the /admin switch on the mstsc command: Connects you to the session for administering a server
.PARAMETER MultiMon
Sets the /multimon switch on the mstsc command: Configures the Remote Desktop Services session monitor layout to be identical to the current client-side configuration
.PARAMETER FullScreen
Sets the /f switch on the mstsc command: Starts Remote Desktop in full-screen mode
.PARAMETER Public
Sets the /public switch on the mstsc command: Runs Remote Desktop in public mode
.PARAMETER Width
Sets the /w:<width> parameter on the mstsc command: Specifies the width of the Remote Desktop window
.PARAMETER Height
Sets the /h:<height> parameter on the mstsc command: Specifies the height of the Remote Desktop window
.NOTES
Name: Connect-Mstsc
Author: Jaap Brasser
DateUpdated: 2016-01-12
Version: 1.2.2
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Connect-Mstsc.ps1
Description
-----------
This command dot sources the script to ensure the Connect-Mstsc function is available in your current PowerShell session
.EXAMPLE
Connect-Mstsc -ComputerName server01 -User contoso\jaapbrasser -Password supersecretpw
Description
-----------
A remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser
.EXAMPLE
Connect-Mstsc server01,server02 contoso\jaapbrasser supersecretpw
Description
-----------
Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser
.EXAMPLE
server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password supersecretpw -Width 1280 -Height 720
Description
-----------
Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.
.EXAMPLE
server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password supersecretpw -Wait
Description
-----------
RDP sessions to server01 will be created, once the mstsc process is closed the session next session is opened to server02. Using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.
.EXAMPLE
Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password supersecretpw -Admin -MultiMon
Description
-----------
A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /admin and /multimon switches will be set for mstsc
.EXAMPLE
Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password supersecretpw -Public
Description
-----------
A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /public switches will be set for mstsc
.EXAMPLE
Connect-Mstsc -ComputerName 192.168.1.10 -Credential $Cred
Description
-----------
A RDP session to the system at 192.168.1.10 will be created using the credentials stored in the $cred variable
.EXAMPLE
Get-AzureVM | Get-AzureEndPoint -Name 'Remote Desktop' | ForEach-Object { Connect-Mstsc -ComputerName ($_.Vip,$_.Port -join ':') -User contoso\jaapbrasser -Password supersecretpw }
Description
-----------
A RDP session is started for each Azure Virtual Machine with the user contoso\jaapbrasser and password supersecretpw
.EXAMPLE
PowerShell.exe -Command "& {. .\Connect-Mstsc.ps1; Connect-Mstsc server01 contoso\jaapbrasser supersecretpw -Admin}"
Description
-----------
An remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser connecting to the administrative session, this example can be used when scheduling tasks or for batch files.
#>
param (
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias('CN')]
[string[]]$ComputerName,
[Parameter(Position=1)]
[Alias('U')]
[string]$User,
[Parameter(Position=2)]
[Alias('P')]
[securestring]$Password,
[Parameter(Position=3)]
[Alias('C')]
$Credential,
[Alias('A')]
[switch]$Admin,
[Alias('MM')]
[switch]$MultiMon,
[Alias('F')]
[switch]$FullScreen,
[Alias('Pu')]
[switch]$Public,
[Alias('W')]
[int]$Width,
[Alias('H')]
[int]$Height,
[Alias('WT')]
[switch]$Wait
)
begin {
[string]$MstscArguments = ''
switch ($true) {
{$Admin} {$MstscArguments += '/admin '}
{$MultiMon} {$MstscArguments += '/multimon '}
{$FullScreen} {$MstscArguments += '/f '}
{$Public} {$MstscArguments += '/public '}
{$Width} {$MstscArguments += "/w:$Width "}
{$Height} {$MstscArguments += "/h:$Height "}
}
if ($Credential) {
$User = $Credential.UserName
$Password = $Credential.GetNetworkCredential().Password
}
}
process {
foreach ($Computer in $ComputerName) {
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$Process = New-Object System.Diagnostics.Process
# Remove the port number for CmdKey otherwise credentials are not entered correctly
if ($Computer.Contains(':')) {
$ComputerCmdkey = ($Computer -split ':')[0]
} else {
$ComputerCmdkey = $Computer
}
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
$ProcessInfo.Arguments = "/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$Password"
$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$Process.StartInfo = $ProcessInfo
[void]$Process.Start()
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
$ProcessInfo.Arguments = "$MstscArguments /v $Computer"
$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
$Process.StartInfo = $ProcessInfo
[void]$Process.Start()
if ($Wait) {
$null = $Process.WaitForExit()
}
}
}
}
+85
View File
@@ -0,0 +1,85 @@
function Convert-CsvToXlsx {
<#
.SYNOPSIS
Function to convert csv to xlsx
.DESCRIPTION
This script provides the ability to convert csv files to xlsx files via the pipe line or by specifying the file. This function works by using the Excel.Application object, specifically the SaveAs method to store the file in a different format.
.PARAMETER Path
This can be a single file, or the piped input from Get-ChildItem. The script will only attempt to convert files that have .csv as a file extension
.NOTES
Name: Convert-CsvToXlsx
Author: Jaap Brasser
DateUpdated: 2015-06-11
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Convert-CsvToXlsx.ps1
Description
-----------
This command dot sources the script to ensure the Convert-CsvToXlsx function is available in your current PowerShell session
.EXAMPLE
Convert-CsvToXlsx -Path C:\Greatest.csv -Verbose
Description
-----------
Converts the file C:\Greatest.csv to C:\Greatest.xlsx while displaying verbose information
.EXAMPLE
Get-ChildItem C:\Temp -Recurse | Convert-CsvToXlsx -WhatIf
Description
-----------
Use Get-ChildItem to retrieve a list of csv files and pipe it into the Convert-CsvToXlsx function in order to convert all the csv files in the folder and sub-folders to xlsx. The WhatIf parameter prevents the script from taking any action and will only display which files would be converted.
.EXAMPLE
#>
[cmdletbinding(SupportsShouldProcess)]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
Position = 0
)]
$Path
)
begin {
Write-Verbose "Starting $($MyInvocation.Mycommand)"
$Excel = New-Object -ComObject "Excel.Application"
}
process {
foreach ($CurrentPath in $Path) {
if ($CurrentPath.GetType().Name -eq 'String') {
$CurrentPath = Get-Item -Path $CurrentPath -ErrorAction SilentlyContinue
}
Write-Verbose "Current object: $($CurrentPath.FullName)"
if (($CurrentPath.Extension -eq '.csv') -and (-not $CurrentPath.PSIsContainer)) {
if ($PSCmdlet.ShouldProcess($CurrentPath.FullName,'Converting csv to xlsx')) {
$Excel.workbooks.open($CurrentPath.FullName).SaveAs("$($CurrentPath.Directory)\$($CurrentPath.BaseName).xlsx",51)
New-Object -TypeName PSCustomObject -Property @{
FullName = $CurrentPath.FullName
NewName = "$($CurrentPath.Directory)\$($CurrentPath.BaseName).xlsx"
}
}
}
}
}
end {
$Excel.Quit()
Write-Verbose "Ending $($MyInvocation.Mycommand)"
}
}
Get-ChildItem C:\Temp\RotterdamIncident | Convert-CsvToXlsx -Verbose -WhatIf
Convert-CsvToXlsx -Path C:\Temp\RotterdamIncident\fap11.csv -Verbose -WhatIf
+164
View File
@@ -0,0 +1,164 @@
function Set-CredInClip {
<#
.SYNOPSIS
Function to temporarily store encrypted credentials in the clipboard
.DESCRIPTION
This function provides the functionality to to temporarily store encrypted credentials in the clipboard. These encrypted credentials can be manually picked out of the clipboard and converted into a PSCredential object or be directly used for any form of authentication. The Get-CredInClip function can retrieve the information from the clipboard. It should be noted that the data that is stored in the clipboard when this function runs will be gone.
.PARAMETER UserName
The username that will be stored in the clipboard
.PARAMETER Password
The password that will be stored in the clipboard
.PARAMETER Credential
The PowerShell credential object that will be be stored in the clipboard
.NOTES
Name: Set-CredInClip
Author: Jaap Brasser
DateUpdated: 2015-06-25
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\CredInClip.ps1
Description
-----------
This command dot sources the script to ensure the Get-CredInClip and Set-CredInClip functions are available in your current PowerShell session
.EXAMPLE
Set-CredInClip -Credential $Credential
Description
-----------
Sets the credentials stored in $Credential to the clipboard
.EXAMPLE
Set-CredInClip -UserName jaapbrasser -Password (ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force)
Description
-----------
Sets the credentials for UserName jaapbrasser and secure password 'PlainTextPassword' to the clipboard
#>
[cmdletbinding()]
param(
[Parameter(ParameterSetName = "Credentials",
Mandatory = $true,
Position = 0)]
[System.Management.Automation.PSCredential]
$Credential,
[Parameter(ParameterSetName = "UserPass",
Mandatory = $true,
Position = 0)]
[string]
$UserName,
[Parameter(ParameterSetName = "UserPass",
Mandatory = $true,
Position = 1)]
[SecureString]
$Password
)
begin {
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
}
process {
[string]$OutToClip = 'JaapBrasser'*15
if ($MyInvocation.BoundParameters.ContainsKey('Credential')) {
$OutToClip += "`r`n$($Credential.UserName)`r`n"
$OutToClip += $Credential.GetNetworkCredential().SecurePassword | ConvertFrom-SecureString
} elseif ($MyInvocation.BoundParameters.ContainsKey('UserName')) {
$PasswordString = $Password | ConvertFrom-SecureString
$OutToClip += "`r`n$UserName`r`n$PasswordString"
}
[System.Windows.Forms.Clipboard]::SetText($OutToClip)
}
end {
}
}
function Get-CredInClip {
<#
.SYNOPSIS
Function to retrieve stored encrypted credentials in the clipboard
.DESCRIPTION
This function provides the functionality to to retrieve temporarily store encrypted credentials in the clipboard. These credentials should have been stored by the Set-CredInClip function that is included in this package. This function returns a PowerShell credentials object if credentials are found in the clipboard. The Wait parameter can specify a delay, during this time the script polls every 100ms to verify if credentials are stored in the clipboard.
.PARAMETER Wait
The delay for which the script will wait for credentials to be stored in the clipboard
.NOTES
Name: Get-CredInClip
Author: Jaap Brasser
DateUpdated: 2015-06-25
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\CredInClip.ps1
Description
-----------
This command dot sources the script to ensure the Get-CredInClip and Set-CredInClip functions are available in your current PowerShell session
.EXAMPLE
Get-CredInClip
Description
-----------
Function checks once if credentials are found, if credentials are found a PSCredential object is output. Otherwise there is no output.
.EXAMPLE
Get-CredInClip -Wait 120
Description
-----------
Function polls every 100ms to verify if credentials are stored in the clipboard, if no credentials are found before 120 seconds are up the function will stop.
#>
[cmdletbinding()]
[OutputType([System.Management.Automation.PSCredential])]
param(
[int]
$Wait
)
begin {
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$StartTime = Get-Date
}
process {
do {
$ClipText = [System.Windows.Forms.Clipboard]::GetText() -split '\r\n'
if (((Get-Date)-$StartTime).TotalSeconds -ge $Wait) {
$TimeUp = $true
}
if ($ClipText[0] -ceq 'JaapBrasser'*15) {
$CredInClip = $true
}
Start-Sleep -Milliseconds 100
} until (($TimeUp) -or ($CredInClip))
if ($CredInClip) {
$User = $ClipText[1]
$SecurePW = $ClipText[2] | ConvertTo-SecureString
New-Object System.Management.Automation.PSCredential($ClipText[1],$SecurePW)
}
}
end {
}
}
@@ -0,0 +1,86 @@
function Disconnect-LoggedOnUser {
<#
.SYNOPSIS
Function to disconnect a RDP session remotely
.DESCRIPTION
This function provides the functionality to disconnect a RDP session remotely by providing the ComputerName and the SessionId
.PARAMETER ComputerName
This can be a single computername or an array where the RDP sessions will be disconnected
.PARAMETER Id
The Session Id that that will be disconnected
.NOTES
Name: Disconnect-LoggedOnUser
Author: Jaap Brasser
DateUpdated: 2015-06-03
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Disconnect-LoggedOnUser.ps1
Description
-----------
This command dot sources the script to ensure the Disconnect-LoggedOnUser function is available in your current PowerShell session
.EXAMPLE
Disconnect-LoggedOnUser -ComputerName server01 -Id 5
Description
-----------
Disconnect session id 5 on server01
.EXAMPLE
.\Get-LoggedOnUser.ps1 -ComputerName server01,server02 | Where-Object {$_.UserName -eq 'JaapBrasser'} | Disconnect-LoggedOnUser -Verbose
Description
-----------
Use the Get-LoggedOnUser script to gather the user sessions on server01 and server02. Where-Object filters out only the JaapBrasser user account and then disconnects the session by piping the results into Disconnect-LoggedOnUser while displaying verbose information.
#>
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
Position=0
)]
[string[]]
$ComputerName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName
)]
[int[]]
$Id
)
begin {
$OldEAP = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
}
process {
foreach ($Computer in $ComputerName) {
$Id | ForEach-Object {
Write-Verbose "Attempting to disconnect session $Id on $Computer"
try {
rwinsta $_ /server:$Computer
Write-Verbose "Session $Id on $Computer successfully disconnected"
} catch {
Write-Verbose 'Error disconnecting session displaying message'
Write-Warning "Error on $Computer, $($_.Exception.Message)"
}
}
}
}
end {
$ErrorActionPreference = $OldEAP
}
}
+60
View File
@@ -0,0 +1,60 @@
function Get-ComObject {
<#
.Synopsis
Returns a list of ComObjects
.DESCRIPTION
This function has two parameter sets, it can either return all ComObject or a sub-section by the filter parameter. This information is gathered from the HKLM:\Software\Classes container.
.NOTES
Name: Get-ComObject
Author: Jaap Brasser
Version: 1.0
DateUpdated: 2013-06-24
.LINK
http://www.jaapbrasser.com
.PARAMETER Filter
The string that will be used as a filter. Wildcard characters are allowed.
.PARAMETER ListAll
Switch parameter, if this parameter is used no filter is required and all ComObjects are returned
.EXAMPLE
Get-ComObject -Filter *Application
Description:
Returns all objects that match the filter
.EXAMPLE
Get-ComObject -Filter ????.Application
Description:
Returns all objects that match the filter
.EXAMPLE
Get-ComObject -ListAll
Description:
Returns all ComObjects
#>
param(
[Parameter(Mandatory=$true,
ParameterSetName='FilterByName')]
[string]$Filter,
[Parameter(Mandatory=$true,
ParameterSetName='ListAllComObjects')]
[switch]$ListAll
)
$ListofObjects = Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue |
Where-Object {
$_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID")
} | Select-Object -ExpandProperty PSChildName
if ($Filter) {
$ListofObjects | Where-Object {$_ -like $Filter}
} else {
$ListofObjects
}
}
@@ -0,0 +1,134 @@
function Get-ExtensionAttribute {
<#
.Synopsis
Retrieves extension attributes from files or folder
.DESCRIPTION
Uses the dynamically generated parameter -ExtensionAttribute to select one or multiple extension attributes and display the attribute(s) along with the FullName attribute
.NOTES
Name: Get-ExtensionAttribute.ps1
Author: Jaap Brasser
Version: 1.0
DateCreated: 2015-03-30
DateUpdated: 2015-03-30
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.PARAMETER FullName
The path to the file or folder of which the attributes should be retrieved. Can take input from pipeline and multiple values are accepted.
.PARAMETER ExtensionAttribute
Additional values to be loaded from the registry. Can contain a string or an array of string that will be attempted to retrieve from the registry for each program entry
.EXAMPLE
. .\Get-ExtensionAttribute.ps1
Description
-----------
This command dot sources the script to ensure the Get-ExtensionAttribute function is available in your current PowerShell session
.EXAMPLE
Get-ExtensionAttribute -FullName C:\Music -ExtensionAttribute Size,Length,Bitrate
Description
-----------
Retrieves the Size,Length,Bitrate and FullName of the contents of the C:\Music folder, non recursively
.EXAMPLE
Get-ExtensionAttribute -FullName C:\Music\Song2.mp3,C:\Music\Song.mp3 -ExtensionAttribute Size,Length,Bitrate
Description
-----------
Retrieves the Size,Length,Bitrate and FullName of Song.mp3 and Song2.mp3 in the C:\Music folder
.EXAMPLE
Get-ChildItem -Recurse C:\Video | Get-ExtensionAttribute -ExtensionAttribute Size,Length,Bitrate,Totalbitrate
Description
-----------
Uses the Get-ChildItem cmdlet to provide input to the Get-ExtensionAttribute function and retrieves selected attributes for the C:\Videos folder recursively
.EXAMPLE
Get-ChildItem -Recurse C:\Music | Select-Object FullName,Length,@{Name = 'Bitrate' ; Expression = { Get-ExtensionAttribute -FullName $_.FullName -ExtensionAttribute Bitrate | Select-Object -ExpandProperty Bitrate } }
Description
-----------
Combines the output from Get-ChildItem with the Get-ExtensionAttribute function, selecting the FullName and Length properties from Get-ChildItem with the ExtensionAttribute Bitrate
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
$FullName
)
DynamicParam
{
$Attributes = new-object System.Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$AttributeCollection.Add($Attributes)
$Values = @($Com=(New-Object -ComObject Shell.Application).NameSpace('C:\');1..400 | ForEach-Object {$com.GetDetailsOf($com.Items,$_)} | Where-Object {$_} | ForEach-Object {$_ -replace '\s'})
$AttributeValues = New-Object System.Management.Automation.ValidateSetAttribute($Values)
$AttributeCollection.Add($AttributeValues)
$DynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ExtensionAttribute", [string[]], $AttributeCollection)
$ParamDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("ExtensionAttribute", $DynParam1)
$ParamDictionary
}
begin {
$ShellObject = New-Object -ComObject Shell.Application
$DefaultName = $ShellObject.NameSpace('C:\')
$ExtList = 0..400 | ForEach-Object {
($DefaultName.GetDetailsOf($DefaultName.Items,$_)).ToUpper().Replace(' ','')
}
}
process {
foreach ($Object in $FullName) {
# Check if there is a fullname attribute, in case pipeline from Get-ChildItem is used
if ($Object.FullName) {
$Object = $Object.FullName
}
# Check if the path is a single file or a folder
if (-not (Test-Path -Path $Object -PathType Container)) {
$CurrentNameSpace = $ShellObject.NameSpace($(Split-Path -Path $Object))
$CurrentNameSpace.Items() | Where-Object {
$_.Path -eq $Object
} | ForEach-Object {
$HashProperties = @{
FullName = $_.Path
}
foreach ($Attribute in $MyInvocation.BoundParameters.ExtensionAttribute) {
$HashProperties.$($Attribute) = $CurrentNameSpace.GetDetailsOf($_,$($ExtList.IndexOf($Attribute.ToUpper())))
}
New-Object -TypeName PSCustomObject -Property $HashProperties
}
} elseif (-not $input) {
$CurrentNameSpace = $ShellObject.NameSpace($Object)
$CurrentNameSpace.Items() | ForEach-Object {
$HashProperties = @{
FullName = $_.Path
}
foreach ($Attribute in $MyInvocation.BoundParameters.ExtensionAttribute) {
$HashProperties.$($Attribute) = $CurrentNameSpace.GetDetailsOf($_,$($ExtList.IndexOf($Attribute.ToUpper())))
}
New-Object -TypeName PSCustomObject -Property $HashProperties
}
}
}
}
end {
Remove-Variable -Force -Name DefaultName
Remove-Variable -Force -Name CurrentNameSpace
Remove-Variable -Force -Name ShellObject
}
}
+84
View File
@@ -0,0 +1,84 @@
<#
.SYNOPSIS
Script to check files on a range of machines listed in $serverlist. Exports to csv.
.DESCRIPTION
Script to check files on a range of machines listed in $serverlist. The script checks filesize, date modified
and version of the file and writes this to a comma separated value.
.PARAMETER InputFile
The plaintext file containing the hostname or full dns names of the computers that should be queried
.PARAMETER LogFilePath
The path where the log file is generated. This should be a folder as the file name is automatically generated
.PARAMETER PathofFile
This parameter specifies the specific file for which the information is required. By default this is set to
netbt.sys. An example of a correct input for this parameter would be: "\c$\WINDOWS\system32\drivers\netbt.sys"
.NOTES
Name: Get-FileVersion.ps1
Author: Jaap Brasser
DateCreated: 19-06-2012
.LINK
http://www.jaapbrasser.com
.EXAMPLE
Get-FileVersion.ps1 -InputFile C:\ListofServers.txt -LogFilePath C:\Log
Description
-----------
The script will query the systems in the C:\ListofServers.txt file details of all the services. The collected results
will be written to a comma separated file named 'Autolog_GetFileVersion_dd-MM-yyyy_HHmm.ss.csv'. If the file
already exists it will be overwritten. Since -PathofFile is not specified the script will default to
#>
#Set variables for script
param(
$inputfile,
$logfilepath,
$pathoffile = "\c$\WINDOWS\system32\drivers\netbt.sys"
)
# Check parameters
If (!($inputfile)) {Write-Warning "InputFile not specified, please provide this parameter";return}
If (!($logfilepath)) {Write-Warning "LogFilePath not specified, please provide this parameter";return}
If (!(Test-Path $inputfile)) {Write-Warning "Inputfile not found, exiting";return}
If (!(Test-Path $logfilepath)) {Write-Warning "Logfile path not found, exiting";return}
# Get server names from file
$serverlist = @(get-content $inputfile)
# Gets date and reformats to be used in log filename, enabling automagic log creation
$tempdate = (get-date).tostring("dd-MM-yyyy_HHmm.ss")
$logfile = $logfilepath+"\Autolog_GetFileVersion_"+$tempdate+".csv"
# Encoding for output is set to utf8, otherwise excel will not open the .csv files correctly
$exporttofile = "Servername,Filename,Filesize,File Version,Product Version,Last Modified"
$exporttofile | out-file $logfile -append -encoding utf8
for ($j=0;$j -lt $serverlist.count;$j++) {
#Prepare variables and display progress of script
$i = $j + 1
$display = $serverlist[$j]+" *** Server "+$i+" out of "+$serverlist.count
$display
$testping = test-connection -computername $serverlist[$j] -count 1 -quiet
# Loop only executed when ping is successful
if ($testping) {
#Set temporary variable and get file properties
$tempfilepath = "\\"+$serverlist[$j]+$PathofFile
$tempvar = get-item $tempfilepath -Force
#Prepare variables
$tempserver = $serverlist[$j]
$tempversion = $tempvar.versioninfo
#Add information to array that will be written to file at end of script
$exporttofile = $tempserver+","+$tempvar.name+","+$tempvar.length+","+$tempversion.fileversion+","+$tempversion.productversion+","+$tempvar.lastwritetime
$exporttofile | out-file $logfile -append -encoding utf8
}
}
+130
View File
@@ -0,0 +1,130 @@
<#
.SYNOPSIS
Script to read firewall rules and output as an array of objects.
.DESCRIPTION
This script will gather the Windows Firewall rules from the registry and convert the information stored in the registry keys to PowerShell Custom Objects to enable easier manipulation and filtering based on this data.
.PARAMETER Local
By setting this switch the script will display only the local firewall rules
.PARAMETER GPO
By setting this switch the script will display only the firewall rules as set by group policy
.NOTES
Name: Get-FireWallRules.ps1
Author: Jaap Brasser
DateUpdated: 2013-01-10
Version: 1.1
.LINK
http://www.jaapbrasser.com
.EXAMPLE
.\Get-FireWallRules.ps1
Description
-----------
The script will output all the local firewall rules
.EXAMPLE
.\Get-FireWallRules.ps1 -GPO
Description
-----------
The script will output all the firewall rules defined by group policies
.EXAMPLE
.\Get-FireWallRules.ps1 -GPO -Local
Description
-----------
The script will output all the firewall rules defined by group policies as well as the local firewall rules
#>
param(
[switch]$Local,
[switch]$GPO
)
# If no switches are set the script will default to local firewall rules
if (!($Local) -and !($Gpo)) {
$Local = $true
}
$RegistryKeys = @()
if ($Local) {$RegistryKeys += 'Registry::HKLM\System\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules'}
if ($GPO) {$RegistryKeys += 'Registry::HKLM\Software\Policies\Microsoft\WindowsFirewall\FirewallRules'}
Foreach ($Key in $RegistryKeys) {
if (Test-Path -Path $Key) {
(Get-ItemProperty -Path $Key).PSObject.Members |
Where-Object {(@('PSPath','PSParentPath','PSChildName') -notcontains $_.Name) -and ($_.MemberType -eq 'NoteProperty') -and ($_.TypeNameOfValue -eq 'System.String')} |
ForEach-Object {
# Prepare hashtable
$HashProps = @{
NameOfRule = $_.Name
RuleVersion = ($_.Value -split '\|')[0]
Action = $null
Active = $null
Dir = $null
Protocol = $null
LPort = $null
App = $null
Name = $null
Desc = $null
EmbedCtxt = $null
Profile = $null
RA4 = $null
RA6 = $null
Svc = $null
RPort = $null
ICMP6 = $null
Edge = $null
LA4 = $null
LA6 = $null
ICMP4 = $null
LPort2_10 = $null
RPort2_10 = $null
}
# Determine if this is a local or a group policy rule and display this in the hashtable
if ($Key -match 'HKLM\\System\\CurrentControlSet') {
$HashProps.RuleType = 'Local'
} else {
$HashProps.RuleType = 'GPO'
}
# Iterate through the value of the registry key and fill PSObject with the relevant data
ForEach ($FireWallRule in ($_.Value -split '\|')) {
switch (($FireWallRule -split '=')[0]) {
'Action' {$HashProps.Action = ($FireWallRule -split '=')[1]}
'Active' {$HashProps.Active = ($FireWallRule -split '=')[1]}
'Dir' {$HashProps.Dir = ($FireWallRule -split '=')[1]}
'Protocol' {$HashProps.Protocol = ($FireWallRule -split '=')[1]}
'LPort' {$HashProps.LPort = ($FireWallRule -split '=')[1]}
'App' {$HashProps.App = ($FireWallRule -split '=')[1]}
'Name' {$HashProps.Name = ($FireWallRule -split '=')[1]}
'Desc' {$HashProps.Desc = ($FireWallRule -split '=')[1]}
'EmbedCtxt' {$HashProps.EmbedCtxt = ($FireWallRule -split '=')[1]}
'Profile' {$HashProps.Profile = ($FireWallRule -split '=')[1]}
'RA4' {[array]$HashProps.RA4 += ($FireWallRule -split '=')[1]}
'RA6' {[array]$HashProps.RA6 += ($FireWallRule -split '=')[1]}
'Svc' {$HashProps.Svc = ($FireWallRule -split '=')[1]}
'RPort' {$HashProps.RPort = ($FireWallRule -split '=')[1]}
'ICMP6' {$HashProps.ICMP6 = ($FireWallRule -split '=')[1]}
'Edge' {$HashProps.Edge = ($FireWallRule -split '=')[1]}
'LA4' {[array]$HashProps.LA4 += ($FireWallRule -split '=')[1]}
'LA6' {[array]$HashProps.LA6 += ($FireWallRule -split '=')[1]}
'ICMP4' {$HashProps.ICMP4 = ($FireWallRule -split '=')[1]}
'LPort2_10' {$HashProps.LPort2_10 = ($FireWallRule -split '=')[1]}
'RPort2_10' {$HashProps.RPort2_10 = ($FireWallRule -split '=')[1]}
Default {}
}
}
# Create and output object using the properties defined in the hashtable
New-Object -TypeName 'PSCustomObject' -Property $HashProps
}
}
}
@@ -0,0 +1,57 @@
<#
.Synopsis
Queries AD for Group Policy objects
.DESCRIPTION
This script uses the DirectoryServices.DirectorySearcher object to get all or a selection of Group Policy Objects.
.NOTES
Name: Get-GroupPolicyObject.ps1
Author: Jaap Brasser
Version: 1.0
DateCreated: 2013-07-30
DateUpdated: 2013-07-30
.LINK
http://www.jaapbrasser.com
.PARAMETER DisplayName
Optional parameter that contains a LDAP search filter for the displayname property of the group policy objects. Wildcards are allowed.
.EXAMPLE
.\Get-GroupPolicyObject.ps1
Description:
Will display all group policy objects.
.EXAMPLE
.\Get-GroupPolicyObject.ps1 -DisplayName Default*
Description:
Will displays the group policy objects which displaynames start with Default
#>
param(
[Parameter()]
[string]$DisplayName
)
# Defining the parameters for the AD Query
$GPOSearcher = New-Object DirectoryServices.DirectorySearcher -Property @{
Filter = '(objectClass=groupPolicyContainer)'
PageSize = 100
}
# If the DisplayName parameter is specified, then update the LDAP Search filter
if ($DisplayName) {
$GPOSearcher.Filter = "(&(objectClass=groupPolicyContainer)(displayname=$DisplayName))"
}
# Execute query and output as custom objects
$GPOSearcher.FindAll() | ForEach-Object {
New-Object -TypeName PSCustomObject -Property @{
'DisplayName' = $_.properties.displayname -join ''
'DistinguishedName' = $_.properties.distinguishedname -join ''
'CommonName' = $_.properties.cn -join ''
'FilePath' = $_.properties.gpcfilesyspath -join ''
} | Select-Object -Property DisplayName,CommonName,FilePath,DistinguishedName
}
@@ -0,0 +1,103 @@
function Get-LocalLastLogonTime {
<#
.SYNOPSIS
Will check local or remote system for the LastLogin of a certain account
.DESCRIPTION
This script utilizes the WinNT provider to connect to either a local or remote system to establish if and when a user account last logged on that system. If the user is not found or the system does not respond an error will be logged. The function will attempt to output the date as a DateTime object, but if the conversion fails the time will be output as provided by the WinNT provider.
.PARAMETER ComputerName
This can be a single computer name or an array of computer names which will checked for the single user name or list of user names
.PARAMETER UserName
This can be a single user name or an array of user names which will checked for the LastLogin property on the computers specified in the ComputerName parameter
.NOTES
Name: Get-LocalLastLogonTime
Author: Jaap Brasser
DateUpdated: 2015-06-01
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Get-LocalLastLogonTime.ps1
Description
-----------
This command dot sources the script to ensure the Get-LocalLastLogonTime function is available in your current PowerShell session
.EXAMPLE
Get-LocalLastLogonTime -ComputerName localhost -UserName user1,JaapBrasser,administrator
Description
-----------
Will check the system for the LastLogin properties of user1, JaapBrasser and the administrator account.
.EXAMPLE
PowerShell.exe -Command "& {. C:\Scripts\Get-LocalLastLogonTime.ps1; Get-LocalLastLogonTime -ComputerName server1,server2 -UserName JaapBrasser,administrator}"
Description
-----------
Will check server1 and server2 for the LastLogin time of JaapBrasser and administrator. This example is useful for scenarios when scheduling tasks or when executing this PowerShell script from batch files.
#>
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
Position=0
)]
[string[]]
$ComputerName,
[Parameter(
Mandatory
)]
[string[]]
$UserName
)
begin {
$SelectSplat = @{
Property = @('ComputerName','UserName','LastLogin','Error')
}
}
process {
foreach ($Computer in $ComputerName) {
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
foreach ($User in $UserName) {
$ObjectSplat = @{
ComputerName = $Computer
UserName = $User
Error = $null
LastLogin = $null
}
$CurrentUser = $null
$CurrentUser = try {([ADSI]"WinNT://$computer/$user")} catch {}
if ($CurrentUser.Properties.LastLogin) {
$ObjectSplat.LastLogin = try {
[datetime](-join $CurrentUser.Properties.LastLogin)
} catch {
-join $CurrentUser.Properties.LastLogin
}
} elseif ($CurrentUser.Properties.Name) {
} else {
$ObjectSplat.Error = 'User not found'
}
New-Object -TypeName PSCustomObject -Property $ObjectSplat | Select-Object @SelectSplat
}
} else {
$ObjectSplat = @{
ComputerName = $Computer
Error = 'Ping failed'
}
New-Object -TypeName PSCustomObject -Property $ObjectSplat | Select-Object @SelectSplat
}
}
}
}
+76
View File
@@ -0,0 +1,76 @@
<#
.Synopsis
Queries a computer to check for interactive sessions
.DESCRIPTION
This script takes the output from the quser program and parses this to PowerShell objects
.NOTES
Name: Get-LoggedOnUser
Author: Jaap Brasser
Version: 1.2.1
DateUpdated: 2015-09-23
.LINK
http://www.jaapbrasser.com
.PARAMETER ComputerName
The string or array of string for which a query will be executed
.EXAMPLE
.\Get-LoggedOnUser.ps1 -ComputerName server01,server02
Description:
Will display the session information on server01 and server02
.EXAMPLE
'server01','server02' | .\Get-LoggedOnUser.ps1
Description:
Will display the session information on server01 and server02
#>
param(
[CmdletBinding()]
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = 'localhost'
)
begin {
$ErrorActionPreference = 'Stop'
}
process {
foreach ($Computer in $ComputerName) {
try {
quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
$HashProps = @{
UserName = $CurrentLine[0]
ComputerName = $Computer
}
# If session is disconnected different fields will be selected
if ($CurrentLine[2] -eq 'Disc') {
$HashProps.SessionName = $null
$HashProps.Id = $CurrentLine[1]
$HashProps.State = $CurrentLine[2]
$HashProps.IdleTime = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[4..6] -join ' '
$HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '
} else {
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.IdleTime = $CurrentLine[4]
$HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '
}
New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
}
} catch {
New-Object -TypeName PSCustomObject -Property @{
ComputerName = $Computer
Error = $_.Exception.Message
} | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
}
+76
View File
@@ -0,0 +1,76 @@
Function Get-LongPathName {
<#
.SYNOPSIS
Function to get file and folder names with long paths.
.DESCRIPTION
This function requires Robocopy to be installed. Robocopy is used to recursively search through
a folder structure to find file or folder names that have more than a certain number of characters.
The function returns an object with three properties: FullPath,Type and FullPath.
.PARAMETER FolderPath
The path or paths which will be scanned for long path names
.PARAMETER MaxDepth
Specifies the maximum depth for files and folders in a folder structure
.NOTES
Name: Get-LongPathName.ps1
Version: 1.1
Author: Jaap Brasser
DateCreated: 2012-10-05
DateUpdated: 2013-08-28
Site: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
Get-LongPathName -FolderPath 'C:\Program Files'
.EXAMPLE
"c:\test","C:\Deeppathtest" | Get-LongPathName -FolderPath $_ -MaxDepth 200 | ft PathLength,Type,FullPath -AutoSize
#>
param(
[CmdletBinding()]
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string[]]
$FolderPath,
[ValidateRange(10,248)]
[int16]
$MaxDepth=248
)
begin {
if (!(Test-Path -Path $(Join-Path $env:SystemRoot 'System32\robocopy.exe'))) {
write-warning "Robocopy not found, please install robocopy"
return
}
}
process {
foreach ($Path in $FolderPath) {
$RoboOutput = robocopy.exe $Path c:\doesnotexist /l /e /b /np /fp /njh /njs /r:0 /w:0
$RoboOutput | Where-Object {$_} |
ForEach-Object {
$CurrentPath = ($_ -split '\s')[-1]
if ($CurrentPath.Length -gt $MaxDepth) {
New-Object -TypeName PSCustomObject -Property @{
FullPath = $CurrentPath
PathLength = $CurrentPath.Length
Type = if ($CurrentPath.SubString($CurrentPath.Length-1,1) -eq '\') {
'Folder'
} else {
'File'
}
}
}
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
Function Get-MappedDrive {
<#
.SYNOPSIS
This function will return the mapped network drives
.DESCRIPTION
This function requires PowerShell 2.0 and utilizes the Wscript.Network COM object to enumerate the
locally mapped network drives. The output of the Wscipt.Network COM object is a collection of strings.
This function takes those strings and converts it into objects.
.NOTES
Name: Get-MappedDrive
Author: Jaap Brasser
DateCreated: 2014-07-22
Version: 1.0
DateUpdated: -
.LINK
http://www.jaapbrasser.com
.EXAMPLE
Get-MappedDrive
Description
-----------
Returns the mapped network drives as objects. The output is separated in two properties: LocalPath and NetworkPath.
#>
(New-Object -ComObject WScript.Network).EnumNetworkDrives() | ForEach-Object -Begin {
$CreateObject = $false
} -Process {
if ($CreateObject) {
$HashProps.NetworkPath = $_
New-Object -TypeName PSCustomObject -Property $HashProps
$CreateObject = $false
} else {
$HashProps = @{
LocalPath = $_
}
$CreateObject =$true
}
}
}
+65
View File
@@ -0,0 +1,65 @@
function Get-OUwithGPOLink {
<#
.SYNOPSIS
Function that enchances the output of Get-ADOrganizationalUnit with human readable GPO names
.DESCRIPTION
This function requires PowerShell v2 with the ActiveDirectory module. This function is written as
an extensions to the functionality of Get-ADOrganizationUnit and adds an additional property
'FriendlyGPODisplayName' which can be used to identify which GPOs are attached to an OU
.PARAMETER Name
This can either be a string or an array of strings that the funtion will query for. Wildcards are
allowed.
.NOTES
Name: Get-OUWithGPOLink
Author: Jaap Brasser
DateCreated: 2014-07-20
Version: 1.0
DateUpdated: -
.LINK
http://www.jaapbrasser.com
.EXAMPLE
Get-OUWithGPOLink
Description
-----------
Will returns all OUs
.EXAMPLE
'Domain*','Computers' | Get-OUWithGPOLink
Description
-----------
Will search for all OUs matching the Domain* name and an OU named Computers
#>
[CmdletBinding(SupportsShouldProcess=$true)]
Param (
[Parameter( ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$Name
)
Begin {
try {
Import-Module ActiveDirectory -ErrorAction Stop
} catch {
Throw "Active Directory module could not be loaded. $($_.Exception.Message)"
}
} Process {
$Name | ForEach-Object {
Get-ADOrganizationalUnit -Filter "Name -like `'$_`'" -Properties name,distinguishedName,gpLink |
Select-Object -Property *,@{
label = 'FriendlyGPODisplayName'
expression = {
$_.LinkedGroupPolicyObjects | ForEach-Object {
-join ([adsi]"LDAP://$_").displayName
}
}
}
}
}
}
@@ -0,0 +1,223 @@
<#
.SYNOPSIS
Checks if home folder still has an enabled AD account and list size of the folder
.DESCRIPTION
This script queries AD with the name of the home folder. If this query does not result in an account or a disabled account the script will list the folder size with the folder path and error message. The script will output an array of PSObject which can be piped into various Format-* and Export-* Cmdlets.
.PARAMETER HomeFolderPath
This parameter determines which folder should be scanned. A list of all folders will be checked for matching samaccountnames in Active Directory. Any folders that do not have a name that matches a samaccount in AD or that match a disabled account are listed.
.PARAMETER ExcludePath
This parameter determines which folders should be excluded from scanning or moving. This is particularly useful in combination with move item to ensure certain folders are never moved or included in results. This parameter takes fullpath names and can be an array of fullpath names to be excluded.
.PARAMETER SearchBase
This parameter determines what the SearchBase for the AD query is, the LDAP path for an OU should be specified here. This can be used to limit the AD Query to a sub tree within Active Directory
.PARAMETER FolderSize
This parameter determines if the folder size should be retrieved for orphaned home folders. Not specifying this parameter will significantly increase speed of execution.
.PARAMETER MoveFolderPath
Specifying this parameter will move all orphaned folders to the specified folder.
.PARAMETER MoveDisabled
This switch parameter works in combination with the MoveFolderPath parameter, it will also move the homefolders of disabled accounts.
.PARAMETER DisplayAll
This switch parameters will force the script to also display enabled active directory accounts, can be used in combination with -FolderSize parameter.
.PARAMETER UseRobocopy
Setting this switch parameter will enable moving of home folders using Robocopy instead of Move-Item. This can be useful to prevent 'Path is too long' errors
.PARAMETER RegExExclude
Setting this switch parameter will handle the strings in the ExcludePath parameter as regular expressions that will be matched against the FullName property of the scanned folders
.PARAMETER CheckHomeDirectory
Setting this switch parameter will check the full path of the folder against the HomeDirectory attribute of an ADObject, when using this switch make sure that the correct shared folder or DFS path is used, otherwise output can be unreliable
.NOTES
Name: Get-OrphanHomeFolder.ps1
Author: Jaap Brasser
Version: 1.9
DateCreated: 2012-10-19
DateUpdated: 2015-09-23
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server01\Home -FolderSize
Description:
Will list all the folders in the \\Server01\Home path. For each of these folders it will query AD using the foldername, if the query does not return an AD account or a disabled AD account an error will be logged and the size of the folder will be reported
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server01\Home -FolderSize -DisplayAll
Description:
Will list all the folders in the \\Server01\Home path. For each of these folders it will query AD using the foldername, regardless of the AD results folder size will be returned
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server01\Home -SearchBase 'LDAP://OU=YourOU,DC=jaapbrasser,DC=com'
Description:
Will list all the folders in the \\Server01\Home path. For each of these folders it will query AD, only in the YourOU Organizational Unit of the JaapBrasser domain, using the foldername
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server02\Fileshare\Home | Format-Table -AutoSize
Description:
Will list all the folders in the \\Server02\Fileshare\Home. Will wait until all folders are processed before piping the input into the Format-Table Cmdlet and displaying the results in the console.
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server02\Fileshare\Home -MoveFolderPath \\Server03\Fileshare\MovedHomeFolders
Description:
Will list all the folders in the \\Server02\Fileshare\Home folder and will move orphaned folders to \\Server03\Fileshare\MovedHomeFolders while displaying results to console.
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server02\Fileshare\Home -MoveFolderPath \\Server03\Fileshare\MovedHomeFolders -MoveDisabled
Description:
Will list all the folders in the \\Server02\Fileshare\Home folder and will move orphaned folders and folders that have disabled users accounts to \\Server03\Fileshare\MovedHomeFolders while displaying results to console.
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server02\Fileshare\Home -MoveFolderPath \\Server03\Fileshare\MovedHomeFolders -ExcludePath \\Server02\Fileshare\Home\JBrasser,\\\\Server02\Fileshare\Home\MShajin -UseRobocopy
Description:
Will list all the folders in the \\Server02\Fileshare\Home folder and will move orphaned folders using robocopy, excluding JBrasser and MShajin, to \\Server03\Fileshare\MovedHomeFolders while displaying results to console
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\Server02\Fileshare\Home -MoveFolderPath \\Server03\Fileshare\MovedHomeFolders -ExcludePath '\.v2$' -RegExExclude
Description:
Will list all the folders in the \\Server02\Fileshare\Home folder and will move orphaned folders using robocopy, excluding folders that end with .v2
.EXAMPLE
.\Get-OrphanHomeFolder.ps1 -HomeFolderPath \\dfs\share\userfolders\ -CheckHomeDirectory
Description:
Will list all the folders in the \\Server02\Fileshare\Home folder and check against the homedirectory attribute of the AD objects
#>
param(
[Parameter(Mandatory=$true)]
$HomeFolderPath,
$MoveFolderPath,
$SearchBase,
[string[]]$ExcludePath,
[switch]$FolderSize,
[switch]$MoveDisabled,
[switch]$DisplayAll,
[switch]$UseRobocopy,
[switch]$RegExExclude,
[switch]$CheckHomeDirectory
)
# Check if HomeFolderPath is found, exit with warning message if path is incorrect
if (!(Test-Path -LiteralPath $HomeFolderPath)){
Write-Warning "HomeFolderPath not found: $HomeFolderPath"
exit
}
# Check if MoveFolderPath is found, exit with warning message if path is incorrect
if ($MoveFolderPath) {
if (!(Test-Path -LiteralPath $MoveFolderPath)){
Write-Warning "MoveFolderPath not found: $MoveFolderPath"
exit
}
}
# Main loop, for each folder found under home folder path AD is queried to find a matching samaccountname
$ListOfFolders = Get-ChildItem -LiteralPath "$HomeFolderPath" -Force | Where-Object {$_.PSIsContainer}
# Exclude folders if the ExcludePath parameter is given
if ($ExcludePath) {
$ExcludePath | ForEach-Object {
$CurrentExcludePath = $_
if ($RegExExclude) {
$ListOfFolders = $ListOfFolders | Where-Object {$_.FullName -notmatch $CurrentExcludePath}
} else {
$ListOfFolders = $ListOfFolders | Where-Object {$_.FullName -ne $CurrentExcludePath}
}
}
}
$ListOfFolders | ForEach-Object {
$CurrentPath = Split-Path -Path $_ -Leaf
# Construct AD Searcher, add SearchRoot attribute if SearchBase parameter is specified
$ADSearcher = New-Object DirectoryServices.DirectorySearcher -Property @{
Filter = "(samaccountname=$CurrentPath)"
}
if ($SearchBase) {
$ADSearcher.SearchRoot = [adsi]$SearchBase
}
# Use the FullName path to look for a homedirectory attribute and replace the backslash by the \5C LDAP escape character
if ($CheckHomeDirectory) {
$ADSearcher.Filter = "(homedirectory=$($_.FullName -replace '\\','\5C')*)"
}
# Execute AD Query and store in $ADResult
$ADResult = $ADSearcher.Findone()
# If no matching samaccountname is found this code is executed and displayed
if (!($ADResult)) {
$HashProps = @{
'Error' = 'Account does not exist and has a home folder'
'FullPath' = $_.FullName
}
if ($FolderSize) {
$HashProps.SizeinBytes = [long](Get-ChildItem -LiteralPath $_.Fullname -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Exp Sum)
$HashProps.SizeinMegaBytes = "{0:n2}" -f ($HashProps.SizeinBytes/1MB)
}
if ($MoveFolderPath) {
$HashProps.DestinationFullPath = Join-Path -Path $MoveFolderPath -ChildPath (Split-Path -Path $_.FullName -Leaf)
if ($UseRobocopy) {
robocopy $($HashProps.FullPath) $($HashProps.DestinationFullPath) /E /MOVE /R:2 /W:1 /XJD /XJF | Out-Null
} else {
Move-Item -LiteralPath $HashProps.FullPath -Destination $HashProps.DestinationFullPath -Force
}
}
# Output the object
New-Object -TypeName PSCustomObject -Property $HashProps
# If samaccountname is found but the account is disabled this information is displayed
} elseif (([boolean]((-join $ADResult.Properties.useraccountcontrol) -band 2))) {
$HashProps = @{
'Error' = 'Account is disabled and has a home folder'
'FullPath' = $_.FullName
}
if ($FolderSize) {
$HashProps.SizeinBytes = [long](Get-ChildItem -LiteralPath $_.Fullname -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Exp Sum)
$HashProps.SizeinMegaBytes = "{0:n2}" -f ($HashProps.SizeinBytes/1MB)
}
if ($MoveFolderPath -and $MoveDisabled) {
$HashProps.DestinationFullPath = Join-Path -Path $MoveFolderPath -ChildPath (Split-Path -Path $_.FullName -Leaf)
Move-Item -LiteralPath $HashProps.FullPath -Destination $HashProps.DestinationFullPath -Force
}
# Output the object
New-Object -TypeName PSCustomObject -Property $HashProps
# Folders that do have active user accounts are displayed if -DisplayAll switch is set
} elseif ($ADResult -and $DisplayAll) {
$HashProps = @{
'Error' = $null
'FullPath' = $_.FullName
}
if ($FolderSize) {
$HashProps.SizeinBytes = [long](Get-ChildItem -LiteralPath $_.Fullname -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Exp Sum)
$HashProps.SizeinMegaBytes = "{0:n2}" -f ($HashProps.SizeinBytes/1MB)
}
# Output the object
New-Object -TypeName PSCustomObject -Property $HashProps
}
}
+36
View File
@@ -0,0 +1,36 @@
<#
.SYNOPSIS
Function that shows the contents of the Recycle Bin
.DESCRIPTION
This function is intended to compliment the Clear-RecycleBin cmdlet, which does not provide any functionality to view the files that are stored in the Recycle-Bin
.NOTES
Name: Get-RecycleBin
Author: Jaap Brasser
DateCreated: 2015-09-24
DateUpdated: 2015-09-24
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Get-RecycleBin.ps1
Description
-----------
This command dot sources the script to ensure the Get-RecycleBin function is available in your current PowerShell session
.EXAMPLE
Get-RecycleBin
Description
-----------
Executing this function will display the name, size and path of the files stored in the Recycle Bin for the current user
#>
function Get-RecycleBin {
(New-Object -ComObject Shell.Application).NameSpace(0x0a).Items() |
Select-Object Name,Size,Path
}
+96
View File
@@ -0,0 +1,96 @@
Function Get-RemoteProgram {
<#
.Synopsis
Generates a list of installed programs on a computer
.DESCRIPTION
This function generates a list by querying the registry and returning the installed programs of a local or remote computer.
.NOTES
Name: Get-RemoteProgram
Author: Jaap Brasser
Version: 1.2.1
DateCreated: 2013-08-23
DateUpdated: 2015-02-28
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.PARAMETER ComputerName
The computer to which connectivity will be checked
.PARAMETER Property
Additional values to be loaded from the registry. Can contain a string or an array of string that will be attempted to retrieve from the registry for each program entry
.EXAMPLE
Get-RemoteProgram
Description:
Will generate a list of installed programs on local machine
.EXAMPLE
Get-RemoteProgram -ComputerName server01,server02
Description:
Will generate a list of installed programs on server01 and server02
.EXAMPLE
Get-RemoteProgram -ComputerName Server01 -Property DisplayVersion,VersionMajor
Description:
Will gather the list of programs from Server01 and attempts to retrieve the displayversion and versionmajor subkeys from the registry for each installed program
.EXAMPLE
'server01','server02' | Get-RemoteProgram -Property Uninstallstring
Description
Will retrieve the installed programs on server01/02 that are passed on to the function through the pipeline and also retrieves the uninstall string for each program
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
$ComputerName = $env:COMPUTERNAME,
[Parameter(Position=0)]
[string[]]$Property
)
begin {
$RegistryLocation = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\',
'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\'
$HashProperty = @{}
$SelectProperty = @('ProgramName','ComputerName')
if ($Property) {
$SelectProperty += $Property
}
}
process {
foreach ($Computer in $ComputerName) {
$RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Computer)
foreach ($CurrentReg in $RegistryLocation) {
if ($RegBase) {
$CurrentRegKey = $RegBase.OpenSubKey($CurrentReg)
if ($CurrentRegKey) {
$CurrentRegKey.GetSubKeyNames() | ForEach-Object {
if ($Property) {
foreach ($CurrentProperty in $Property) {
$HashProperty.$CurrentProperty = ($RegBase.OpenSubKey("$CurrentReg$_")).GetValue($CurrentProperty)
}
}
$HashProperty.ComputerName = $Computer
$HashProperty.ProgramName = ($DisplayName = ($RegBase.OpenSubKey("$CurrentReg$_")).GetValue('DisplayName'))
if ($DisplayName) {
New-Object -TypeName PSCustomObject -Property $HashProperty |
Select-Object -Property $SelectProperty
}
}
}
}
}
}
}
}
+141
View File
@@ -0,0 +1,141 @@
<#
.SYNOPSIS
Script that returns scheduled tasks on a computer
.DESCRIPTION
This script uses the Schedule.Service COM-object to query the local or a remote computer in order to gather a formatted list including the Author, UserId and description of the task. This information is parsed from the XML attributed to provide a more human readable format
.PARAMETER Computername
The computer that will be queried by this script, local administrative permissions are required to query this information
.NOTES
Name: Get-ScheduledTask.ps1
Author: Jaap Brasser
DateCreated: 2012-05-23
DateUpdated: 2015-08-17
Site: http://www.jaapbrasser.com
Version: 1.3.2
.LINK
http://www.jaapbrasser.com
.EXAMPLE
.\Get-ScheduledTask.ps1 -ComputerName server01
Description
-----------
This command query mycomputer1 and display a formatted list of all scheduled tasks on that computer
.EXAMPLE
.\Get-ScheduledTask.ps1
Description
-----------
This command query localhost and display a formatted list of all scheduled tasks on the local computer
.EXAMPLE
.\Get-ScheduledTask.ps1 -ComputerName server01 | Select-Object -Property Name,Trigger
Description
-----------
This command query server01 for scheduled tasks and display only the TaskName and the assigned trigger(s)
.EXAMPLE
.\Get-ScheduledTask.ps1 | Where-Object {$_.Name -eq 'TaskName') | Select-Object -ExpandProperty Trigger
Description
-----------
This command queries the local system for a scheduled task named 'TaskName' and display the expanded view of the assisgned trigger(s)
.EXAMPLE
Get-Content C:\Servers.txt | ForEach-Object { .\Get-ScheduledTask.ps1 -ComputerName $_ }
Description
-----------
Reads the contents of C:\Servers.txt and pipes the output to Get-ScheduledTask.ps1 and outputs the results to the console
#>
param(
[string]$ComputerName = $env:COMPUTERNAME,
[switch]$RootFolder
)
#region Functions
function Get-AllTaskSubFolders {
[cmdletbinding()]
param (
# Set to use $Schedule as default parameter so it automatically list all files
# For current schedule object if it exists.
$FolderRef = $Schedule.getfolder("\")
)
if ($FolderRef.Path -eq '\') {
$FolderRef
}
if (-not $RootFolder) {
$ArrFolders = @()
if(($Folders = $folderRef.getfolders(1))) {
$Folders | ForEach-Object {
$ArrFolders += $_
if($_.getfolders(1)) {
Get-AllTaskSubFolders -FolderRef $_
}
}
}
$ArrFolders
}
}
function Get-TaskTrigger {
[cmdletbinding()]
param (
$Task
)
$Triggers = ([xml]$Task.xml).task.Triggers
if ($Triggers) {
$Triggers | Get-Member -MemberType Property | ForEach-Object {
$Triggers.($_.Name)
}
}
}
#endregion Functions
try {
$Schedule = New-Object -ComObject 'Schedule.Service'
} catch {
Write-Warning "Schedule.Service COM Object not found, this script requires this object"
return
}
$Schedule.connect($ComputerName)
$AllFolders = Get-AllTaskSubFolders
foreach ($Folder in $AllFolders) {
if (($Tasks = $Folder.GetTasks(1))) {
$Tasks | Foreach-Object {
New-Object -TypeName PSCustomObject -Property @{
'Name' = $_.name
'Path' = $_.path
'State' = switch ($_.State) {
0 {'Unknown'}
1 {'Disabled'}
2 {'Queued'}
3 {'Ready'}
4 {'Running'}
Default {'Unknown'}
}
'Enabled' = $_.enabled
'LastRunTime' = $_.lastruntime
'LastTaskResult' = $_.lasttaskresult
'NumberOfMissedRuns' = $_.numberofmissedruns
'NextRunTime' = $_.nextruntime
'Author' = ([xml]$_.xml).Task.RegistrationInfo.Author
'UserId' = ([xml]$_.xml).Task.Principals.Principal.UserID
'Description' = ([xml]$_.xml).Task.RegistrationInfo.Description
'Trigger' = Get-TaskTrigger -Task $_
'ComputerName' = $Schedule.TargetServer
}
}
}
}
@@ -0,0 +1,34 @@
<#
.SYNOPSIS
Active Directory Script that queries for user accounts that have unchanged passwords for the past 90 days
.DESCRIPTION
This script will return the samaccountname, pwdlastset and if an account is currently enabled or disabled. This script is part of the Active Directory Friday section of my blog.
.NOTES
Name: Get-UnchangedPwdLastSet.ps1
Author: Jaap Brasser
DateCreated: 2013-07-26
DateUpdated: 2015-09-21
Site: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com/active-directory-friday-find-user-accounts-that-have-not-changed-password-in-90-days/
.PARAMETER PwdAge
The number of days since the password has been changed. This value defaults to 90.
#>
param (
$PwdAge = 90
)
$PwdDate = (Get-Date).AddDays(-$PwdAge).ToFileTime()
(New-Object DirectoryServices.DirectorySearcher -Property @{
Filter = "(&(objectclass=user)(objectcategory=person)(pwdlastset<=$PwdDate))"
PageSize = 500
}).FindAll() | ForEach-Object {
New-Object -TypeName PSCustomObject -Property @{
samaccountname = $_.Properties.samaccountname -join ''
pwdlastset = [datetime]::FromFileTime([int64]($_.Properties.pwdlastset -join ''))
enabled = -not [boolean]([int64]($_.properties.useraccountcontrol -join '') -band 2)
}
}
+89
View File
@@ -0,0 +1,89 @@
<#
.SYNOPSIS
Script that gets quantum random numbers from Australian National University
.DESCRIPTION
Script automatically grabs the output from the http site
.PARAMETER Seed
A switch, when entered the script returns 7 converted hexadecimal characters as INT[32] which can be used as a
seed for the built-in Get-Random command.
.PARAMETER Hexchars
This parameters can be an integer between 1 and 15, this specifies the amount of hexadecimal characters the
script will grab from the generator and return.
.PARAMETER Decimal
A switch that specifies whether the output should be decimal, only works in conjunction with Hexchars parameter.
.NOTES
Name: Get-VacuumRandom.ps1
Author: Jaap Brasser
DateCreated: 17-04-2012
Website: http://www.jaapbrasser.com
Blogpost: http://www.jaapbrasser.com/?p=79
.EXAMPLE
.\Get-VacuumRandom.ps1 -Seed
Description
-----------
The script will contact the website of the Australian National Univerity grabbing the first 7 hexadecimal
characters generated by the number generator. This seed could be used to seed the Get-Random PowerShell command
as shown in the next example
.EXAMPLE
get-random -maximum 100 -minimum 50 -SetSeed (.\Get-VacuumRandom.ps1 -Seed)
Description
-----------
By running the script in this fashion the seed provided by the quantum numbers is used as a seed for the random
number generated by the Get-Random Cmdlet.
.EXAMPLE
.\Get-VacuumRandom.ps1 -Hexchars 15
Description
-----------
Returns 15 randomly generated hexadecimal characters
.EXAMPLE
.\Get-VacuumRandom.ps1 -Hexchars 8 -Decimal
Description
-----------
Returns 8 Hexadecimal characters which will be converted to an INT64(Long) integer which ranges from 989680 to
4294967295 or 00000000
#>
param (
[switch]$seed,
[ValidateRange(1,15)]
[int]$hexchars,
[switch]$decimal
)
if (-not $seed -and $hexchars -eq $null) {
Write-Warning "Either Seed or Hexchars parameter should be specified"
return
}
if ($seed) {
# Gather 7 random hexadecimal characters from the
$HexRandom = (invoke-webrequest http://150.203.48.55/RawHex.php | select -expandproperty content |
Foreach-Object {$_.substring($_.IndexOf('<td>'))})[5..11] -join ""
([Convert]::ToInt32($HexRandom, 16))
return
}
$HexRandom = (invoke-webrequest http://150.203.48.55/RawHex.php | select -expandproperty content |
Foreach-Object {$_.substring($_.IndexOf('<td>'))})[5..($hexchars+4)] -join ""
if ($decimal) {
([Convert]::ToInt64($HexRandom, 16))
return
}
else {
$HexRandom.ToUpper()
}
@@ -0,0 +1,96 @@
function Get-ZipFileProperties {
<#
.SYNOPSIS
Function to show detailed information about a zip archive
.DESCRIPTION
This function provides the ability to display detailed information about a compressed archive. Information that this function retrieves are the number of files, folder, compression ratio, compressed size and uncompressed size.
.PARAMETER Path
This can be a single file name or an array of file names. This parameter supports the pipeline and can take input from other cmdlets such as Get-ChildItem
.NOTES
Name: Get-ZipFileProperties
Author: Jaap Brasser
DateUpdated: 2015-10-06
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Get-ZipFileProperties.ps1
Description
-----------
This command dot sources the script to ensure the Get-ZipFileProperties function is available in your current PowerShell session
.EXAMPLE
Get-ChildItem -Filter *.zip | Get-ZipFileProperties
Description
-----------
Use Get-ChildItem to retrieve a list of zip files in the current folder and pipe it into the Get-ZipFileProperties function to retrieve information about these files
.EXAMPLE
Get-ZipFileProperties -Path C:\Users\JaapBrasser\Documents\Archive.zip
Description
-----------
The Get-ZipFileProperties function to retrieves information about Archive.zip
#>
[cmdletbinding()]
param (
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[Alias("FullName")]
$Path
)
begin {
try {
Add-Type -Assembly 'System.IO.Compression.FileSystem'
} catch {
Write-Warning $_.exception.message
}
}
process {
foreach ($CurrentPath in $Path) {
if ($CurrentPath.GetType().Name -eq 'FileInfo') {
$CurrentPath = $CurrentPath.FullName
}
if (Test-Path -LiteralPath $CurrentPath) {
try {
([System.IO.Compression.ZipFile]::Open($CurrentPath,'Read')).Entries | ForEach-Object -Begin {
[long]$TotalFileSize = $null
[long]$TotalFiles = $null
[string[]]$ParentPath = $null
$TotalSize = (Get-Item -LiteralPath $CurrentPath).Length
} -Process {
$TotalFileSize += $_.Length
$TotalFiles++
$ParentPath += Split-Path $_.FullName
} -End {
New-Object -TypeName PSCustomObject -Property @{
FullName = $Path
CompressedSize = $TotalSize
Files = $TotalFiles
Folders = @($ParentPath | Select-Object -Unique).Count - 1
UnCompressedSize = $TotalFileSize
Ratio = "{0:P2}" -f ($TotalSize / $TotalFileSize)
}
}
} catch {
Write-Warning "File '$CurrentPath' is corrupted or not an archive"
}
} else {
Write-Warning "$CurrentPath, path not found"
}
}
}
}
@@ -0,0 +1,76 @@
<#
.SYNOPSIS
Script that retrieves disk information from a list of computer and outputs to csv
.DESCRIPTION
This script reads a list of servers or computer from a plaintext file and read the disk information
using WMI. This information will be written to a comma-separated file containing the computer name,
drive letter, total space, free space and free space percentage. The log file automatically
generates a timestamp so this job can be scheduled as a task without overwriting the previous
log file.
.PARAMETER Listpath
The plaintext file containing
.PARAMETER Logpath
Optional parameter, if not filled in it will default to .\
.NOTES
Name: GetComputerDiskspace.ps1
Author: Jaap Brasser
DateCreated: 23-03-2012
.EXAMPLE
.\GetComputerDiskspace.ps1 computers.txt c:\logs\
Description
-----------
This will read the computer name in the plaintext file, computers.txt and output the logfile to
c:\logs\Available_Diskspace_"+$tempdate+".csv.
#>
#function GetComputerDiskspace {
param
(
[string]$listpath,
[string]$logpath
)
# Get the list of machines for this script if none is set exits script
if (!($listpath)) {"No list of computers specified, exiting";return}
$serverlist = @(get-content $listpath)
# Checks for $logpath if does not exist defaults to .\
if (!($logpath)) {$logpath = ".\"}
# Gets date and reformats to be used in log filename, enabling automagic log creation
$tempdate = (get-date).tostring("dd-MM-yyyy_HHmm.ss")
$logfile = $logpath+"Available_Diskspace_"+$tempdate+".csv"
# Encoding for output is set to utf8, otherwise excel will not open the .csv files correctly
$exporttofile = "Servername,Drive Letter,Total Space(GB),Free Space(GB),Free Percentage"
$exporttofile | out-file $logfile -append -encoding utf8
# Main loop
$count = $serverlist.count
for ($j=0;$j -lt $count;$j++) {
$tempvar = @()
# Prepare variables and display progress of script
write-output ($serverlist[$j],"*** Server",($j+1),"out of",$serverlist.count -join " ")
# Loop only executed when ping is successful
if (test-connection -computername $serverlist[$j] -count 1 -quiet) {
[array]$tempvar = Get-WmiObject win32_logicaldisk -filter "drivetype = '3'" -computername $serverlist[$j] | Select systemname,deviceid,size,freespace
for ($k=0;$k -lt $tempvar.count;$k++) {
$tempoutput = $tempvar[$k]
# Setup line to be written to file
$freespace = "{0:N1}" -f ($tempoutput.freespace/$tempoutput.size*100)
$exporttofile = $tempoutput.systemname+","+$tempoutput.deviceid+","+("{0:N1}" -f ($tempoutput.size/1GB))+","+("{0:N1}" -f ($tempoutput.freespace/1GB))+","+$freespace
# Write to log, UTF8 encoding for .csv
$exporttofile | out-file $logfile -append -encoding utf8
}
}
}
#}
+153
View File
@@ -0,0 +1,153 @@
function Invoke-BossMode {
<#
.SYNOPSIS
Function to show or hide a window using the ShowWindow method
.DESCRIPTION
This script provides the ability to temporarily show or hide a number of windows. The windows can be set to reappear on pressing enter, a time out or a hidden string that should be entered in the correct order. The use case for this script is to temporarily remove a number of applications from view, allowing to work without distractions.
.PARAMETER ProcessName
This can be a single process name or an array of process names which will be hidden by the function
.PARAMETER TimeOut
Optional parameter, changing the default behaviour of waiting for the enter key and instead having a timer to hide the windows for a certain time
.PARAMETER HiddenPassword
Optional parameter, changing the default behaviour of waiting for the enter key and instead setting a hidden string as a password. If 'jaap' as a string is given then the script only shows the windows if the characters are typed in the correct order j a a p, typing jaaap would not unlock the computer but typing jaaapjaap would as the hidden password resets to the first character when an incorrect character is typed.
.PARAMETER NoClear
This parameter can be set to prevent the PowerShell console from being cleared, the default behavior of the script is to clear the PowerShell console
.NOTES
Name: Invoke-BossMode
Author: Jaap Brasser
DateUpdated: 2015-05-29
Version: 1.1
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Invoke-BossMode.ps1
Description
-----------
This command dot sources the script to ensure the Invoke-BossMode function is available in your current PowerShell session
.EXAMPLE
Get-Process calc,notepad | Invoke-BossMode
Description
-----------
Use Get-Process to retrieve a list of applications and pipe it into the Invoke-BossMode function to hide the windows until enter is pressed
.EXAMPLE
Invoke-BossMode -TimeOut 5 -ProcessName powershell_ise
Description
-----------
Will hide the powershell_ise while clearing the console and the window will be visible again after five seconds
.EXAMPLE
Invoke-BossMode -TimeOut 5 -ProcessName calc,notepad -NoClear
Description
-----------
Will hide the calc and notepad windows while not clearing the console and the windows will be visible again after five seconds
.EXAMPLE
'wordpad','notepad','calc' | Invoke-BossMode -NoClear -TimeOut 10
Description
-----------
Hide wordpad, notepad and calc for 10 seconds without clearing the console
.EXAMPLE
PowerShell.exe -Command "& {. C:\Scripts\Invoke-BossMode.ps1; Invoke-BossMode -TimeOut 5 -ProcessName powershell_ise}"
Description
-----------
Will hide the powershell_ise while clearing the console and the window will be visible again after five seconds. This example can be used when scheduling tasks or for batch files.
.EXAMPLE
'notepad' | Invoke-BossMode -HiddenPassword Jaap
Description
-----------
Pipe the string notepad into Invoke-BossMode and clear the console. The windows will only reappear if the secret password is typed in the correct order in the PowerShell console
.EXAMPLE
function ivb {Invoke-BossMode -ProcessName notepad -TimeOut 2}
Description
-----------
Create a function to run the Invoke-BossMode with a number of pre-defined parameters to quickly be able to Invoke-BossMode without have to type the full command
#>
[cmdletbinding(SupportsShouldProcess,DefaultParametersetName="WaitForEnter")]
param (
[Parameter(ParameterSetName="WaitForEnter")]
[Parameter(ParameterSetName="TimeOut")]
[Parameter(ParameterSetName="HiddenPassword")]
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
$ProcessName,
[Parameter(ParameterSetName="TimeOut")]
[int]
$TimeOut,
[Parameter(ParameterSetName="HiddenPassword")]
[string]
$HiddenPassword,
[switch]
$NoClear
)
begin {
if (-not $NoClear) {
Clear-Host
}
$TypeSplat = @{
Name = 'Win'
NameSpace = 'Native'
Member = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
}
Add-Type @TypeSplat
[array]$Handles = $null
}
process {
foreach ($Process in $ProcessName) {
$Temp += $Process
$Handles += Get-Process $Process -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty MainWindowHandle |
Select-Object -Unique |
Where-Object {$_ -ne 0}
}
$Handles | ForEach-Object {
$null = [Native.Win]::ShowWindow($_, 0)
}
}
end {
if ($TimeOut) {
Start-Sleep -Seconds $TimeOut
} elseif ($HiddenPassword) {
for ($i = 0; $i -lt $HiddenPassword.Length; $i++) {
$KeyPress = [System.Console]::ReadKey($true)
if ($KeyPress.KeyChar -ne $HiddenPassword[$i]) {
$i = 0
}
}
} else {
Read-Host 'Press Enter to continue. . .'
}
$Handles | ForEach-Object {
$null = [Native.Win]::ShowWindow($_, 1)
}
}
}
@@ -0,0 +1,147 @@
function Invoke-BossMode {
<#
.SYNOPSIS
Function to show or hide a window using the ShowWindow method
.DESCRIPTION
This script provides the ability to temporarily show or hide a number of windows. The windows can be set to reappear on pressing enter, a time out or a hidden string that should be entered in the correct order. The use case for this script is to temporarily remove a number of applications from view, allowing to work without distractions.
.PARAMETER ProcessName
This can be a single process name or an array of process names which will be hidden by the function
.PARAMETER TimeOut
Optional parameter, changing the default behaviour of waiting for the enter key and instead having a timer to hide the windows for a certain time
.PARAMETER HiddenPassword
Optional parameter, changing the default behaviour of waiting for the enter key and instead setting a hidden string as a password. If 'jaap' as a string is given then the script only shows the windows if the characters are typed in the correct order j a a p, typing jaaap would not unlock the computer but typing jaaapjaap would as the hidden password resets to the first character when an incorrect character is typed.
.PARAMETER NoClear
This parameter can be set to prevent the PowerShell console from being cleared, the default behavior of the script is to clear the PowerShell console
.NOTES
Name: Invoke-BossMode
Author: Jaap Brasser
DateUpdated: 2015-05-29
Version: 1.1
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Invoke-BossMode.ps1
Description
-----------
This command dot sources the script to ensure the Invoke-BossMode function is available in your current PowerShell session
.EXAMPLE
Get-Process calc,notepad | Invoke-BossMode
Description
-----------
Use Get-Process to retrieve a list of applications and pipe it into the Invoke-BossMode function to hide the windows until enter is pressed
.EXAMPLE
Invoke-BossMode -TimeOut 5 -ProcessName powershell_ise
Description
-----------
Will hide the powershell_ise while clearing the console and the window will be visible again after five seconds
.EXAMPLE
Invoke-BossMode -TimeOut 5 -ProcessName calc,notepad -NoClear
Description
-----------
Will hide the calc and notepad windows while not clearing the console and the windows will be visible again after five seconds
.EXAMPLE
'wordpad','notepad','calc' | Invoke-BossMode -NoClear -TimeOut 10
Description
-----------
Hide wordpad, notepad and calc for 10 seconds without clearing the console
.EXAMPLE
PowerShell.exe -Command "& {. C:\Scripts\Invoke-BossMode.ps1; Invoke-BossMode -TimeOut 5 -ProcessName powershell_ise}"
Description
-----------
Will hide the powershell_ise while clearing the console and the window will be visible again after five seconds. This example can be used when scheduling tasks or for batch files.
.EXAMPLE
'notepad' | Invoke-BossMode -HiddenPassword Jaap
Description
-----------
Pipe the string notepad into Invoke-BossMode and clear the console. The windows will only reappear if the secret password is typed in the correct order in the PowerShell console
.EXAMPLE
function ivb {Invoke-BossMode -ProcessName notepad -TimeOut 2}
Description
-----------
Create a function to run the Invoke-BossMode with a number of pre-defined parameters to quickly be able to Invoke-BossMode without have to type the full command
#>
[cmdletbinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
$ProcessName,
[int]
$TimeOut,
[string]
$HiddenPassword,
[switch]
$NoClear
)
begin {
if (-not $NoClear) {
Clear-Host
}
$TypeSplat = @{
Name = 'Win'
NameSpace = 'Native'
Member = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
}
Add-Type @TypeSplat
[array]$Handles = $null
}
process {
foreach ($Process in $ProcessName) {
$Temp += $Process
$Handles += Get-Process $Process -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty MainWindowHandle |
Select-Object -Unique |
Where-Object {$_ -ne 0}
}
$Handles | ForEach-Object {
$null = [Native.Win]::ShowWindow($_, 0)
}
}
end {
if ($TimeOut) {
Start-Sleep -Seconds $TimeOut
} elseif ($HiddenPassword) {
for ($i = 0; $i -lt $HiddenPassword.Length; $i++) {
$KeyPress = [System.Console]::ReadKey($true)
if ($KeyPress.KeyChar -ne $HiddenPassword[$i]) {
$i = 0
}
}
} else {
Read-Host 'Press Enter to continue. . .'
}
$Handles | ForEach-Object {
$null = [Native.Win]::ShowWindow($_, 1)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
<#
.SYNOPSIS
Script to read and store the password value of a user credential as a securestring to/from file
.DESCRIPTION
Script with both both the ability to set and get. When the Set switch is specified the script will prompt for credentials
and write the password to the file file specified. When the script is running with the Get switch the script will read the password
from the file specified in the $filename variable and use the username specified in the $username variable. This essentially allows you
to runas another identity without having to enter credentials.
.SWITCH Get
This switch runs the script in get mode
.SWITCH Set
This switch runs the script in set mode
.PARAMETER Username
The username to be written to file or to be used with the password that is extracted from the file.
.PARAMETER Filename
Optional parameter, if not filled in it will default to $username.txt with backspaces removed
.NOTES
Name: PowerShellRunAs.ps1
Author: Jaap Brasser
DateCreated: 22-03-2012
.EXAMPLE
.\PowerShellRunAs.ps1 -get contoso\svc_remoterestart \\fileserver\share\file.pwd
Description
-----------
This command will get the password from file.pwd on the fileserver and use that in combination with contoso\svc_remoterestart
to return the $credentials variable which can be directly used in another script. See the next example as to how you can use
this script within another script.
.EXAMPLE
-credential (C:\Script\PowerShellRunAs.ps1 -get contoso\svc_remoterestart \\fileserver\share\file.pwd)
Description
-----------
This command will get the password from file.pwd on the fileserver and use that in combination with contoso\svc_remoterestart
to return the $credentials variable directly into -credential. This allows you to run as a different user and can be used in
certain scheduled tasks or scripts in which typing the command can be bothersome.
.EXAMPLE
-credential (PowerShellRunAs -get contoso\svc_remoterestart)
Description
-----------
This third example when you run the command as a function within your script. Because the filename was omitted the script will
try and look for a standard filename in this case .\contoso_svc_remoterestart.pwd. Other than that is functions the same as the
previous two examples and allows you to directly use the credentials to run an application as a different identity.
.EXAMPLE
.\PowerShellRunAs.ps1 -set contoso\svc_remoterestart \\fileserver\share\file.pwd
Description
-----------
The last example shows how you can write the credentials to file. By running this a pop up will appear in which the password can
be entered. After clicking okay the password will be written to file as a PowerShell securestring.
#>
#function PowerShellRunAs {
param
(
[string]$username,
[string]$filename,
[switch]$get,
[switch]$set
)
# Checks whether the correct values have been entered for this script to run, exits otherwise
if (!($get) -and !($set)) {write-output "No get or set, exiting script";return}
if (($get) -and ($set)) {write-output "Both get and set specified, exiting script";return}
if (!($username)) {write-output "No username specified";return}
if (!($filename)) {$filename = ($username -replace "\\", "_")+".pwd"}
# Runs the get sequence of the script, exits function if $filename is not found. Outputs $credential which can be used
# in combination with -credential
if ($get)
{
if (!(test-path $filename)) {write-output "File not found $filename, exiting script";return}
$password = Get-Content $filename | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username,$password)
$credential
return
}
# Runs the set sequence of the script where the password securestring is written to file
# Erroractionpreference is set to suppress errors when user closes credentials input
if ($set)
{
$erroractionpreference = 0
$credential = Get-Credential -Credential $username
$credential.Password | ConvertFrom-SecureString | Set-Content $filename
return
}
#}
@@ -0,0 +1,21 @@
' If no argument is supplied then script is executed on local computer
set args = Wscript.Arguments
If Wscript.Arguments.Count = 0 Then
strComputer = "."
Else
strComputer = args.item(0)
end if
'Query WMI
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_PnPSignedDriver where deviceclass = 'net'")
'Output to console
For Each objItem in colItems
Wscript.Echo "DeviceName: " & objItem.DeviceName
Wscript.Echo "DriverProviderName: " & objItem.DriverProviderName
Wscript.Echo "DriverVersion: " & objItem.DriverVersion
Wscript.Echo "InfName: " & objItem.InfName
Wscript.Echo "IsSigned: " & objItem.IsSigned
Wscript.Echo "Signer: " & objItem.Signer
Next
@@ -0,0 +1,96 @@
<#
.SYNOPSIS
Function to delete scheduled tasks
.DESCRIPTION
This function provides the possibility to remove scheduled tasks either locally or remotely. It was written after I received a request from Wulfioso to be able to delete scheduled tasks. This script can either take output from my Get-ScheduledTask.ps1 through the pipeline or a ComputerName and Path to a task can be specified. This function supports the WhatIf and Confirm switch parameters.
.PARAMETER ComputerName
This parameter contains the computername from which a task should be deleted
.PARAMETER Path
This parameter specifies the path of task that should be deleted. This should be in the following format: '\Folder\SubFolder\TaskName'
.NOTES
Name: Remove-ScheduledTask
Author: Jaap Brasser
DateUpdated: 2015-08-06
Version: 1.0
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Remove-ScheduledTask.ps1
Description
-----------
This command dot sources the script to ensure the Remove-ScheduledTask function is available in your current PowerShell session
.EXAMPLE
Remove-ScheduledTask -ComputerName JaapTest01 -Path '\Folder\YourTask'
Description
-----------
Will remove the YourTask task from the JaapTest01 system
.EXAMPLE
.\Get-ScheduledTask.ps1 | Where-Object {$_.State -eq 'Disabled'} | Remove-ScheduledTask -WhatIf
Description
-----------
Get-ScheduledTask will list all the disabled tasks on a system and the Remove-ScheduledTask function will list all the actions that could be taken
.EXAMPLE
.\Get-ScheduledTask.ps1 | Remove-ScheduledTask -Confirm
Description
-----------
Will go through all the tasks on the local system and ask for confirmation before removing any tasks.
#>
function Remove-ScheduledTask {
[cmdletbinding(SupportsShouldProcess = $true)]
param (
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0
)]
[string]
$ComputerName,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 1
)]
[string]
$Path
)
begin {
try {
$Schedule = New-Object -ComObject 'Schedule.Service'
} catch {
Write-Warning "Schedule.Service COM Object not found, this script requires this object"
return
}
}
process {
try {
$Schedule.Connect($ComputerName)
$TaskFolder = $Schedule.GetFolder((Split-Path -Path $Path))
if ($PSCmdlet.ShouldProcess($Path,'Deleting Task')) {
$TaskFolder.DeleteTask((Split-Path -Path $Path -Leaf),0)
}
} catch {
$_.exception.message
}
}
end {
}
}
+44
View File
@@ -0,0 +1,44 @@
Function Search-Msdn {
<#
.Synopsis
Open a Search page on MSDN
.DESCRIPTION
This function takes a searchquery, either a single query or an array and culture value to query MSDN and opens a webpage in the default browser.
.NOTES
Name: Search-Msdn
Author: Jaap Brasser
Version: 1.0
DateUpdated: 2013-06-23
.LINK
http://www.jaapbrasser.com
.PARAMETER SearchQuery
The string or array of string for which a query will be executed
.PARAMETER Culture
The culture for which the search query will be executed. Eg: en-US, de-DE, fr-FR
.EXAMPLE
Search-Msdn -SearchQuery Wscript -Culture de-DE
Description:
Will open a search page on Msdn in German searching for Wscript
.EXAMPLE
Search-Msdn Word.Application
Description:
Will open a search page on Msdn searching for Word.Application using the default culture of en-US
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$SearchQuery,
[System.Globalization.Cultureinfo]$Culture = 'en-US'
)
foreach ($Query in $SearchQuery) {
Start-Process -FilePath "http://social.msdn.microsoft.com/Search/$($Culture.Name)?query=$Query"
}
}
+40
View File
@@ -0,0 +1,40 @@
<#
.Synopsis
Verify Active Directory credentials
.DESCRIPTION
This function takes a user name and a password as input and will verify if the combination is correct. The function returns a boolean based on the result.
.NOTES
Name: Test-ADCredential
Author: Jaap Brasser
Version: 1.0
DateUpdated: 2013-05-10
.PARAMETER UserName
The samaccountname of the Active Directory user account
.PARAMETER Password
The password of the Active Directory user account
.EXAMPLE
Test-ADCredential -username jaapbrasser -password Secret01
Description:
Verifies if the username and password provided are correct, returning either true or false based on the result
#>
function Test-ADCredential {
[CmdletBinding()]
Param
(
[string]$UserName,
[string]$Password
)
if (!($UserName) -or !($Password)) {
Write-Warning 'Test-ADCredential: Please specify both user name and password'
} else {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('domain')
$DS.ValidateCredentials($UserName, $Password)
}
}
+72
View File
@@ -0,0 +1,72 @@
<#
.Synopsis
Check connectivity of a system
.DESCRIPTION
This function pings and opens a connection to the default RDP port to verify connectivity, futhermore it will check if a DNS entry exists and whether there is a computeraccount
.NOTES
Name: Test-ComputerName
Author: Jaap Brasser
Version: 1.0
DateUpdated: 2013-08-23
.LINK
http://www.jaapbrasser.com
.PARAMETER ComputerName
The computer to which connectivity will be checked
.EXAMPLE
Test-ComputerName
Description:
Will perform the ping, RDP, DNS and AD checks for the local machine
.EXAMPLE
Test-ComputerName -ComputerName server01,server02
Description:
Will perform the ping, RDP, DNS and AD checks for server01 and server02
#>
Function Test-ComputerName {
param (
[CmdletBinding()]
[string[]]$ComputerName = $env:COMPUTERNAME
)
begin {
$SelectHash = @{
'Property' = @('Name','ADObject','DNSEntry','PingResponse','RDPConnection')
}
}
process {
foreach ($CurrentComputer in $ComputerName) {
# Create new Hash
$HashProps = @{
'Name' = $CurrentComputer
'ADObject' = $false
'DNSEntry' = $false
'RDPConnection' = $false
'PingResponse' = $false
}
# Perform Checks
switch ($true)
{
{([adsisearcher]"samaccountname=$CurrentComputer`$").findone()} {$HashProps.ADObject = $true}
{$(try {[system.net.dns]::gethostentry($CurrentComputer)} catch {})} {$HashProps.DNSEntry = $true}
{$(try {$socket = New-Object Net.Sockets.TcpClient($CurrentComputer, 3389);if ($socket.Connected) {$true};$socket.Close()} catch {})} {$HashProps.RDPConnection = $true}
{Test-Connection -ComputerName $CurrentComputer -Quiet -Count 1} {$HashProps.PingResponse = $true}
Default {}
}
# Output object
New-Object -TypeName 'PSCustomObject' -Property $HashProps | Select-Object @SelectHash
}
}
end {
}
}
@@ -0,0 +1,44 @@
<#
.Synopsis
Verify Local SAM store
.DESCRIPTION
This function takes a user name and a password as input and will verify if the combination is correct. The function returns a boolean based on the result. The script defaults to local user accounts, but a remote computername can be specified in the -ComputerName parameter.
.NOTES
Name: Test-LocalCredential
Author: Jaap Brasser
Version: 1.0
DateUpdated: 2013-05-20
.PARAMETER UserName
The samaccountname of the Local Machine user account
.PARAMETER Password
The password of the Local Machine user account
.PARAMETER ComputerName
The computer on which the local credentials will be verified
.EXAMPLE
Test-LocalCredential -username jaapbrasser -password Secret01
Description:
Verifies if the username and password provided are correct on the local machine, returning either true or false based on the result
#>
function Test-LocalCredential {
[CmdletBinding()]
Param
(
[string]$UserName,
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Password
)
if (!($UserName) -or !($Password)) {
Write-Warning 'Test-LocalCredential: Please specify both user name and password'
} else {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$ComputerName)
$DS.ValidateCredentials($UserName, $Password)
}
}
@@ -0,0 +1,98 @@
function Test-ScheduledTaskFolder {
<#
.SYNOPSIS
Function tests for existance of a folder in scheduled tasks
.DESCRIPTION
This script uses the Schedule.Service COM-object to query the local or a remote computer in order to test if a certain scheduled task folder exists
.PARAMETER Computername
The computer that will be queried by this script, local administrative permissions are required to query this information
.PARAMETER TaskFolder
This parameter specifies which folder should be queried, should be in the \Microsoft\
.NOTES
Name: Test-ScheduledTaskFolder.ps1
Author: Jaap Brasser
DateCreated: 2015-03-30
DateUpdated: 2015-03-30
Version: 1.0
Site: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.EXAMPLE
. .\Test-ScheduledTaskFolder.ps1
Description
-----------
This command dot sources the script to ensure the Test-ScheduledTaskFolder function is available in your current PowerShell session
.EXAMPLE
Test-ScheduledTaskFolder -TaskFolder \Microsoft
Description
-----------
Tests if the \Microsoft folder exists on the local system
.EXAMPLE
Test-ScheduledTaskFolder -ComputerName server01 -TaskFolder \Microsoft,\Microsoft\Windows\RAS
Description
-----------
Tests if the \Microsoft and \Microsoft\Windows\RAS folders exists on server01
.EXAMPLE
'server01','server02' | Test-ScheduledTaskFolder -TaskFolder \CustomTaskFolder
Description
-----------
Uses pipeline to verify if the \CustomTaskFolder exists on server01 and server02
#>
param(
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
$ComputerName = $env:COMPUTERNAME,
[string[]]
$TaskFolder
)
begin {
try {
$Schedule = New-Object -ComObject "Schedule.Service"
} catch {
Write-Warning "Schedule.Service COM Object not found, this script requires this object"
}
}
process {
foreach ($Computer in $ComputerName) {
try {
$Schedule.Connect($Computer)
foreach ($Folder in $TaskFolder) {
$HashProps = @{
TaskFolder = $Folder
Exists = $true
ComputerName = $Computer
}
try {
$null = $Schedule.GetFolder($Folder)
} catch {
$HashProps.Exists = $false
}
New-Object -TypeName PSCustomObject -Property $HashProps
}
} catch {
Write-Warning "Could not connect to $Computer"
}
}
}
end {
Remove-Variable -Name Schedule
}
}