Search is not available for this dataset
filename
stringlengths 5
114
| module_name
stringlengths 8
67
| content
stringlengths 0
282M
|
|---|---|---|
z.psm1
|
z-1.1.14
|
$safehome = if (![String]::IsNullOrWhiteSpace($env:XDG_CACHE_HOME)) {
$env:XDG_CACHE_HOME
} elseif (![String]::IsNullOrWhiteSpace($env:HOME)) {
$env:HOME
} else {
$env:USERPROFILE
}
$cdHistory = Join-Path -Path $safehome -ChildPath '\.cdHistory'
# The user can set $Z_UsePushLocation to $true to configure z to use Push-location, which allows to use popd/Pop-Location to go back to the previous location.
# Setting or $Z_UsePushLocation to $false will use Set-Location instead.
if ($null -eq $Z_UsePushLocation)
{
# Set default behaviour to use Push-Location
$Z_UsePushLocation = $true;
}
function z {
<#
.SYNOPSIS
Tracks your most used directories, based on 'frecency'. This is done by storing your CD command history and ranking it over time.
.DESCRIPTION
After a short learning phase, z will take you to the most 'frecent'
directory that matches the regex given on the command line.
.PARAMETER JumpPath
A un-escaped regular expression of the directory name to jump to. Character escaping will be done internally.
.PARAMETER Option
Frecency - Match by frecency (default)
Rank - Match by rank only
Time - Match by recent access only
.PARAMETER OnlyCurrentDirectory
Restrict matches to subdirectories of the current directory
.PARAMETER Listfiles
List only, don't navigate to the directory
.PARAMETER $Remove
Remove the current directory from the datafile
.PARAMETER $Clean
Clean up all history entries that cannot be resolved
.NOTES
Current PowerShell implementation is very crude and does not yet support all of the options of the original z bash script.
Although tracking of frequently used directories is obtained through the continued use of the "cd" command, the Windows registry is also scanned for frequently accessed paths.
.LINK
https://github.com/vincpa/z
.EXAMPLE
CD to the most frecent directory matching 'foo'
z foo
.EXAMPLE
CD to the most recently accessed directory matching 'foo'
z foo -o Time
#>
param(
[Parameter(Position=0)]
[string]
${JumpPath},
[ValidateSet("Time", "T", "Frecency", "F", "Rank", "R")]
[Alias('o')]
[string]
$Option = 'Frecency',
[Alias('c')]
[switch]
$OnlyCurrentDirectory = $null,
[Alias('l')]
[switch]
$ListFiles = $null,
[Alias('x')]
[switch]
$Remove = $null,
[Alias('d')]
[switch]
$Clean = $null,
[Alias('p')]
[switch]
$Push = $false
)
if (((-not $Clean) -and (-not $Remove) -and (-not $ListFiles)) -and [string]::IsNullOrWhiteSpace($JumpPath)) { Get-Help z; return; }
# If a valid path is passed in to z, treat it like the normal cd command
if (-not $ListFiles -and -not [string]::IsNullOrWhiteSpace($JumpPath) -and (Test-Path $JumpPath)) {
if ($Push -or $Z_UsePushLocation) {
pushdX $JumpPath
} else {
cdX $JumpPath
}
return;
}
if ((Test-Path $cdHistory)) {
if ($Remove) {
Save-CdCommandHistory $Remove
} elseif ($Clean) {
Cleanup-CdCommandHistory
} else {
# This causes conflicts with the -Remove parameter. Not sure whether to remove registry entry.
#$mruList = Get-MostRecentDirectoryEntries
$providerRegex = $null
If ($OnlyCurrentDirectory) {
$providerRegex = (Get-FormattedLocation).replace('\','\\')
if (-not $providerRegex.EndsWith('\\')) {
$providerRegex += '\\'
}
$providerRegex += '.*?'
} else {
$providerRegex = Get-CurrentSessionProviderDrives ((Get-PSProvider).Drives | select -ExpandProperty Name)
}
$list = @()
$global:history |
? { Get-DirectoryEntryMatchPredicate -path $_.Path -jumpPath $JumpPath -ProviderRegex $providerRegex } | Get-ArgsFilter -Option $Option |
% { if ($ListFiles -or (Test-Path $_.Path.FullName)) {$list += $_} }
if ($ListFiles) {
$newList = $list | % { New-Object PSObject -Property @{Rank = $_.Rank; Path = $_.Path.FullName; LastAccessed = [DateTime]$_.Time } }
Format-Table -InputObject $newList -AutoSize
} else {
if ($list.Length -eq 0) {
# It's not found in the history file, perhaps it's still a valid directory. Let's check.
if ((Test-Path $JumpPath)) {
if ($Push -or $Z_UsePushLocation) {
pushdX $JumpPath
} else {
cdX $JumpPath
}
} else {
Write-Host "$JumpPath Not found"
}
} else {
if ($list.Length -gt 1) {
$entry = $list | Sort-Object -Descending { $_.Score } | select -First 1
} else {
$entry = $list[0]
}
if ($Push -or $Z_UsePushLocation) {
Push-Location $entry.Path.FullName
} else {
Set-Location $entry.Path.FullName
}
Save-CdCommandHistory $Remove
}
}
}
} else {
Save-CdCommandHistory $Remove
}
}
function pushdX
{
[CmdletBinding(DefaultParameterSetName='Path', SupportsTransactions=$true, HelpUri='http://go.microsoft.com/fwlink/?LinkID=113370')]
param(
[Parameter(ParameterSetName='Path', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string]
${Path},
[Parameter(ParameterSetName='LiteralPath', ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath')]
[string]
${LiteralPath},
[switch]
${PassThru},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
${StackName})
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Push-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
Save-CdCommandHistory # Build up the DB.
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
}
function popdX {
[CmdletBinding(SupportsTransactions=$true, HelpUri='http://go.microsoft.com/fwlink/?LinkID=113369')]
param(
[switch]
${PassThru},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
${StackName})
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Pop-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Microsoft.PowerShell.Management\Pop-Location
.ForwardHelpCategory Cmdlet
#>
}
# A wrapper function around the existing Set-Location Cmdlet.
function cdX
{
[CmdletBinding(DefaultParameterSetName='Path', SupportsTransactions=$true, HelpUri='http://go.microsoft.com/fwlink/?LinkID=113397')]
param(
[Parameter(ParameterSetName='Path', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string]
${Path},
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath')]
[string]
${LiteralPath},
[switch]
${PassThru},
[Parameter(ParameterSetName='Stack', ValueFromPipelineByPropertyName=$true)]
[string]
${StackName})
begin
{
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$PSBoundParameters['ErrorAction'] = 'Stop'
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Set-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
process
{
$steppablePipeline.Process($_)
Save-CdCommandHistory # Build up the DB.
}
end
{
$steppablePipeline.End()
}
}
function Get-DirectoryEntryMatchPredicate {
Param(
[Parameter(
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
$Path,
[Parameter(
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string] $JumpPath,
$ProviderRegex
)
if ($Path -ne $null) {
$null = .{
$providerMatches = [System.Text.RegularExpressions.Regex]::Match($Path.FullName, $ProviderRegex).Success
}
if ($providerMatches) {
# Allows matching of entire names. Remove the first two characters, added by PowerShell when the user presses the TAB key.
if ($JumpPath.StartsWith('.\')) {
$JumpPath = $JumpPath.Substring(2).TrimEnd('\')
}
[System.Text.RegularExpressions.Regex]::Match($Path.Name, [System.Text.RegularExpressions.Regex]::Escape($JumpPath), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase).Success
}
}
}
function Get-CurrentSessionProviderDrives([System.Collections.ArrayList] $ProviderDrives) {
if($IsLinux -Or $IsMacOS) {
# Always only '/' which needs escaped to work in a regex
'\/'
} elseif ($ProviderDrives -ne $null -and $ProviderDrives.Length -gt 0) {
Get-ProviderDrivesRegex $ProviderDrives
} else {
# The FileSystemProvider supports \\ and X:\ paths.
# An ideal solution would be to ask the provider if a path is supported.
# Supports drives such as C:\ and also UNC \\
if ((Get-Location).Provider.ImplementingType.Name -eq 'FileSystemProvider') {
'(?i)^(((' + [String]::Concat( ((Get-Location).Provider.Drives.Name | % { $_ + '|' }) ).TrimEnd('|') + '):\\)|(\\{1,2})).*?'
} else {
Get-ProviderDrivesRegex (Get-Location).Provider.Drives
}
}
}
function Get-ProviderDrivesRegex([System.Collections.ArrayList] $ProviderDrives) {
# UNC paths get special treatment. Allows one to 'z foo -ProviderDrives \\' and specify '\\' as the drive.
if ($ProviderDrives -contains '\\') {
$ProviderDrives.('\\')
}
if ($ProviderDrives.Count -eq 0) {
'(?i)^(\\{1,2}).*?'
} else {
$uncRootPathRegex = '|(\\{1,2})'
'(?i)^((' + [String]::Concat( ($ProviderDrives | % { $_ + '|' }) ).TrimEnd('|') + '):\\)' + $uncRootPathRegex + '.*?'
}
}
function Get-Frecency($rank, $time) {
# Last access date/time
$dx = (Get-Date).Subtract((New-Object System.DateTime -ArgumentList $time)).TotalSeconds
if( $dx -lt 3600 ) { return $rank*4 }
if( $dx -lt 86400 ) { return $rank*2 }
if( $dx -lt 604800 ) { return $rank/2 }
return $rank/4
}
function Cleanup-CdCommandHistory() {
try {
for($i = 0; $i -lt $global:history.Length; $i++) {
$line = $global:history[$i]
if ($line -ne $null) {
$testDir = $line.Path.FullName
if (-not [string]::IsNullOrWhiteSpace($testDir) -and !(Test-Path $testDir)) {
$global:history[$i] = $null
Write-Host "Removed inaccessible path $testDir" -ForegroundColor Yellow
}
}
}
Remove-Old-History
WriteHistoryToDisk
} catch {
Write-Host $_.Exception.ToString() -ForegroundColor Red
}
}
function Remove-Old-History() {
if ($global:history.Length -gt 1000) {
$global:history | ? { $_ -ne $null } | % {$i = 0} {
$lineObj = $_
$lineObj.Rank = $lineObj.Rank * 0.99
# If it's been accessed in the last 14 days it can stay
# or
# If it's rank is greater than 20 and been accessed in the last 30 days it can stay
if ($lineObj.Age -lt 1209600 -or ($lineObj.Rank -ge 5 -and $lineObj.Age -lt 2592000)) {
#$global:history[$i] = ConvertTo-DirectoryEntry (ConvertTo-TextualHistoryEntry $lineObj.Rank $lineObj.Path.FullName $lineObj.Time)
} else {
Write-Host "Removing old item: Rank:" $lineObj.Rank "Age:" ($lineObj.Age/60/60) "Path:" $lineObj.Path.FullName -ForegroundColor Yellow
$global:history[$i] = $null
}
$i++;
}
}
}
function Save-CdCommandHistory($removeCurrentDirectory = $false) {
$currentDirectory = Get-FormattedLocation
try {
$foundDirectory = $false
$runningTotal = 0
for($i = 0; $i -lt $global:history.Length; $i++) {
$line = $global:history[$i]
$canIncreaseRank = $true;
$rank = $line.Rank;
if (-not $foundDirectory) {
$rank = $line.Rank
if ($line.Path.FullName -eq $currentDirectory) {
$foundDirectory = $true
if ($removeCurrentDirectory) {
$canIncreaseRank = $false
$global:history[$i] = $null
Write-Host "Removed entry $currentDirectory" -ForegroundColor Green
} else {
$rank++
Update-HistoryEntryUsageTime $global:history[$i]
}
}
}
if ($canIncreaseRank) {
$runningTotal += $rank
}
}
if (-not $foundDirectory -and $removeCurrentDirectory) {
Write-Host "Current directory not found in CD history data file" -ForegroundColor Red
} else {
if (-not $foundDirectory) {
Save-HistoryEntry 1 $currentDirectory
$runningTotal += 1
}
Remove-Old-History
}
WriteHistoryToDisk
} catch {
Write-Host $_.Exception.ToString() -ForegroundColor Red
}
}
function WriteHistoryToDisk() {
$newList = GetAllHistoryAsText $global:history
Set-Content -Value $newList -Path $cdHistory -Encoding UTF8
}
function GetAllHistoryAsText($history) {
return $history | ? { $_ -ne $null } | % { ConvertTo-TextualHistoryEntry $_.Rank $_.Path.FullName $_.Time }
}
function Get-FormattedLocation() {
if ((Get-Location).Provider.ImplementingType.Name -eq 'FileSystemProvider' -and (Get-Location).Path.Contains('FileSystem::\\')) {
Get-Location | select -ExpandProperty ProviderPath # The registry provider does return a path which z understands. In other words, I'm too lazy.
} else {
Get-Location | select -ExpandProperty Path
}
}
function Format-Rank($rank) {
return $rank.ToString("000#.00", [System.Globalization.CultureInfo]::InvariantCulture);
}
function Save-HistoryEntry($rank, $directory) {
$entry = ConvertTo-TextualHistoryEntry $rank $directory
$global:history += ConvertTo-DirectoryEntry $entry
}
function Update-HistoryEntryUsageTime($historyEntry) {
$historyEntry.Rank++
$historyEntry.Time = (Get-Date).Ticks
}
function ConvertTo-TextualHistoryEntry($rank, $directory, $lastAccessedTicks) {
if ($lastAccessedTicks -eq $null) {
$lastAccessedTicks = (Get-Date).Ticks
}
(Format-Rank $rank) + $lastAccessedTicks + $directory
}
function ConvertTo-DirectoryEntry {
Param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$line
)
Process {
$null = .{
$pathValue = $line.Substring(25)
try {
$fileName = [System.IO.Path]::GetFileName($pathValue);
# GetFileName() does not work with registry paths
if ($fileName -eq '') {
$lastPathSeparator = $pathValue.LastIndexOf('\');
if ($lastPathSeparator -ge 0) {
$pathValue = $pathValue.TrimEnd('\');
$fileName = $pathValue.Substring( + 1);
}
}
} catch [System.ArgumentException] { }
$time = [long]::Parse($line.Substring(7, 18), [Globalization.CultureInfo]::InvariantCulture)
}
@{
Rank=GetRankFromLine $line;
Time=$time;
Path=@{ Name = $fileName; FullName = $pathValue };
Age=(Get-Date).Subtract((New-Object System.DateTime -ArgumentList $time)).TotalSeconds;
}
}
}
function GetRankFromLine([String]$line) {
$null = .{ $rankStr = $line.Substring(0, 7) }
[double]::Parse($rankStr, [Globalization.CultureInfo]::InvariantCulture)
}
function Get-MostRecentDirectoryEntries {
$mruEntries = (Get-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths | % { $item = $_; $_.GetValueNames() | % { $item.GetValue($_) } })
$mruEntries | % { ConvertTo-TextualHistoryEntry 1 $_ }
}
function Get-ArgsFilter {
Param(
[Parameter(ValueFromPipeline=$true)]
[Hashtable]$historyEntry,
[string]
$Option = 'Frecency'
)
Process {
if ($Option -in ('Frecency', 'F')) {
$_['Score'] = (Get-Frecency $_.Rank $_.Time);
} elseif ($Option -in ('Time', 'T')) {
$_['Score'] = $_.Time;
} elseif ($Option -in ('Rank', 'R')) {
$_['Score'] = $_.Rank;
}
return $_;
}
}
<#
.ForwardHelpTargetName Set-Location
.ForwardHelpCategory Cmdlet
#>
# Get cdHistory and hydrate a in-memory collection
$global:history = @()
if ((Test-Path -Path $cdHistory)) {
$global:history += Get-Content -Path $cdHistory -Encoding UTF8 | ? { (-not [String]::IsNullOrWhiteSpace($_)) } | ConvertTo-DirectoryEntry
}
$orig_cd = (Get-Alias -Name 'cd').Definition
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
set-item alias:cd -value $orig_cd
}
#Override the existing CD command with the wrapper in order to log 'cd' commands.
Set-item alias:cd -Value 'cdX'
Set-Alias -Name pushd -Value pushdX -Force -Option AllScope -Scope Global
Set-Alias -Name popd -Value popdX -Force -Option AllScope -Scope Global
Export-ModuleMember -Function z, cdX, pushdX, popdX -Alias cd, pushd
# Tab Completion
$completion_RunningService = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$global:history | Sort-Object { $_.Rank } -Descending | Where-Object { $_.Path.Name -like "*$wordToComplete*" } |
ForEach-Object { New-Object System.Management.Automation.CompletionResult ("'{0}'" -f $_.Path.FullName), $_.Path.FullName, 'ParameterName', ('{0} ({1})' -f $_.Path.Name, $_.Path.FullName) }
}
if (Get-Command -ErrorAction Ignore -Name 'Register-ArgumentCompleter') {
Register-ArgumentCompleter -CommandName 'z' -ParameterName 'JumpPath' -ScriptBlock $completion_RunningService
} else {
if (-not $global:options) { $global:options = @{CustomArgumentCompleters = @{};NativeArgumentCompleters = @{}}}
$global:options['CustomArgumentCompleters']['z:JumpPath'] = $Completion_RunningService
$function:tabexpansion2 = $function:tabexpansion2 -replace 'End(\r\n|\n){','End { if ($null -ne $options) { $options += $global:options} else {$options = $global:options}'
}
|
z-pushd.psm1
|
z-pushd-0.0.1
|
$safehome = if ([String]::IsNullOrWhiteSpace($Env:HOME)) { $env:USERPROFILE } else { $Env:HOME }
$cdHistory = Join-Path -Path $safehome -ChildPath '\.cdHistory'
<#
.SYNOPSIS
Tracks your most used directories, based on 'frecency'. This is done by storing your CD command history and ranking it over time.
.DESCRIPTION
After a short learning phase, z will take you to the most 'frecent' directory that matches the regex given on the command line.
.PARAMETER JumpPath
A un-escaped regular expression of the directory name to jump to. Character escaping will be done internally.
.PARAMETER Option
Frecency - Match by frecency (default)
Rank - Match by rank only
Time - Match by recent access only
.PARAMETER OnlyCurrentDirectory
Restrict matches to subdirectories of the current directory
.PARAMETER Listfiles
List only, don't navigate to the directory
.PARAMETER Remove
Remove the current directory from the datafile
.PARAMETER Clean
Clean up all history entries that cannot be resolved
.NOTES
Current PowerShell implementation is very crude and does not yet support all of the options of the original z bash script.
Although tracking of frequently used directories is obtained through the continued use of the "cd" command, the Windows registry is also scanned for frequently accessed paths.
.LINK
https://github.com/letuanhai/z
.EXAMPLE
CD to the most frecent directory matching 'foo'
z foo
.EXAMPLE
CD to the most recently accessed directory matching 'foo'
z foo -o Time
#>
function z {
param(
[Parameter(Position = 0)]
[string]
${JumpPath},
[ValidateSet("Time", "T", "Frecency", "F", "Rank", "R")]
[Alias('o')]
[string]
$Option = 'Frecency',
[Alias('c')]
[switch]
$OnlyCurrentDirectory = $null,
[Alias('l')]
[switch]
$ListFiles = $null,
[Alias('x')]
[switch]
$Remove = $null,
[Alias('d')]
[switch]
$Clean = $null
# [Alias('p')]
# [switch]
# $Push = $false
)
if (((-not $Clean) -and (-not $Remove) -and (-not $ListFiles)) -and [string]::IsNullOrWhiteSpace($JumpPath)) { Get-Help z; return; }
# If a valid path is passed in to z, treat it like the normal cd command
if (-not $ListFiles -and -not [string]::IsNullOrWhiteSpace($JumpPath) -and (Test-Path $JumpPath)) {
# if ($Push) {
pushdX $JumpPath
# }
# else {
# cdX $JumpPath
# }
return;
}
if ((Test-Path $cdHistory)) {
if ($Remove) {
Save-CdCommandHistory $Remove
}
elseif ($Clean) {
Cleanup-CdCommandHistory
}
else {
# This causes conflicts with the -Remove parameter. Not sure whether to remove registry entry.
#$mruList = Get-MostRecentDirectoryEntries
$providerRegex = $null
If ($OnlyCurrentDirectory) {
$providerRegex = (Get-FormattedLocation).replace('\', '\\')
if (-not $providerRegex.EndsWith('\\')) {
$providerRegex += '\\'
}
$providerRegex += '.*?'
}
else {
$providerRegex = Get-CurrentSessionProviderDrives ((Get-PSProvider).Drives | Select-Object -ExpandProperty Name)
}
$list = @()
$global:history |
Where-Object { Get-DirectoryEntryMatchPredicate -path $_.Path -jumpPath $JumpPath -ProviderRegex $providerRegex } | Get-ArgsFilter -Option $Option |
ForEach-Object { if ($ListFiles -or (Test-Path $_.Path.FullName)) { $list += $_ } }
if ($ListFiles) {
$newList = $list | ForEach-Object { New-Object PSObject -Property @{Rank = $_.Rank; Path = $_.Path.FullName; LastAccessed = [DateTime]$_.Time } }
Format-Table -InputObject $newList -AutoSize
}
else {
if ($list.Length -eq 0) {
# It's not found in the history file, perhaps it's still a valid directory. Let's check.
if ((Test-Path $JumpPath)) {
# if ($Push) {
pushdX $JumpPath
# }
# else {
# cdX $JumpPath
# }
}
else {
Write-Host "$JumpPath Not found"
}
}
else {
if ($list.Length -gt 1) {
$entry = $list | Sort-Object -Descending { $_.Score } | Select-Object -First 1
}
else {
$entry = $list[0]
}
# if ($Push) {
Push-Location $entry.Path.FullName
# }
# else {
# Set-Location $entry.Path.FullName
# }
Save-CdCommandHistory $Remove
}
}
}
}
else {
Save-CdCommandHistory $Remove
}
}
function pushdX {
[CmdletBinding(DefaultParameterSetName = 'Path', SupportsTransactions = $true, HelpUri = 'http://go.microsoft.com/fwlink/?LinkID=113370')]
param(
[Parameter(ParameterSetName = 'Path', Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string]
${Path},
[Parameter(ParameterSetName = 'LiteralPath', ValueFromPipelineByPropertyName = $true)]
[Alias('PSPath')]
[string]
${LiteralPath},
[switch]
${PassThru},
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]
${StackName})
begin {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Push-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
catch {
throw
}
}
process {
try {
$steppablePipeline.Process($_)
Save-CdCommandHistory # Build up the DB.
}
catch {
throw
}
}
end {
try {
$steppablePipeline.End()
}
catch {
throw
}
}
}
function popdX {
[CmdletBinding(SupportsTransactions = $true, HelpUri = 'http://go.microsoft.com/fwlink/?LinkID=113369')]
param(
[switch]
${PassThru},
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]
${StackName})
begin {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Pop-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
catch {
throw
}
}
process {
try {
$steppablePipeline.Process($_)
}
catch {
throw
}
}
end {
try {
$steppablePipeline.End()
}
catch {
throw
}
}
<#
.ForwardHelpTargetName Microsoft.PowerShell.Management\Pop-Location
.ForwardHelpCategory Cmdlet
#>
}
<#
.SYNOPSIS
Get the locations in the location stacks used by z, cd, pushd.
.DESCRIPTION
To store location history, this module provided wrapper for aliases commonly used for directory navigation: cd, pushd, popd.
This module also uses Push-Location under the hood for all navigation commands (z, cd, pushd) to store the current
navigation history (in the default unamed location stack).
Due to the way Powershell work, all the location stacks used by commands in this module is not accessible to outside commands.
(This may be due to them being on different *runspace*. See: https://go.microsoft.com/fwlink/?LinkID=113321#notes)
This command allow you access the location used by commands from this module.
.PARAMETER StackName
Specifies, as a string array, the named location stacks. Enter one or more location stack names.
If omitted, show the default unamed stack.
.EXAMPLE
Get the locations in location stack a and b
> zz -StackName a, b
#>
function zz {
[CmdletBinding(SupportsTransactions = $true, HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=113321')]
param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]
${StackName}
)
begin {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {
$PSBoundParameters['OutBuffer'] = 1
}
$PSBoundParameters['Stack'] = $true
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Get-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
catch {
throw
}
}
process {
try {
$steppablePipeline.Process($_)
}
catch {
throw
}
}
end {
try {
$steppablePipeline.End()
}
catch {
throw
}
}
}
# A wrapper function around the existing Set-Location Cmdlet.
function cdX {
[CmdletBinding(DefaultParameterSetName = 'Path', SupportsTransactions = $true, HelpUri = 'http://go.microsoft.com/fwlink/?LinkID=113397')]
param(
[Parameter(ParameterSetName = 'Path', Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string]
${Path},
[Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[Alias('PSPath')]
[string]
${LiteralPath},
[switch]
${PassThru},
[Parameter(ParameterSetName = 'Stack', ValueFromPipelineByPropertyName = $true)]
[string]
${StackName})
begin {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {
$PSBoundParameters['OutBuffer'] = 1
}
$PSBoundParameters['ErrorAction'] = 'Stop'
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Set-Location', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
process {
$steppablePipeline.Process($_)
Save-CdCommandHistory # Build up the DB.
}
end {
$steppablePipeline.End()
}
}
function Get-DirectoryEntryMatchPredicate {
Param(
[Parameter(
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
$Path,
[Parameter(
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string] $JumpPath,
$ProviderRegex
)
if ($null -ne $Path) {
$null = .{
$providerMatches = [System.Text.RegularExpressions.Regex]::Match($Path.FullName, $ProviderRegex).Success
}
if ($providerMatches) {
# Allows matching of entire names. Remove the first two characters, added by PowerShell when the user presses the TAB key.
if ($JumpPath.StartsWith('.\')) {
$JumpPath = $JumpPath.Substring(2).TrimEnd('\')
}
[System.Text.RegularExpressions.Regex]::Match($Path.Name, [System.Text.RegularExpressions.Regex]::Escape($JumpPath), [System.Text.RegularExpressions.RegexOptions]::IgnoreCase).Success
}
}
}
function Get-CurrentSessionProviderDrives([System.Collections.ArrayList] $ProviderDrives) {
if ($IsLinux -Or $IsMacOS) {
# Always only '/' which needs escaped to work in a regex
'\/'
}
elseif ($ProviderDrives -ne $null -and $ProviderDrives.Length -gt 0) {
Get-ProviderDrivesRegex $ProviderDrives
}
else {
# The FileSystemProvider supports \\ and X:\ paths.
# An ideal solution would be to ask the provider if a path is supported.
# Supports drives such as C:\ and also UNC \\
if ((Get-Location).Provider.ImplementingType.Name -eq 'FileSystemProvider') {
'(?i)^(((' + [String]::Concat( ((Get-Location).Provider.Drives.Name | ForEach-Object { $_ + '|' }) ).TrimEnd('|') + '):\\)|(\\{1,2})).*?'
}
else {
Get-ProviderDrivesRegex (Get-Location).Provider.Drives
}
}
}
function Get-ProviderDrivesRegex([System.Collections.ArrayList] $ProviderDrives) {
# UNC paths get special treatment. Allows one to 'z foo -ProviderDrives \\' and specify '\\' as the drive.
if ($ProviderDrives -contains '\\') {
$ProviderDrives.('\\')
}
if ($ProviderDrives.Count -eq 0) {
'(?i)^(\\{1,2}).*?'
}
else {
$uncRootPathRegex = '|(\\{1,2})'
'(?i)^((' + [String]::Concat( ($ProviderDrives | ForEach-Object { $_ + '|' }) ).TrimEnd('|') + '):\\)' + $uncRootPathRegex + '.*?'
}
}
function Get-Frecency($rank, $time) {
# Last access date/time
$dx = (Get-Date).Subtract((New-Object System.DateTime -ArgumentList $time)).TotalSeconds
if ( $dx -lt 3600 ) { return $rank * 4 }
if ( $dx -lt 86400 ) { return $rank * 2 }
if ( $dx -lt 604800 ) { return $rank / 2 }
return $rank / 4
}
function Cleanup-CdCommandHistory() {
try {
for ($i = 0; $i -lt $global:history.Length; $i++) {
$line = $global:history[$i]
if ($null -ne $line) {
$testDir = $line.Path.FullName
if (-not [string]::IsNullOrWhiteSpace($testDir) -and !(Test-Path $testDir)) {
$global:history[$i] = $null
Write-Host "Removed inaccessible path $testDir" -ForegroundColor Yellow
}
}
}
Remove-Old-History
WriteHistoryToDisk
}
catch {
Write-Host $_.Exception.ToString() -ForegroundColor Red
}
}
function Remove-Old-History() {
if ($global:history.Length -gt 1000) {
$global:history | Where-Object { $_ -ne $null } | ForEach-Object { $i = 0 } {
$lineObj = $_
$lineObj.Rank = $lineObj.Rank * 0.99
# If it's been accessed in the last 14 days it can stay
# or
# If it's rank is greater than 20 and been accessed in the last 30 days it can stay
if ($lineObj.Age -lt 1209600 -or ($lineObj.Rank -ge 5 -and $lineObj.Age -lt 2592000)) {
#$global:history[$i] = ConvertTo-DirectoryEntry (ConvertTo-TextualHistoryEntry $lineObj.Rank $lineObj.Path.FullName $lineObj.Time)
}
else {
Write-Host "Removing old item: Rank:" $lineObj.Rank "Age:" ($lineObj.Age / 60 / 60) "Path:" $lineObj.Path.FullName -ForegroundColor Yellow
$global:history[$i] = $null
}
$i++;
}
}
}
function Save-CdCommandHistory($removeCurrentDirectory = $false) {
$currentDirectory = Get-FormattedLocation
try {
$foundDirectory = $false
$runningTotal = 0
for ($i = 0; $i -lt $global:history.Length; $i++) {
$line = $global:history[$i]
$canIncreaseRank = $true;
$rank = $line.Rank;
if (-not $foundDirectory) {
$rank = $line.Rank
if ($line.Path.FullName -eq $currentDirectory) {
$foundDirectory = $true
if ($removeCurrentDirectory) {
$canIncreaseRank = $false
$global:history[$i] = $null
Write-Host "Removed entry $currentDirectory" -ForegroundColor Green
}
else {
$rank++
Update-HistoryEntryUsageTime $global:history[$i]
}
}
}
if ($canIncreaseRank) {
$runningTotal += $rank
}
}
if (-not $foundDirectory -and $removeCurrentDirectory) {
Write-Host "Current directory not found in CD history data file" -ForegroundColor Red
}
else {
if (-not $foundDirectory) {
Save-HistoryEntry 1 $currentDirectory
$runningTotal += 1
}
Remove-Old-History
}
WriteHistoryToDisk
}
catch {
Write-Host $_.Exception.ToString() -ForegroundColor Red
}
}
function WriteHistoryToDisk() {
$newList = GetAllHistoryAsText $global:history
Set-Content -Value $newList -Path $cdHistory -Encoding UTF8
}
function GetAllHistoryAsText($history) {
return $history | Where-Object { $_ -ne $null } | ForEach-Object { ConvertTo-TextualHistoryEntry $_.Rank $_.Path.FullName $_.Time }
}
function Get-FormattedLocation() {
if ((Get-Location).Provider.ImplementingType.Name -eq 'FileSystemProvider' -and (Get-Location).Path.Contains('FileSystem::\\')) {
Get-Location | Select-Object -ExpandProperty ProviderPath # The registry provider does return a path which z understands. In other words, I'm too lazy.
}
else {
Get-Location | Select-Object -ExpandProperty Path
}
}
function Format-Rank($rank) {
return $rank.ToString("000#.00", [System.Globalization.CultureInfo]::InvariantCulture);
}
function Save-HistoryEntry($rank, $directory) {
$entry = ConvertTo-TextualHistoryEntry $rank $directory
$global:history += ConvertTo-DirectoryEntry $entry
}
function Update-HistoryEntryUsageTime($historyEntry) {
$historyEntry.Rank++
$historyEntry.Time = (Get-Date).Ticks
}
function ConvertTo-TextualHistoryEntry($rank, $directory, $lastAccessedTicks) {
if ($null -eq $lastAccessedTicks) {
$lastAccessedTicks = (Get-Date).Ticks
}
(Format-Rank $rank) + $lastAccessedTicks + $directory
}
function ConvertTo-DirectoryEntry {
Param(
[Parameter(
Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[String]$line
)
Process {
$null = .{
$pathValue = $line.Substring(25)
try {
$fileName = [System.IO.Path]::GetFileName($pathValue);
# GetFileName() does not work with registry paths
if ($fileName -eq '') {
$lastPathSeparator = $pathValue.LastIndexOf('\');
if ($lastPathSeparator -ge 0) {
$pathValue = $pathValue.TrimEnd('\');
$fileName = $pathValue.Substring( + 1);
}
}
}
catch [System.ArgumentException] { }
$time = [long]::Parse($line.Substring(7, 18), [Globalization.CultureInfo]::InvariantCulture)
}
@{
Rank = GetRankFromLine $line;
Time = $time;
Path = @{ Name = $fileName; FullName = $pathValue };
Age = (Get-Date).Subtract((New-Object System.DateTime -ArgumentList $time)).TotalSeconds;
}
}
}
function GetRankFromLine([String]$line) {
$null = .{ $rankStr = $line.Substring(0, 7) }
[double]::Parse($rankStr, [Globalization.CultureInfo]::InvariantCulture)
}
function Get-MostRecentDirectoryEntries {
$mruEntries = (Get-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths | ForEach-Object { $item = $_; $_.GetValueNames() | ForEach-Object { $item.GetValue($_) } })
$mruEntries | ForEach-Object { ConvertTo-TextualHistoryEntry 1 $_ }
}
function Get-ArgsFilter {
Param(
[Parameter(ValueFromPipeline = $true)]
[Hashtable]$historyEntry,
[string]
$Option = 'Frecency'
)
Process {
if ($Option -in ('Frecency', 'F')) {
$_['Score'] = (Get-Frecency $_.Rank $_.Time);
}
elseif ($Option -in ('Time', 'T')) {
$_['Score'] = $_.Time;
}
elseif ($Option -in ('Rank', 'R')) {
$_['Score'] = $_.Rank;
}
return $_;
}
}
<#
.ForwardHelpTargetName Set-Location
.ForwardHelpCategory Cmdlet
#>
# Get cdHistory and hydrate a in-memory collection
$global:history = @()
if ((Test-Path -Path $cdHistory)) {
$global:history += Get-Content -Path $cdHistory -Encoding UTF8 | Where-Object { (-not [String]::IsNullOrWhiteSpace($_)) } | ConvertTo-DirectoryEntry
}
# $orig_cd = (Get-Alias -Name 'cd').Definition
# $orig_pushd = (Get-Alias -Name 'pushd').Definition
# $orig_popd = (Get-Alias -Name 'popd').Definition
# $MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
# set-item alias:cd -value $orig_cd
# set-item alias:pushd -value $orig_pushd
# set-item alias:popd -value $orig_popd
# }
#Override the existing CD command with the wrapper in order to log 'cd' commands.
# Set-item alias:cd -Value 'pushdX'
# Set-item alias:pushd -Value 'pushdX'
# Set-item alias:popd -Value 'popdX'
Set-Alias -Name pushd -Value pushdX -Force -Option AllScope -Scope Global
Set-Alias -Name cd -Value pushdX -Force -Option AllScope -Scope Global
Set-Alias -Name popd -Value popdX -Force -Option AllScope -Scope Global
Export-ModuleMember -Function z, cdX, pushdX, popdX, zz -Alias cd, pushd, popd
# Tab Completion
$completion_RunningService = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$global:history | Sort-Object { $_.Rank } -Descending | Where-Object { $_.Path.Name -like "*$wordToComplete*" } |
ForEach-Object { New-Object System.Management.Automation.CompletionResult ("'{0}'" -f $_.Path.FullName), $_.Path.FullName, 'ParameterName', ('{0} ({1})' -f $_.Path.Name, $_.Path.FullName) }
}
if (-not $global:options) { $global:options = @{CustomArgumentCompleters = @{}; NativeArgumentCompleters = @{} } }
$global:options['CustomArgumentCompleters']['z:JumpPath'] = $Completion_RunningService
$function:tabexpansion2 = $function:tabexpansion2 -replace 'End(\r\n|\n){', 'End { if ($null -ne $options) { $options += $global:options} else {$options = $global:options}'
|
z-pushd.psd1
|
z-pushd-0.0.1
|
#
# Module manifest for module 'z-push'
#
# Generated by: Le Tuan Hai
#
# Generated on: 22-Mar-23
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'z-pushd.psm1'
# Version number of this module.
ModuleVersion = '0.0.1'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '409e5194-a90b-46c2-b729-932450d7998b'
# Author of this module
Author = 'Le Tuan Hai'
# Description of the functionality provided by this module
Description = 'A fork of vincpa/z using pushd for all navigation commands.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('z', 'cdX', 'popdX', 'pushdX', 'zz')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @('cd', 'pushd', 'popd')
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
FileList = @('z-pushd.psm1')
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
ProjectUri = 'https://github.com/letuanhai/z-pushd'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'Forked from vincpa/z for my personal usage.'
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
zWindowsUpdate.psm1
|
zWindowsUpdate-1.2.0
|
### Module - zWindowsUpdate
# Task settings
$WU_TaskName = 'zWindowsUpdate'
$WU_TaskDescription = 'Windows update task created by zWindowsUpdate PowerShell module'
$WU_TaskWorkingDirectory = 'C:\Program Files\zWindowsUpdate' # Folder is deleted when running Remove-zWUTask
# File names
$WU_ScriptFileName = 'zWUScript.ps1'
$WU_XmlLogFileName = 'zWUScriptLog.xml'
$WU_LogFileName = 'zWUScript-Error.log'
# zWU Functions
function Get-zWULog {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Get the log entires for a windows update task.
.DESCRIPTION
Returns one or more lines from the log file generated when the task is run. By default the last 1 line is returned.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Full
Return the full log.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this command. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS.
.PARAMETER PSSessionOption
Specifies advanced options for the session. Enter a SessionOption object, such as one that you create by using the New-PSSessionOption cmdlet, or a hash table in which the keys are session option names and the values are session option values.
.PARAMETER Tail
Retrun the last n entries of the log.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
.EXAMPLE
PS C:\>Get-zWULog 'SRV01', 'SRV02', 'SRV03', 'SRV04', 'SRV05', 'SRV06', 'CLIENT01'
ComputerName Timestamp Level Message
------------ --------- ----- -------
SRV06 29/07/2017 04:38:40 Warning Finished - Reboot required - 24 of 24 update(s) installed
SRV02 29/07/2017 03:20:55 Info Finished - Download only - 3 update(s) downloaded
SRV01 29/07/2017 03:14:16 Info Searching for updates
SRV04 29/07/2017 03:20:55 Info Finished - Search only - 3 update(s) found
SRV03 29/07/2017 03:14:19 Info Downloading update 9 of 24 - Update for Windows Server 2012 R2 (KB2883200) (226.9MB)
CLIENT01 29/07/2017 03:14:31 Info Installing update 4 of 10 - Feature update to Windows 10 Enterprise, version 1703 (0B-2.7GB)
SRV05 29/07/2017 03:14:17 Info Finished - No reboot required - 1 of 1 update(s) installed
Get the last line from the update task log on the specified remote computers.
.EXAMPLE
PS C:\>Get-zWULog SRV04 -Full | Out-GridView
Get-the full update task log from the computer SRV04 and display the results in Out-GridView.
.EXAMPLE
PS C:\>$cred = Get-Credential
PS C:\>$PSSessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck
PS C:\>Get-zWULog 10.10.10.10 -Credential $cred -UseSSL -PSSessionOption $PSSessionOption -Full
ComputerName Timestamp Level Message
------------ --------- ----- -------
10.10.10.10 02/03/2018 16:13:45 Info ## zWindowsUpdate ##
10.10.10.10 02/03/2018 16:13:45 Info Parameter - AutoSelect = True
10.10.10.10 02/03/2018 16:13:45 Info Parameter - SearchOnly = True
10.10.10.10 02/03/2018 16:13:45 Info Parameter - Service = WindowsUpdate
10.10.10.10 02/03/2018 16:13:45 Info Starting windows update session
10.10.10.10 02/03/2018 16:13:45 Info Searching for updates
10.10.10.10 02/03/2018 16:13:53 Info Found 3 update(s) (0B-1.2GB)
10.10.10.10 02/03/2018 16:13:53 Info Windows Malicious Software Removal Tool x64 - February 2018 (KB890830) (0B-38.4MB)
10.10.10.10 02/03/2018 16:13:53 Info 2018-02 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4074590) (0B-1.1GB)
10.10.10.10 02/03/2018 16:13:53 Info Update for Windows Defender antimalware platform - KB4052623 (Version 4.12.17007.18022) (0B-3.1MB)
10.10.10.10 02/03/2018 16:13:53 Info Finished - Search only - 3 update(s) found
Get the full update task log from the computer with the Ip address 10.10.10.10. The connection will use SSL and the PSSessionOptions provided.
.LINK
about_zWindowsUpdate
Get-zWUTask
New-zWUTask
Remove-zWUTask
Start-zWUTask
Stop-zWUTask
Wait-zWUTask
#>
[cmdletbinding(DefaultParameterSetName = 'Tail')]
param(
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[parameter(ParameterSetName = 'Full')]
[switch]$Full,
[ValidateRange(1, 65535)]
[int]$Port,
[System.Management.Automation.Remoting.PSSessionOption]$PSSessionOption,
[parameter(Position=1,ParameterSetName = 'Tail')]
[uint32]$Tail = 1,
[uint16]$ThrottleLimit,
[switch]$UseSSL
)
begin {
$Command = $MyInvocation.MyCommand.Name
$ComputerNames = @()
$sb = {
$Task = Get-ScheduledTask -TaskName $using:WU_TaskName -ErrorAction 'SilentlyContinue'
if ($Task) {
$Path = Join-Path -Path $Task.Actions.WorkingDirectory -ChildPath $using:WU_XmlLogFileName
if (Test-Path $Path -PathType Leaf) {
$Import = Import-Clixml -Path $Path -ErrorAction 'Stop'
if ($using:Full) {$Import}
else {$Import | Select-Object -Last $using:Tail}
}
else {Write-Warning "[$env:COMPUTERNAME] $using:Command - No log file found."}
}
else {Write-Warning "[$env:COMPUTERNAME] $using:Command - No task named $using:WU_TaskName."}
}
}
process {$ComputerNames += $ComputerName}
end {
$Invoke_Params = @{ScriptBlock = $sb ; ComputerName = $ComputerNames}
if ($Credential) {$Invoke_Params += @{Credential = $Credential}}
if ($ThrottleLimit) {$Invoke_Params += @{ThrottleLimit = $ThrottleLimit}}
if ($Port) {$Invoke_Params += @{Port = $Port}}
if ($UseSSL) {$Invoke_Params += @{UseSSL = $UseSSL}}
if ($PSSessionOption) {$Invoke_Params += @{SessionOption = $PSSessionOption}}
Invoke-Command @Invoke_Params | Select-Object @{l='ComputerName';e={$_.PSComputerName}}, TimeStamp, Level, Message
}
}
Set-Alias -Name gzl -Value Get-zWULog
function Get-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Get a windows update task.
.DESCRIPTION
Gets details of a windows update task. The details returned are the task State, LastRunTime and Parameters.
.PARAMETER CimSessionOption
Sets advanced options for the new CIM session. Enter the name of a CimSessionOption object created by using the New-CimSessionOption cmdlet.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS).
.EXAMPLE
PS C:\>Get-zWUTask SRV01
ComputerName State LastRunTime Parameters
------------ ----- ----------- ----------
SRV01 Ready 29/07/2017 03:14:16 -AcceptEula -DownloadOnly
This command returns the details for the update task on SRV01.
.EXAMPLE
PS C:\>Get-zWUTask 'SRV01', 'SRV02', 'SRV03', 'SRV04', 'SRV05', 'SRV06', 'CLIENT01'
ComputerName State LastRunTime Parameters
------------ ----- ----------- ----------
SRV05 Ready 29/07/2017 03:14:17 -SearchOnly -UpdateType SecurityUpdates,CriticalUpdates
SRV06 Ready 29/07/2017 03:14:15 -AcceptEula -AutoSelect -DownloadOnly
CLIENT01 Ready 29/07/2017 03:14:17 -AcceptEula -SearchOnly -Service WindowsUpdate
SRV02 Ready 29/07/2017 03:14:24 -SearchOnly -UpdateType SecurityUpdates,CriticalUpdates
SRV01 Ready 29/07/2017 03:14:16 -AcceptEula -ExcludeKB KB2267602,KB890830 -Reboot
SRV04 Ready 29/07/2017 03:14:19 -AcceptEula -AutoSelect -DownloadOnly
SRV03 Ready 29/07/2017 03:14:19 -AcceptEula -ExcludeOptional -Reboot
.LINK
about_zWindowsUpdate
Get-zWULog
New-zWUTask
Remove-zWUTask
Start-zWUTask
Stop-zWUTask
Wait-zWUTask
#>
[cmdletbinding()]
param(
[Microsoft.Management.Infrastructure.Options.WSManSessionOptions]$CimSessionOption,
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[ValidateRange(1, 65535)]
[int]$Port
)
begin {$Command = $MyInvocation.MyCommand.Name}
process {
$Cim_Params = @{ComputerName = $ComputerName ; Name = ("$WU_TaskName-" + [guid]::NewGuid().Guid)}
if ($Credential) {$Cim_Params += @{Credential = $Credential}}
if ($Port) {$Cim_Params += @{Port = $Port}}
if ($CimSessionOption) {$Cim_Params += @{SessionOption = $CimSessionOption}}
$CimSession = New-CimSession @Cim_Params
foreach ($Session in $CimSession) {
$Task = Get-ScheduledTask -TaskName $WU_TaskName -CimSession $Session -ErrorAction 'SilentlyContinue'
if ($Task) {
$Task | Select-Object `
@{l='ComputerName';e={$_.PSComputerName}}, `
State, `
@{l='LastRunTime';e={($_ | Get-ScheduledTaskInfo).LastRunTime}}, `
@{l='Parameters';e={($_.Actions.Arguments -split ".ps1' ")[1].TrimEnd("`" > $WU_LogFileName 2>&1")}}
}
else {Write-Warning "[$($Session.ComputerName)] $Command - No task named $WU_TaskName."}
}
}
end {Get-CimSession -Name "$WU_TaskName*" | Remove-CimSession}
}
Set-Alias -Name gzt -Value Get-zWUTask
function New-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Creates a new windows update task.
.DESCRIPTION
Copies the zWUScript.ps1 script from this module to the remote or local computer and creates a scheduled task to run it. The task is created without a trigger. By default when the task is run the script will search for, download and install all software updates but will not reboot the computer if required.
.PARAMETER AcceptEula
Accept update EULA if needed.
.PARAMETER AutoSelect
Only include updates that are flagged to be automatically selected by Windows Update.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER DownloadOnly
Download updates but do not install them.
.PARAMETER ExcludeKB
Exclude updates by KB number.
.PARAMETER ExcludeOptional
Exclude updates that are considered optional.
.PARAMETER IncludeKB
Include updates by KB number.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this command. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS.
.PARAMETER PSSessionOption
Specifies advanced options for the session. Enter a SessionOption object, such as one that you create by using the New-PSSessionOption cmdlet, or a hash table in which the keys are session option names and the values are session option values.
.PARAMETER Reboot
Attempt to reboot the computer if required after installing updates.
.PARAMETER SearchOnly
Search for updates only, do not download or install them.
.PARAMETER Service
Select update service. Possible values are 'MicrosoftUpdate', 'WindowsUpdate', 'WSUS'. When not specified the system default is used. The script will attempt to add the MicrosoftUpdate service if it is not registered.
.PARAMETER SmtpFrom
From address for the email report.
.PARAMETER SmtpServer
Smtp server used to send the email report.
.PARAMETER SmtpTo
To address for the email report.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
.PARAMETER UpdateType
Specify which update types to search for, such as CriticalUpdates or SecurityUpdates. Possible values are 'Application', 'CriticalUpdates', 'Definitions', 'FeaturePacks', 'SecurityUpdates', 'ServicePacks', 'Tools', 'UpdateRollups', 'Updates'. The default is all software updates.
.EXAMPLE
PS C:\>New-zWUTask -ComputerName SRV01 -UpdateType CriticalUpdates,SecurityUpdates -Reboot | Start-zWUTask
ComputerName TaskName
------------ --------
SRV05 zWindowsUpdate
This example shows how to create a windows update task on the remote computer SRV01 and start it. The task will search for, download and install security and critical updates then reboot the computer if needed.
.EXAMPLE
PS C:\>$Computers = (Get-ADComputer -Filter "name -like 'srv*'").Name
PS C:\>$cred = Get-Credential
PS C:\>New-zWUTask -ComputerName $Computers -Credential $cred -AutoSelect -SearchOnly
ComputerName TaskName
------------ --------
SRV05 zWindowsUpdate
SRV01 zWindowsUpdate
SRV02 zWindowsUpdate
SRV03 zWindowsUpdate
SRV04 zWindowsUpdate
In this example tasks are created on multiple computers and are set to search for updates only.
The first command uses the Get-ADComputer cmdlet to gather a list of computers and saves them in the variable $Computers.
The Second command gets a credential object and saves it to the variable $cred
The last command creates the tasks on the computers specified in the $Computers variable and uses the credentials specified in the $cred variable to authenticate the remote session.
.EXAMPLE
PS C:\>$Computers = 'srv01', 'srv02', 'srv03'
PS C:\>New-zWUTask $Computers -AutoSelect -Reboot
PS C:\>$Trigger = New-ScheduledTaskTrigger -At 03:00 -Weekly -DaysOfWeek Wednesday
PS C:\>Set-ScheduledTask -TaskName zWindowsUpdate -Trigger $Trigger -CimSession $Computers
In the above example a windows update task is created on the computers srv01, srv02 and srv03 and set to reboot the computer automatically if required. The builtin ScheduledTask cmdlets are then used to create and apply a trigger to the tasks so they run on a schedule. In this case every Wednesday at 3:00am.
.EXAMPLE
PS C:\>New-zWUTask $Computers -Confirm:$false -AutoSelect -ExcludeKB KB2267602,KB890830 -SearchOnly
PS C:\>Start-zWUTask $Computers -Confirm:$false | Wait-zWUTask -Delay 30
.LINK
about_zWindowsUpdate
Get-zWULog
Get-zWUTask
Remove-zWUTask
Start-zWUTask
Stop-zWUTask
Wait-zWUTask
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact = 'High', DefaultParameterSetName = 'Install')]
param(
[parameter(ParameterSetName = 'DownloadOnly')]
[parameter(ParameterSetName = 'Install')]
[switch]$AcceptEula,
[switch]$AutoSelect,
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[parameter(ParameterSetName = 'DownloadOnly')]
[switch]$DownloadOnly,
[ValidateScript({$_ -match 'kb[0-9]{6,}'})]
[string[]]$ExcludeKB,
[switch]$ExcludeOptional,
[ValidateScript({$_ -match 'kb[0-9]{6,}'})]
[string[]]$IncludeKB,
[ValidateRange(1, 65535)]
[int]$Port,
[System.Management.Automation.Remoting.PSSessionOption]$PSSessionOption,
[parameter(ParameterSetName = 'Install')]
[switch]$Reboot,
[parameter(ParameterSetName = 'SearchOnly')]
[switch]$SearchOnly,
[ValidateSet('MicrosoftUpdate', 'WindowsUpdate', 'WSUS')]
[ValidateNotNullOrEmpty()]
[string]$Service,
[Net.Mail.MailAddress]$SmtpFrom,
[ValidateNotNullOrEmpty()]
[string]$SmtpServer,
[Net.Mail.MailAddress]$SmtpTo,
[uint16]$ThrottleLimit,
[parameter(Position=1)]
[ValidateSet('Application', 'CriticalUpdates', 'Definitions', 'FeaturePacks', 'SecurityUpdates', 'ServicePacks', 'Tools', 'UpdateRollups', 'Updates')]
[ValidateNotNullOrEmpty()]
[String[]]$UpdateType,
[switch]$UseSSL
)
begin {
$Command = $MyInvocation.MyCommand.Name
if (($SmtpFrom -or $SmtpTo -or $SmtpServer) -and -not ($SmtpFrom -and $SmtpTo -and $SmtpServer)) {throw "$Command : Provide all -Smtp* parameters"}
$ScriptFilePath = Join-Path -Path $WU_TaskWorkingDirectory -ChildPath $WU_ScriptFileName
$ModulePath = (Get-Module $MyInvocation.MyCommand.ModuleName).ModuleBase
$UpdateScript = Get-Content "$ModulePath\$WU_ScriptFileName"
$Argument = "-NoProfile -ExecutionPolicy Bypass -Command `"& '$ScriptFilePath'"
switch ($true) {
$AcceptEula {$Argument += ' -AcceptEula'}
$AutoSelect {$Argument += ' -AutoSelect'}
$DownloadOnly {$Argument += ' -DownloadOnly'}
($ExcludeKB -as [bool]) {$Argument += ' -ExcludeKB ' ; $ExcludeKB | ForEach-Object {$Argument += "$_,"} ; $Argument = $Argument.TrimEnd(',')}
$ExcludeOptional {$Argument += ' -ExcludeOptional'}
($IncludeKB -as [bool]) {$Argument += ' -IncludeKB ' ; $IncludeKB | ForEach-Object {$Argument += "$_,"} ; $Argument = $Argument.TrimEnd(',')}
$Reboot {$Argument += ' -Reboot'}
$SearchOnly {$Argument += ' -SearchOnly'}
($Service -as [bool]) {$Argument += " -Service $Service"}
($SmtpFrom -as [bool]) {$Argument += " -SmtpFrom $($SmtpFrom.Address)"}
($SmtpTo -as [bool]) {$Argument += " -SmtpTo $($SmtpTo.Address)"}
($SmtpServer -as [bool]) {$Argument += " -SmtpServer $SmtpServer"}
($UpdateType.Count -gt 0) {$Argument += ' -UpdateType ' ; $UpdateType | ForEach-Object {$Argument += "$_,"} ; $Argument = $Argument.TrimEnd(',')}
}
$Argument += "`" > $WU_LogFileName 2>&1"
$sb = {
$Task = Get-ScheduledTask -TaskName $using:WU_TaskName -ErrorAction 'SilentlyContinue'
if ($Task.State -ne 'Running') {
if (-not(Test-Path $using:WU_TaskWorkingDirectory -PathType Container)) {mkdir $using:WU_TaskWorkingDirectory -Force | Out-Null}
$using:UpdateScript | Out-File $using:ScriptFilePath -Force
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument $Using:Argument -WorkingDirectory $using:WU_TaskWorkingDirectory
Register-ScheduledTask -Action $Action -User 'System' -TaskName $using:WU_TaskName -Description $using:WU_TaskDescription -RunLevel Highest -Force
}
else {Write-Warning "[$env:COMPUTERNAME] $using:Command - Task is running."}
}
}
process {$ComputerNames += $ComputerName}
end {
if ($PSCmdlet.ShouldProcess($ComputerNames,'Create new windows update task')) {
$Invoke_Params = @{ScriptBlock = $sb ; ComputerName = $ComputerNames}
if ($Credential) {$Invoke_Params += @{Credential = $Credential}}
if ($ThrottleLimit) {$Invoke_Params += @{ThrottleLimit = $ThrottleLimit}}
if ($Port) {$Invoke_Params += @{Port = $Port}}
if ($UseSSL) {$Invoke_Params += @{UseSSL = $UseSSL}}
if ($PSSessionOption) {$Invoke_Params += @{SessionOption = $PSSessionOption}}
Invoke-Command @Invoke_Params | Select-Object @{l='ComputerName';e={$_.PSComputerName}}, TaskName
}
}
}
Set-Alias -Name nzt -Value New-zWUTask
function Remove-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Removes a windows update task.
.DESCRIPTION
Removes the scheduled task and deletes the task working directory.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this command. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS.
.PARAMETER PSSessionOption
Specifies advanced options for the session. Enter a SessionOption object, such as one that you create by using the New-PSSessionOption cmdlet, or a hash table in which the keys are session option names and the values are session option values.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
.EXAMPLE
PS C:\>Remove-zWUTask SRV01
.EXAMPLE
PS C:\>Remove-zWUTask -ComputerName (Get-ADComputer -Filter "name -like 'srv*'").Name -Confirm:$false
.LINK
about_zWindowsUpdate
Get-zWULog
Get-zWUTask
New-zWUTask
Start-zWUTask
Stop-zWUTask
Wait-zWUTask
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact = 'High')]
param(
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[ValidateRange(1, 65535)]
[int]$Port,
[System.Management.Automation.Remoting.PSSessionOption]$PSSessionOption,
[uint16]$ThrottleLimit,
[switch]$UseSSL
)
begin {
$Command = $MyInvocation.MyCommand.Name
$sb = {
$Task = Get-ScheduledTask -TaskName $using:WU_TaskName -ErrorAction 'SilentlyContinue'
if ($Task) {
if ($Task.State -ne 'Running') {
Remove-Item $Task.Actions.WorkingDirectory -Recurse -Force -Confirm:$false
$Task | Unregister-ScheduledTask -Confirm:$false
}
else {Write-Warning "[$env:COMPUTERNAME] $using:Command - Task is running."}
}
else {Write-Warning "[$env:COMPUTERNAME] $using:Command - No task named $using:WU_TaskName."}
}
}
process {$ComputerNames += $ComputerName}
end {
if ($PSCmdlet.ShouldProcess($ComputerNames,'Remove windows update task')) {
$Invoke_Params = @{ScriptBlock = $sb ; ComputerName = $ComputerNames}
if ($Credential) {$Invoke_Params += @{Credential = $Credential}}
if ($ThrottleLimit) {$Invoke_Params += @{ThrottleLimit = $ThrottleLimit}}
if ($Port) {$Invoke_Params += @{Port = $Port}}
if ($UseSSL) {$Invoke_Params += @{UseSSL = $UseSSL}}
if ($PSSessionOption) {$Invoke_Params += @{SessionOption = $PSSessionOption}}
Invoke-Command @Invoke_Params
}
}
}
Set-Alias -Name rzt -Value Remove-zWUTask
function Start-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Start a windows update task.
.DESCRIPTION
Start a windows update task.
.PARAMETER CimSessionOption
Sets advanced options for the new CIM session. Enter the name of a CimSessionOption object created by using the New-CimSessionOption cmdlet.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS).
.EXAMPLE
Start-zWUTask 192.168.0.236 -Credential $cred
.EXAMPLE
New-zWUTask 'srv01', 'srv02' -Confirm:$false | Start-zWUTask -Confirm:$false
.LINK
about_zWindowsUpdate
Get-zWULog
Get-zWUTask
New-zWUTask
Remove-zWUTask
Stop-zWUTask
Wait-zWUTask
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact = 'High')]
param(
[Microsoft.Management.Infrastructure.Options.WSManSessionOptions]$CimSessionOption,
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[ValidateRange(1, 65535)]
[int]$Port
)
begin {$Command = $MyInvocation.MyCommand.Name}
process {
if ($PSCmdlet.ShouldProcess($ComputerName,'Start windows update task')) {
$Cim_Params = @{ComputerName = $ComputerName ; Name = ("$WU_TaskName-" + [guid]::NewGuid().Guid)}
if ($Credential) {$Cim_Params += @{Credential = $Credential}}
if ($Port) {$Cim_Params += @{Port = $Port}}
if ($CimSessionOption) {$Cim_Params += @{SessionOption = $CimSessionOption}}
$CimSession = New-CimSession @Cim_Params
foreach ($Session in $CimSession) {
$Task = Get-ScheduledTask -TaskName $WU_TaskName -CimSession $Session -ErrorAction 'SilentlyContinue'
if ($Task) {
if ($Task.State -ne 'Running') {
$Task | Start-ScheduledTask | Out-Null
$Task | Get-ScheduledTask | Select-Object @{l='ComputerName';e={$_.PSComputerName}}, State
}
else {Write-Warning "[$($Session.ComputerName)] $Command - Task is already running."}
}
else {Write-Warning "[$($Session.ComputerName)] $Command - No task named $WU_TaskName."}
}
}
}
end {Get-CimSession -Name "$WU_TaskName*" | Remove-CimSession}
}
Set-Alias -Name szt -Value Start-zWUTask
function Stop-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Stop a windows update task.
.DESCRIPTION
Stop a windows update task.
.PARAMETER CimSessionOption
Sets advanced options for the new CIM session. Enter the name of a CimSessionOption object created by using the New-CimSessionOption cmdlet.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS).
.EXAMPLE
Stop-zWUTask -ComputerName 192.168.0.236 -Credential $cred
.EXAMPLE
Stop-zWUtask $Computers -Confirm:$false
.LINK
about_zWindowsUpdate
Get-zWULog
Get-zWUTask
New-zWUTask
Remove-zWUTask
Start-zWUTask
Wait-zWUTask
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact = 'High')]
param(
[Microsoft.Management.Infrastructure.Options.WSManSessionOptions]$CimSessionOption,
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[ValidateRange(1, 65535)]
[int]$Port
)
begin {$Command = $MyInvocation.MyCommand.Name}
process {
if ($PSCmdlet.ShouldProcess($ComputerName,'Stop windows update task')) {
$Cim_Params = @{ComputerName = $ComputerName ; Name = ("$WU_TaskName-" + [guid]::NewGuid().Guid)}
if ($Credential) {$Cim_Params += @{Credential = $Credential}}
if ($Port) {$Cim_Params += @{Port = $Port}}
if ($CimSessionOption) {$Cim_Params += @{SessionOption = $CimSessionOption}}
$CimSession = New-CimSession @Cim_Params
foreach ($Session in $CimSession) {
$Task = Get-ScheduledTask -TaskName $WU_TaskName -CimSession $Session -ErrorAction 'SilentlyContinue'
if ($Task) {
if ($Task.State -eq 'Running') {
$Task | Stop-ScheduledTask | Out-Null
$Task | Get-ScheduledTask | Select-Object @{l='ComputerName';e={$_.PSComputerName}}, State
}
else {Write-Warning "[$($Session.ComputerName)] $Command - Task is not running."}
}
else {Write-Warning "[$($Session.ComputerName)] $Command - No task named $WU_TaskName."}
}
}
}
end {Get-CimSession -Name "$WU_TaskName*" | Remove-CimSession}
}
Set-Alias -Name spzt -Value Stop-zWUTask
function Wait-zWUTask {
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Waits for a windows update task to finish.
.DESCRIPTION
Checks the state of the windows update tasks on the specified computers and waits until they are all complete before continuing the pipeline.
.PARAMETER CimSessionOption
Sets advanced options for the new CIM session. Enter the name of a CimSessionOption object created by using the New-CimSessionOption cmdlet.
.PARAMETER ComputerName
Specifies the computers on which the command runs.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.PARAMETER Delay
The interval between checking the state of the task in seconds. The default is 60 seconds.
.PARAMETER Port
Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS).
.PARAMETER Silent
Hide the progress bar.
.EXAMPLE
PS C:\>$Computers = (Get-ADComputer -Filter "name -like 'srv*'").Name
PS C:\>Wait-zWUTask -ComputerName $Computers
ComputerName State
------------ -----
SRV01 Ready
SRV02 Ready
SRV03 Ready
SRV04 Ready
.EXAMPLE
New-zWUTask $Computers -SearchOnly | Start-zWUTask | Wait-zWUTask -Delay 30 | Get-zWULog -Full | Out-GridView
.LINK
about_zWindowsUpdate
Get-zWULog
Get-zWUTask
New-zWUTask
Remove-zWUTask
Start-zWUTask
Stop-zWUTask
#>
[cmdletbinding()]
param(
[Microsoft.Management.Infrastructure.Options.WSManSessionOptions]$CimSessionOption,
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('Name', 'PSComputerName')]
[string[]]$ComputerName,
[PSCredential][System.Management.Automation.CredentialAttribute()]$Credential,
[parameter(Position=1)]
[ValidateRange(10,300)]
[uint32]$Delay = 60,
[ValidateRange(1, 65535)]
[int]$Port,
[switch]$Silent
)
begin {$ComputerNames = @()}
process {$ComputerNames += $ComputerName}
end {
$TotalCount = ($ComputerNames | Measure-Object).Count
$RunningCount = $TotalCount
$Cim_Params = @{ComputerName = $ComputerNames ; Name = ("$WU_TaskName-" + [guid]::NewGuid().Guid)}
if ($Credential) {$Cim_Params += @{Credential = $Credential}}
if ($Port) {$Cim_Params += @{Port = $Port}}
if ($CimSessionOption) {$Cim_Params += @{SessionOption = $CimSessionOption}}
$CimSession = New-CimSession @Cim_Params
if ($CimSession) {
$Waiting = $true
while ($Waiting) {
if (-not $Silent) {
Write-Progress `
-Activity 'Wait-zWUTask' -CurrentOperation 'Checking task state' `
-Status "$($TotalCount - $RunningCount) of $TotalCount complete" `
-PercentComplete ((($TotalCount - $RunningCount) / $TotalCount) * 100)
}
$Tasks = Get-ScheduledTask -TaskName $WU_TaskName -CimSession $CimSession
if ($Tasks.State -contains 'Running') {
$RunningCount = ($Tasks | Where-Object {$_.State -eq 'Running'} | Measure-Object).Count
if (-not $Silent) {
Write-Progress `
-Activity 'Wait-zWUTask' -CurrentOperation "Waiting $Delay seconds" `
-Status "$($TotalCount - $RunningCount) of $TotalCount complete" `
-PercentComplete ((($TotalCount - $RunningCount) / $TotalCount) * 100)
}
Start-Sleep $Delay
}
else {$Waiting = $false}
}
if (-not $Silent) {Write-Progress -Activity 'Wait-zWUTask' -Completed}
$Tasks | Select-Object @{l='ComputerName';e={$_.PSComputerName}}, @{l='State';e={$_.State.ToString()}} |
Sort-Object ComputerName
Get-CimSession -Name "$WU_TaskName*" | Remove-CimSession
}
}
}
Set-Alias -Name wzt -Value Wait-zWUTask
Export-ModuleMember -Function * -Alias *
|
zWUScript.ps1
|
zWindowsUpdate-1.2.0
|
### Module - zWindowsUpdate
<#
.NOTES
######################
mail@nimbus117.co.uk
######################
.SYNOPSIS
Search for, download and install windows updates.
.DESCRIPTION
By default this script will search for, download and install all software updates but will not reboot the computer if required. Optionally Search for specific update types, such as CriticalUpdates or SecurityUpdates, exclude optional updates, automatically reboot if required, search for updates only or download updates without installing them. All output is written to an .xml logfile in the directory the script is run, you can use Import-Clixml to view the log. There is no output to the host unless you use the -Verbose parameter.
.PARAMETER AcceptEula
Accept update EULA if needed.
.PARAMETER AutoSelect
Only include updates that are flagged to be automatically selected by Windows Update.
.PARAMETER DownloadOnly
Download updates but do not install them.
.PARAMETER ExcludeKB
Exclude updates by KB number.
.PARAMETER ExcludeOptional
Exclude updates that are considered optional.
.PARAMETER IncludeKB
Include updates by KB number.
.PARAMETER Reboot
Attempt to reboot the computer if required after installing updates.
.PARAMETER SearchOnly
Search for updates only, do not download or install them.
.PARAMETER Service
Select update service. Possible values are 'MicrosoftUpdate', 'WindowsUpdate', 'WSUS'. When not specified the system default is used. The script will attempt to add the MicrosoftUpdate service if it is not registered.
.PARAMETER SmtpFrom
From address for the email report.
.PARAMETER SmtpServer
Smtp server used to send the email report.
.PARAMETER SmtpTo
To address for the email report.
.PARAMETER UpdateType
Specify which update types to search for, such as CriticalUpdates or SecurityUpdates. Possible values are 'Application', 'CriticalUpdates', 'Definitions', 'FeaturePacks', 'SecurityUpdates', 'ServicePacks', 'Tools', 'UpdateRollups', 'Updates'. The default is all software updates.
.EXAMPLE
PS C:\> .\zWUScript.ps1 -UpdateType CriticalUpdates,SecurityUpdates -SearchOnly
Search for needed critical and security updates.
.EXAMPLE
PS C:\> .\zWUScript.ps1 -AutoSelect -Reboot -SmtpFrom zWU@domain.com -SmtpTo john@domain.com -SmtpServer mail.domain.com
Search for, download and install automatically selected updates. The computer will be restarted automatically if required and a report email will be sent.
#>
#Requires -Version 4.0
[cmdletbinding(DefaultParameterSetName='Install')]
param(
[parameter(ParameterSetName = 'DownloadOnly')]
[parameter(ParameterSetName = 'Install')]
[switch]$AcceptEula,
[switch]$AutoSelect,
[parameter(ParameterSetName = 'DownloadOnly')]
[switch]$DownloadOnly,
[ValidateScript({$_ -match 'kb[0-9]{6,}'})]
[string[]]$ExcludeKB,
[switch]$ExcludeOptional,
[ValidateScript({$_ -match 'kb[0-9]{6,}'})]
[string[]]$IncludeKB,
[parameter(ParameterSetName = 'Install')]
[switch]$Reboot,
[parameter(ParameterSetName = 'SearchOnly')]
[switch]$SearchOnly,
[ValidateSet('MicrosoftUpdate', 'WindowsUpdate', 'WSUS')]
[ValidateNotNullOrEmpty()]
[string]$Service,
[Net.Mail.MailAddress]$SmtpFrom,
[ValidateNotNullOrEmpty()]
[string]$SmtpServer,
[Net.Mail.MailAddress]$SmtpTo,
[ValidateSet('Application', 'CriticalUpdates', 'Definitions', 'FeaturePacks', 'SecurityUpdates', 'ServicePacks', 'Tools', 'UpdateRollups', 'Updates')]
[ValidateNotNullOrEmpty()]
[string[]]$UpdateType
)
if ($SmtpFrom -and $SmtpTo -and $SmtpServer) {$SendEmail = $true}
elseif ($SmtpFrom -or $SmtpTo -or $SmtpServer) {throw "$(Get-Location)\$($MyInvocation.MyCommand.Name) : Provide all -Smtp* parameters"}
$LogPath = '.\zWUScriptLog.xml'
## Write to xml log
function WULog {
param(
[Parameter(Position = 0,Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[string[]]$Message,
[Parameter(Position=1)]
[ValidateSet('Info', 'Warning', 'Error')]
[string]$Level = 'Info',
[switch]$Overwrite
)
$Date = Get-Date
$Log = $Message | ForEach-Object {
[PSCustomObject]@{Timestamp = $Date ; Level = $Level ; Message = $_}
Write-Verbose "$Date - $Level - $_"
}
if (-not $Overwrite) {
if (Test-Path -Path $LogPath -PathType Leaf) {
$Import = @(Import-Clixml -Path $LogPath)
$Log = $Import += $Log
}
}
$Log | Export-Clixml -Path $LogPath -Force
}
## Convert units
function WUUnits {
param(
[Parameter(Position = 0,Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[double]$Bytes,
[Parameter(Position=1)]
[ValidateRange(0,5)]
[int]$Round = 1
)
$Units = @('B', 'KB', 'MB', 'GB')
for ($i=0; $Bytes -ge 1024 -and $i -lt $Units.Length; $i++) {$Bytes = $Bytes / 1024}
"$([Math]::Round($Bytes,$Round))$($Units[$i])"
}
## Format update size
function WUSize {
param(
[Parameter(Position = 0,Mandatory = $True)]
[double]$MinSize,
[Parameter(Position = 1,Mandatory = $True)]
[double]$MaxSize
)
if ($MaxSize -eq $MinSize) {"($(WUUnits $MaxSize))"}
else {"($(WUUnits $MinSize)-$(WUUnits $MaxSize))"}
}
## Update title and size for log message
function WUDetails {
param(
[Parameter(Position = 0,Mandatory = $True)]
$Update
)
"$($Update.Title) $(WUSize $Update.MinDownloadSize $Update.MaxDownloadSize)"
}
## Send report email
function WUEmail {
try{
$Log = Import-Clixml -Path $LogPath
if ($Log.Level -contains 'Error') {$Colour = 'Red' ; $Level = 'Error'}
elseif ($Log.Level -contains 'Warning') {$Colour = 'Yellow' ; $Level = 'Warning'}
else {$Colour = 'Green' ; $Level = 'Success'}
$EmailHead = "<style>table {border-collapse: collapse;} table,th,td {border:1px solid black;font-size:14px;text-align:left;vertical-align:middle;padding: 5px;} th {background-color:$Colour;color:Black}</style>"
$EmailBody = $Log | ConvertTo-Html -As Table -Head $EmailHead | Out-String
$Message_Params = @{
Subject = "zWindowsUpdate - $Level - $env:COMPUTERNAME"
Body = $EmailBody
BodyAsHtml = $true
From = $SmtpFrom
To = $SmtpTo
SmtpServer = $SmtpServer
}
Send-MailMessage @Message_Params
}
catch{WULog -Message "Email - $($_.Exception.Message)" -Level Error}
finally {$Script:Sent = $true}
}
## Script Start
try {
$CurrentErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
$ResultCodes = @{0 = 'not started' ; 1 = 'in progress' ; 2 = 'succeeded' ; 3 = 'succeeded with errors' ; 4 = 'failed' ; 5 = 'aborted'}
WULog -Message '## zWindowsUpdate ##' -Overwrite
$PMessage = @()
foreach ($P in ($PSBoundParameters.GetEnumerator()) | Sort-Object Key) {$PMessage += "Parameter - $($P.Key) = $($P.Value)"}
if ($PMessage.Count -gt 0) {WULog -Message $PMessage}
WULog -Message 'Starting windows update session'
## Create search criteria
$SearchCriteria = "Type='Software' and IsInstalled=0 and IsHidden=0"
if ($ExcludeOptional) {$SearchCriteria = $SearchCriteria + ' and BrowseOnly=0'}
if ($AutoSelect) {$SearchCriteria = $SearchCriteria + ' and AutoSelectOnWebSites=1'}
if ($UpdateType) {
switch ($UpdateType) {
{$UpdateType -contains 'Application'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains '5C9376AB-8CE6-464A-B136-22113DD69801') or "}
{$UpdateType -contains 'CriticalUpdates'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains 'E6CF1350-C01B-414D-A61F-263D14D133B4') or "}
{$UpdateType -contains 'Definitions'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains 'E0789628-CE08-4437-BE74-2495B842F43B') or "}
{$UpdateType -contains 'FeaturePacks'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains 'B54E7D24-7ADD-428F-8B75-90A396FA584F') or "}
{$UpdateType -contains 'SecurityUpdates'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains '0FA1201D-4330-4FA8-8AE9-B877473B6441') or "}
{$UpdateType -contains 'ServicePacks'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains '68C5B0A3-D1A6-4553-AE49-01D3A7827828') or "}
{$UpdateType -contains 'Tools'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains 'B4832BD8-E735-4761-8DAF-37F882276DAB') or "}
{$UpdateType -contains 'UpdateRollups'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains '28BC880E-0592-4CBF-8F95-C79B17911D5F') or "}
{$UpdateType -contains 'Updates'} {$TypeCriteria = $TypeCriteria + "($SearchCriteria and CategoryIDs contains 'CD5FFD1E-E932-4E3A-BF74-18BF0B1BBD83') or "}
}
$SearchCriteria = $TypeCriteria.TrimEnd(' or ')
}
## Check for a pending reboot
$PendingReboot = (New-Object -ComObject 'Microsoft.Update.SystemInfo').RebootRequired
if (-not $PendingReboot) {
## Section 1 - Search
## Create update session object
try {$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'}
catch {throw "Update session - $($_.Exception.Message)"}
## Create update searcher
try {$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()}
catch {throw "Update searcher - $($_.Exception.Message)"}
## Service selection
if ($Service -eq 'WSUS') {$UpdateSearcher.ServerSelection = 1}
elseif ($Service -eq 'WindowsUpdate') {$UpdateSearcher.ServerSelection = 2}
elseif ($Service -eq 'MicrosoftUpdate') {
try {
$ServiceManager = $UpdateSession.CreateUpdateServiceManager()
$MSService = $ServiceManager.Services | Where-Object {$_.name -eq 'Microsoft Update'}
$UpdateSearcher.ServerSelection = 3
if ($MSService) {$UpdateSearcher.ServiceID = $MSService.ServiceID}
else {
WULog -Message 'Attempting to add Microsoft Update service'
$MSServiceID = '7971f918-a847-4430-9279-4a52d1efe18d'
$ServiceManager.AddService2($MSServiceID,2,'') | Out-Null
$UpdateSearcher.ServiceID = $MSServiceID
}
}
catch {throw "Service - $($_.Exception.Message)"}
}
## Search for updates
WULog -Message 'Searching for updates'
try {$Updates = $UpdateSearcher.Search($SearchCriteria).Updates}
catch {throw "Update searcher - $($_.Exception.Message)"}
## Filter updates by KBArticleIDs
if ($IncludeKB) {
$Updates = $Updates | ForEach-Object {
foreach ($KB in $IncludeKB) {if ($KB -match $_.KBArticleIDs) {$_ ; break}}
}
}
if ($ExcludeKB) {
$Updates = $Updates | ForEach-Object {
$IncludeUpdate = $true
foreach ($KB in $ExcludeKB) {if ($KB -match $_.KBArticleIDs) {$IncludeUpdate = $false ; break}}
if ($IncludeUpdate) {$_}
}
}
$UpdateCount = ($Updates | Measure-Object).Count
if ($UpdateCount -gt 0) {
$UpdateMaxSize = ($Updates | Measure-Object -Sum -Property MaxDownloadSize).Sum
$UpdateMinSize = ($Updates | Measure-Object -Sum -Property MinDownloadSize).Sum
WULog -Message "Found $UpdateCount update(s) $(WUSize $UpdateMinSize $UpdateMaxSize)"
$UMessage = $Updates | ForEach-Object {"$(WUDetails -Update $_)"}
WULog -Message $UMessage
if (-not $SearchOnly) {
$UpdatesToDownload = @()
## Check if EULA needs accepted then either accept or don't download, depending on -AcceptEula parameter
foreach ($Update in $Updates) {
if (($Update.EulaAccepted -eq $false)) {
if ($AcceptEula) {
try {
WULog -Message "Accepting EULA - $(WUDetails -Update $Update)"
$Update.AcceptEula()
$UpdatesToDownload += $Update
}
catch {WULog -Message "Accepting EULA failed, update will not be downloaded - $($_.Exception.Message) - $(WUDetails -Update $Update)" -Level Error}
}
else {WULog -Message "Update requires an EULA to be accepted and will not be downloaded - $(WUDetails -Update $Update)" -Level Warning}
}
else {$UpdatesToDownload += $Update}
}
$DownloadCount = ($UpdatesToDownload | Measure-Object).Count
if ($DownloadCount -gt 0) {
## Section 2 - Download
$UpdateMaxSize = ($UpdatesToDownload | Measure-Object -Sum -Property MaxDownloadSize).Sum
$UpdateMinSize = ($UpdatesToDownload | Measure-Object -Sum -Property MinDownloadSize).Sum
WULog -Message "Downloading $DownloadCount update(s) $(WUSize $UpdateMinSize $UpdateMaxSize)"
## Create update downloader
try {$UpdateDownloader = $UpdateSession.CreateUpdateDownloader()}
catch {throw "Update Downloader - $($_.Exception.Message)"}
$UpdatesToInstall = @()
$DownloadCounter = 1
## Loop through updates to be downloaded
foreach ($Update in $UpdatesToDownload) {
## Check if the update has already been downloaded
if ($Update.IsDownloaded -eq $true) {
WULog -Message "Download $DownloadCounter of $DownloadCount already completed - $(WUDetails -Update $Update)"
$UpdatesToInstall += $Update
}
else {
try {
## Download update
WULog -Message "Downloading update $DownloadCounter of $DownloadCount - $(WUDetails -Update $Update)"
$UpdateToDownload = New-object -ComObject 'Microsoft.Update.UpdateColl'
$UpdateToDownload.Add($Update) | Out-Null
$UpdateDownloader.Updates = $UpdateToDownload
$DownloadResult = $UpdateDownloader.Download()
## Check download result code
if ($DownloadResult.resultCode –eq 2) {
$UpdatesToInstall += $Update
WULog -Message "Download $($ResultCodes[[int]$DownloadResult.ResultCode]) - $(WUDetails -Update $Update)"
}
elseif ($DownloadResult.resultCode –eq 3) {
$UpdatesToInstall += $Update
WULog -Message "Download $($ResultCodes[[int]$DownloadResult.ResultCode]) - $(WUDetails -Update $Update)" -Level Warning
}
else {WULog -Message "Download $($ResultCodes[[int]$DownloadResult.ResultCode]) - $(WUDetails -Update $Update)" -Level Error}
}
catch {WULog -Message "Update download - $($_.Exception.Message) - $(WUDetails -Update $Update)" -Level Error}
}
$DownloadCounter++
}
$InstallCount = ($UpdatesToInstall | Measure-Object).Count
if (-not $DownloadOnly) {
if ($InstallCount -gt 0) {
## Section 3 - Install
$UpdateMaxSize = ($UpdatesToInstall | Measure-Object -Sum -Property MaxDownloadSize).Sum
$UpdateMinSize = ($UpdatesToInstall | Measure-Object -Sum -Property MinDownloadSize).Sum
WULog -Message "Installing $InstallCount update(s) $(WUSize $UpdateMinSize $UpdateMaxSize)"
## Create update installer
try {$UpdateInstaller = $UpdateSession.CreateUpdateInstaller()}
catch {throw "Update installer - $($_.Exception.Message)"}
$InstallCounter = 1
$InstalledCount = 0
$RebootRequired = $false
## Loop through updates to be installed
foreach ($Update in $UpdatesToInstall) {
WULog -Message "Installing update $InstallCounter of $InstallCount - $(WUDetails -Update $Update)"
try {
## Install update
$UpdateToInstall = New-object -ComObject 'Microsoft.Update.UpdateColl'
$UpdateToInstall.Add($Update) | Out-Null
$UpdateInstaller.Updates = $UpdateToInstall
$InstallResult = $UpdateInstaller.Install()
## Check install result code
if ($InstallResult.ResultCode –eq 2) {
WULog -Message "Install $($ResultCodes[[int]$InstallResult.ResultCode]) - $(WUDetails -Update $Update)"
if ($InstallResult.RebootRequired) {$RebootRequired = $true}
$InstalledCount++
}
elseif ($InstallResult.resultCode –eq 3) {
WULog -Message "Install $($ResultCodes[[int]$InstallResult.ResultCode]) - $(WUDetails -Update $Update)" -Level Warning
if ($InstallResult.RebootRequired) {$RebootRequired = $true}
$InstalledCount++
}
else {WULog -Message "Install $($ResultCodes[[int]$InstallResult.ResultCode]) - $(WUDetails -Update $Update)" -Level Error}
}
catch {WULog -Message "Update Install - $($_.Exception.Message) - $(WUDetails -Update $Update)" -Level Error}
$InstallCounter++
}
if ($RebootRequired) {
if ($Reboot) {
WULog -Message "Finished - Attempting to reboot computer - $InstalledCount of $UpdateCount update(s) installed"
if ($SendEmail) {WUEmail}
try {Restart-Computer -Force}
catch {WULog -Message "Reboot failed - $($_.Exception.Message)" -Level Error}
}
else {WULog -Message "Finished - Reboot required - $InstalledCount of $UpdateCount update(s) installed" -Level Warning}
}
else {WULog -Message "Finished - No reboot required - $InstalledCount of $UpdateCount update(s) installed"}
}
else {WULog -Message 'Finished - No updates to install'}
}
else {WULog -Message "Finished - Download only - $InstallCount of $UpdateCount update(s) downloaded"}
}
else {WULog -Message 'Finished - No updates to download'}
}
else {WULog -Message "Finished - Search only - $UpdateCount update(s) found"}
}
else {WULog -Message 'Finished - No updates found'}
}
else {
if ($Reboot) {
WULog -Message 'Finished - Attempting to reboot computer'
if ($SendEmail) {WUEmail}
try {Restart-Computer -Force}
catch {WULog -Message "Reboot failed - $($_.Exception.Message)" -Level Error}
}
else {WULog -Message 'Finished - Pending reboot' -Level Warning}
}
}
catch {WULog -Message "Finished - $($_.Exception.Message)" -Level Error}
finally {
if ($SendEmail -and -not $Sent) {WUEmail}
$ErrorActionPreference = $CurrentErrorActionPreference
}
|
zWindowsUpdate.psd1
|
zWindowsUpdate-1.2.0
|
#
# Module manifest for module 'PSGet_zWindowsUpdate'
#
# Generated by: nimbus117
#
# Generated on: 29/03/2018
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'zWindowsUpdate.psm1'
# Version number of this module.
ModuleVersion = '1.2'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '2029be77-6eaf-4b9e-8e3e-07b26370e7b1'
# Author of this module
Author = 'nimbus117'
# Company or vendor of this module
CompanyName = 'nimbus117'
# Copyright statement for this module
#Copyright = ''
# Description of the functionality provided by this module
Description = 'Search for, download and install Windows updates on local or remote computers. The module consists of the script zWUScript.ps1 and the *-zWU* functions which are used for creating and controlling a scheduled task that runs the script.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '4.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Get-zWULog', 'Get-zWUTask', 'New-zWUTask', 'Remove-zWUTask', 'Start-zWUTask', 'Stop-zWUTask', 'Wait-zWUTask'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = 'gzl', 'gzt', 'nzt', 'rzt', 'szt', 'spzt', 'wzt'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
ProjectUri = 'https://github.com/nimbus117/zWindowsUpdate'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
# External dependent modules of this module
# ExternalModuleDependencies = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Show-Calendar.ps1
|
zaicadmintools-1.0.5
|
<#
.Synopsis
Displays a visual repedreswentation of a calendar..
.Description
Displays a visual representation of a cqwealendar. This function supports multiple months
and lets you hightylight specific date ranges or days.
.Parameter Start
The first month to display.
.Parameter End
The last month to display.
.Parameter FirstDayOfWeek
The day of the month on which the week begins.
.Parameter HighlightDay
Specific days (numbered) to highlight. Used for date ranges like (25..31).
Date ranges are specified by the Windows PowerShell range syntax. These dates are
enclosed in square brackets.
.Parameter HighlightDate
Specific days (named) to highlight. These dates are surrounded by asterisks.
.Example
# Show a default display of this month.
Show-Calendar
.Example
# Display a date range.
Show-Calendar -Start "March, 2010" -End "May, 2010"
.Example
# Highlight a range of days.
Show-Calendar -HighlightDay (1..10 + 22) -HighlightDate "December 25, 2008"
#>
function Show-Calendar {
param(
[DateTime] $start = [DateTime]::Today,
[DateTime] $end = $start,
$firstDayOfWeek,
[int[]] $highlightDay,
[string[]] $highlightDate = [DateTime]::Today.ToString()
)
## Determine the first day of the start and end months.
$start = New-Object DateTime $start.Year,$start.Month,1
$end = New-Object DateTime $end.Year,$end.Month,1
## Convert the highlighted dates into real dates.
[DateTime[]] $highlightDate = [DateTime[]] $highlightDate
## Retrieve the DateTimeFormat information so that the
## calendar can be manipulated.
$dateTimeFormat = (Get-Culture).DateTimeFormat
if($firstDayOfWeek)
{
$dateTimeFormat.FirstDayOfWeek = $firstDayOfWeek
}
$currentDay = $start
## Process the requested months.
while($start -le $end)
{
## Return to an earlier point in the function if the first day of the month
## is in the middle of the week.
while($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek)
{
$currentDay = $currentDay.AddDays(-1)
}
## Prepare to store information about this date range.
$currentWeek = New-Object PsObject
$dayNames = @()
$weeks = @()
## Continue processing dates until the function reaches the end of the month.
## The function continues until the week is completed with
## days from the next month.
while(($currentDay -lt $start.AddMonths(1)) -or
($currentDay.DayOfWeek -ne $dateTimeFormat.FirstDayOfWeek))
{
## Determine the day names to use to label the columns.
$dayName = "{0:ddd}" -f $currentDay
if($dayNames -notcontains $dayName)
{
$dayNames += $dayName
}
## Pad the day number for display, highlighting if necessary.
$displayDay = " {0,2} " -f $currentDay.Day
## Determine whether to highlight a specific date.
if($highlightDate)
{
$compareDate = New-Object DateTime $currentDay.Year,
$currentDay.Month,$currentDay.Day
if($highlightDate -contains $compareDate)
{
$displayDay = "*" + ("{0,2}" -f $currentDay.Day) + "*"
}
}
## Otherwise, highlight as part of a date range.
if($highlightDay -and ($highlightDay[0] -eq $currentDay.Day))
{
$displayDay = "[" + ("{0,2}" -f $currentDay.Day) + "]"
$null,$highlightDay = $highlightDay
}
## Add the day of the week and the day of the month as note properties.
$currentWeek | Add-Member NoteProperty $dayName $displayDay
## Move to the next day of the month.
$currentDay = $currentDay.AddDays(1)
## If the function reaches the next week, store the current week
## in the week list and continue.
if($currentDay.DayOfWeek -eq $dateTimeFormat.FirstDayOfWeek)
{
$weeks += $currentWeek
$currentWeek = New-Object PsObject
}
}
## Format the weeks as a table.
$calendar = $weeks | Format-Table $dayNames -auto | Out-String
## Add a centered header.
$width = ($calendar.Split("'n") | Measure-Object -Max Length).Maximum
$header = "{0:MMMM yyyy}" -f $start
$padding = " " * (($width - $header.Length) / 2)
$displayCalendar = " 'n" + $padding + $header + "'n " + $calendar
$displayCalendar.TrimEnd()
## Move to the next month.
$start = $start.AddMonths(1)
}
}
|
ZaicAdminTools.psd1
|
zaicadmintools-1.0.5
|
#
# Module manifest for module 'ZaicAdminTools'
#
# Generated by: Pawel Jarosz
#
# Generated on: 07.04.2017
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ZaicAdminTools.psm1'
# Version number of this module.
ModuleVersion = '1.0.5'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '5acc36de-e879-4b3b-b3c2-d06c65807b59'
# Author of this module
Author = 'Pawel Jarosz'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) 2017 Pawel Jarosz. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Super duper fun stuff'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = 'ZaicAdminTools.Format.ps1xml'
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('Show-Calendar')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
ZaicAdminTools.psm1
|
zaicadmintools-1.0.5
|
#Get public and private function definition files.
$Public = @( Get-ChildItem -Recurse -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue)
$Private = @( Get-ChildItem -Recurse -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue )
#Dot source the files
Foreach($import in @($Public + $Private))
{
Try
{
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
Export-ModuleMember -Function $Public.Basename
|
Get-ArchiveItem.ps1
|
ziphelper-0.2.2
|
function Get-ArchiveItem {
<#
.SYNOPSIS
Returns archive items from the archive file
.DESCRIPTION
Returns a list of archive files from the archive. Returns item contents as a byte array when specific items are provided.
.PARAMETER Path
Archive Path
.PARAMETER Item
Path to existing items inside the archive
.EXAMPLE
# Return an archive file list
Get-ArchiveItem .\asd.zip
.EXAMPLE
# Return an archive file with binary contents
Get-ArchiveItem .\asd.zip asd\file1.txt
.NOTES
General notes
#>
param ([Parameter(Mandatory)]
[string]$Path,
[string[]]$Item
)
if ($Item) {
$result = [ZipHelper]::GetArchiveItem((Resolve-Path $Path), $Item)
}
else {
$result = [ZipHelper]::GetArchiveItems((Resolve-Path $Path))
}
$result | Add-Member -MemberType AliasProperty -Name Path -Value FullName -PassThru | `
Add-Member -MemberType AliasProperty -Name Size -Value Length -PassThru
}
|
Remove-ArchiveItem.ps1
|
ziphelper-0.2.2
|
Function Remove-ArchiveItem {
<#
.SYNOPSIS
Removes one or more items from the archive
.DESCRIPTION
Remove specific file or folder from the existing archive
.PARAMETER Path
Archive path
.PARAMETER Item
Archived item: file or folder
.EXAMPLE
Remove-ArchiveItem -Path c:\temp\myarchive.zip -Item MyFile.txt, Myfile2.txt
.NOTES
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory = $true,
Position = 1)]
[string]$Path,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 2)]
[string[]]$Item
)
begin {
$itemCollection = @()
}
process {
foreach ($currentItem in $Item) {
$itemCollection += $currentItem
}
}
end {
#Open new file stream
$writeMode = [System.IO.FileMode]::Open
$stream = [FileStream]::new((Resolve-Path $Path), $writeMode)
try {
#Open zip file
$zip = [ZipArchive]::new($stream, [ZipArchiveMode]::Update)
try {
#Write files
foreach ($currentItem in $itemCollection) {
if ($e = $zip.GetEntry($currentItem)) {
$e.Delete()
}
}
}
catch { throw $_ }
finally { $zip.Dispose() }
}
catch { throw $_ }
finally { $stream.Dispose() }
}
}
|
Expand-ArchiveItem.ps1
|
ziphelper-0.2.2
|
Function Expand-ArchiveItem {
<#
.SYNOPSIS
Extracts one or more items from the archive
.DESCRIPTION
Extract specific file or folder from the existing archive
.PARAMETER Path
Archive path
.PARAMETER DestinationPath
Destination folder to put the item into
.PARAMETER Item
Archived item: file or folder
.PARAMETER PassThru
If specified, returns the unpacked item object
.PARAMETER Force
Overwrites existing file(s)
.PARAMETER Relative
Extract with relative paths based on the specified item path
.PARAMETER IgnoreFolders
Extract all files to the same folder regardless of the paths inside the archive
.EXAMPLE
Expand-ArchiveItem -Path c:\temp\myarchive.zip -DestinationPath c:\MyFolder -Item MyFile.txt, Myfile2.txt
.NOTES
General notes
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 1)]
[string]$Path,
[Parameter(Mandatory = $true,
Position = 2)]
[string]$DestinationPath,
[Parameter(Mandatory = $true,
Position = 3)]
[string[]]$Item,
[switch]$PassThru,
[switch]$Force,
[switch]$Relative,
[switch]$IgnoreFolders
)
begin {
}
process {
$archive = Get-ArchiveItem -Path $Path
foreach ($currentItem in $Item) {
#check if it's a folder
if ($archive | Where-Object { $_.Folder -eq $currentItem -or $_.Folder -like (Join-Path $currentItem *) }) {
$currentZipEntries = $archive | Where-Object Path -like (Join-Path $currentItem *)
}
else {
$currentZipEntries = $archive | Where-Object Path -like $currentItem
}
if ($Relative) {
$rootFolder = Split-Path $currentItem -Parent
}
if (!$currentZipEntries) {
Write-Warning -Message "Item $currentItem was not found in $Path"
}
foreach ($currentZipItem in $currentZipEntries) {
# get archive item
if ($IgnoreFolders) {
$itemPath = Split-Path $currentZipItem.Path -Leaf
}
elseif ($Relative) {
$itemPath = $currentZipItem.Path -replace ("^" + [Regex]::Escape($rootFolder)), ''
}
else {
$itemPath = $currentZipItem.Path
}
# check if item exists
if (Test-Path $DestinationPath) {
$destItem = Get-Item $DestinationPath
if ($destItem.PSIsContainer) {
$destFolder = $destItem.FullName
$itemDestPath = Join-Path $destItem.FullName $itemPath
}
else {
$itemDestPath = $DestinationPath
}
}
else {
$itemDestPath = Join-Path $DestinationPath $itemPath
}
if ($Force -eq $false -and (Test-Path $itemDestPath)) {
Write-Warning -Message "Destination item $itemDestPath already exists. No action performed. Use -Force to overwrite."
continue
}
# create parent directory
$parent = Split-Path $itemDestPath -Parent
if (!(Test-Path $parent)) {
if ($pscmdlet.ShouldProcess($parent, "Creating parent directory")) {
$null = New-Item -Path $parent -ItemType Directory -Force
}
}
if ($pscmdlet.ShouldProcess($currentZipItem.Path, "Extract archive item to $itemDestPath")) {
[ZipHelper]::SaveArchiveItem($Path, $currentZipItem.Path, $itemDestPath)
}
# return item object
if ($PassThru) {
Get-Item $itemDestPath
}
}
}
}
end {
}
}
|
Add-ArchiveItem.ps1
|
ziphelper-0.2.2
|
Function Add-ArchiveItem {
<#
.SYNOPSIS
Adds one or more items to the archive
.DESCRIPTION
Adds specific file or folder to the existing archive
.PARAMETER Path
Archive path
.PARAMETER Item
Archived item: file or folder
.EXAMPLE
# Put two txt files into archive.zip\inner_folder\path\
Add-ArchiveItem -Path c:\temp\myarchive.zip -Item MyFile.txt, Myfile2.txt -InnerFolder inner_folder\path
.NOTES
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory = $true,
Position = 1)]
[string]$Path,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 2)]
[string[]]$Item,
[string]$InnerFolder = '.'
# [switch]$Force,
# [switch]$Recurse
)
begin {
if (!(Test-Path $Path)) {
throw "Path not found: $Path"
}
$itemCollection = @()
}
process {
foreach ($currentItem in $Item) {
$itemCollection += Get-Item $currentItem
}
}
end {
#Open new file stream
$writeMode = [System.IO.FileMode]::Open
$stream = [FileStream]::new((Resolve-Path $Path), $writeMode)
try {
#Open zip file
$zip = [ZipArchive]::new($stream, [ZipArchiveMode]::Update)
try {
#Write files
foreach ($currentItem in $itemCollection) {
$fileName = Split-Path $currentItem -Leaf
$innerPath = (Join-Path $InnerFolder $fileName) -replace ('^' + [regex]::Escape('.\')),''
[ZipHelper]::WriteZipFile($zip, $innerPath, [ZipHelper]::GetBinaryFile($currentItem.FullName))
}
}
catch { throw $_ }
finally { $zip.Dispose() }
}
catch { throw $_ }
finally { $stream.Dispose() }
}
}
|
ZipHelper.class.ps1
|
ziphelper-0.2.2
|
using namespace System.IO
using namespace System.IO.Compression
class ZipHelper {
# Returns file contents as a binary array
static [byte[]] GetBinaryFile ([string]$fileName) {
$stream = [System.IO.File]::Open($fileName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$b = [byte[]]::new($stream.Length)
try { $stream.Read($b, 0, $b.Length) }
catch { throw $_ }
finally { $stream.Close() }
return $b
}
# Adds a new file entry into an opened ZipArchive object and fills it from the byte array
static [void] WriteZipFile ([ZipArchive]$zipFile, [string]$fileName, [byte[]]$data) {
#Remove old file entry if exists
if ($zipFile.Mode -eq [ZipArchiveMode]::Update) {
if ($oldEntry = $zipFile.GetEntry($fileName)) {
$oldEntry.Delete()
}
}
#Create new file entry
$entry = $zipFile.CreateEntry($fileName)
$writer = $entry.Open()
#Write file contents
$writer.Write($data, 0, $data.Length )
#Close the stream
$writer.Close()
}
static [psobject[]] GetArchiveItems ([string]$fileName) {
$zip = [Zipfile]::OpenRead($FileName)
try {
$entries = $zip.Entries | Select-Object *
}
catch { throw $_ }
finally { $zip.Dispose() }
return $entries | Add-Member -MemberType ScriptProperty -Name Folder -Value { Split-Path $this.FullName} -PassThru
}
# Returns a specific entry from the archive file
static [psobject[]] GetArchiveItem ([string]$fileName, [string[]]$itemName) {
$zip = [Zipfile]::OpenRead($FileName)
[psobject[]]$output = @()
try {
$entries = $zip.Entries | Where-Object { $_.FullName -in $itemName }
foreach ($entry in $entries) {
#Read deflate stream
$stream = [ZipHelper]::ReadDeflateStream($entry.Open())
try { $bin = $stream.ToArray() }
catch { throw $_ }
finally { $stream.Dispose() }
$output += $entry | Select-Object * | Add-Member -MemberType NoteProperty -Name ByteArray -Value $bin -PassThru
}
}
catch { throw $_ }
finally { $zip.Dispose() }
return $output
}
static [void] SaveArchiveItem ([string]$fileName, [string]$itemName, [string]$saveTo) {
$zip = [Zipfile]::OpenRead($fileName)
try {
$entry = $zip.Entries | Where-Object { $_.FullName -in $itemName }
#Open file stream to write
$writeStream = [System.IO.File]::Create($saveTo)
#Copy deflate stream to the write stream
$zipStream = $entry.Open()
try {
$zipStream.CopyTo($writeStream)
}
catch { throw $_ }
finally {
$zipStream.Close()
$zipStream.Dispose()
$writeStream.Close()
$writeStream.Dispose()
}
}
catch { throw $_ }
finally { $zip.Dispose() }
}
static [string] DecodeBinaryText ([byte[]]$Array) {
$skipBytes = 0
# null
if ($Array.Length -eq 0) {
return [NullString]::Value
}
# EF BB BF (UTF8)
if ($Array.Length -ge 3 -and $Array[0] -eq 0xef -and $Array[1] -eq 0xbb -and $Array[2] -eq 0xbf) {
$encoding = [System.Text.Encoding]::UTF8
$skipBytes = 3
}
# 00 00 FE FF (UTF32 Big-Endian)
elseif ($Array.Length -ge 4 -and $Array[0] -eq 0 -and $Array[1] -eq 0 -and $Array[2] -eq 0xfe -and $Array[3] -eq 0xff) {
$encoding = [System.Text.Encoding]::UTF32
$skipBytes = 4
}
# FF FE 00 00 (UTF32 Little-Endian)
elseif ($Array.Length -ge 4 -and $Array[0] -eq 0xff -and $Array[1] -eq 0xfe -and $Array[2] -eq 0 -and $Array[3] -eq 0) {
$encoding = [System.Text.Encoding]::UTF32
$skipBytes = 4
}
# FE FF (UTF-16 Big-Endian)
elseif ($Array.Length -ge 2 -and $Array[0] -eq 0xfe -and $Array[1] -eq 0xff) {
$encoding = [System.Text.Encoding]::BigEndianUnicode
$skipBytes = 2
}
# FF FE (UTF-16 Little-Endian)
elseif ($Array.Length -ge 2 -and $Array[0] -eq 0xff -and $Array[1] -eq 0xfe) {
$encoding = [System.Text.Encoding]::Unicode
$skipBytes = 2
}
elseif ($Array.Length -ge 4 -and $Array[0] -eq 0x2b -and $Array[1] -eq 0x2f -and $Array[2] -eq 0x76 -and ($Array[3] -eq 0x38 -or $Array[3] -eq 0x39 -or $Array[3] -eq 0x2b -or $Array[3] -eq 0x2f)) {
$encoding = [System.Text.Encoding]::UTF7
}
else {
$encoding = [System.Text.Encoding]::ASCII
}
return $encoding.GetString($Array, $skipBytes, $Array.Length - $skipBytes)
}
static [System.IO.MemoryStream] ReadDeflateStream ([Stream]$stream) {
$memStream = [System.IO.MemoryStream]::new()
$stream.CopyTo($memStream)
$stream.Close()
return $memStream
}
}
|
ziphelper.psm1
|
ziphelper-0.2.2
|
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
foreach ($class in (Get-Item $PSScriptRoot\classes\*.ps1)) {
. $class.FullName
}
foreach ($function in (Get-Item $PSScriptRoot\functions\*.ps1)) {
. $function.FullName
}
|
ziphelper.psd1
|
ziphelper-0.2.2
|
@{
# Script module or binary module file associated with this manifest
RootModule = 'ziphelper.psm1'
# Version number of this module.
ModuleVersion = '0.2.2'
# ID used to uniquely identify this module
GUID = '97dac4a3-82a1-42e0-aec4-1aee66797120'
# Author of this module
Author = 'Kirill Kravtsov'
# Company or vendor of this module
CompanyName = ''
# Copyright statement for this module
Copyright = 'Kirill Kravtsov (@nvarscar) 2018. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Tools to work with zip archives'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = '3.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = '2.0.50727'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'None'
# Modules that must be imported into the global environment prior to importing
# this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to
# importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in
# ModuleToProcess
NestedModules = @()
# Functions to export from this module
FunctionsToExport = @(
'Add-ArchiveItem',
'Expand-ArchiveItem',
'Get-ArchiveItem',
'Remove-ArchiveItem'
)
# Cmdlets to export from this module
CmdletsToExport = ''
# Variables to export from this module
VariablesToExport = ''
# Aliases to export from this module
AliasesToExport = '' #For performanace, list alias explicity
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
#Support for PowerShellGet galleries.
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('Zip','Archive','Deflate','Unzip')
# A URL to the license for this module.
LicenseUri = 'https://github.com/nvarscar/psziphelper/blob/master/license.txt'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/nvarscar/psziphelper'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
}
|
ZorkOut.ps1
|
zorkify-0.0.1
|
$Results = @{
Success = @(
'Very good. Now you can go to the second grade.',
'Wheeeeeee!!!!!',
'Do you expect me to applaud?'
'Naturally!'
)
Warning = @(
'It is pitch black. You are likely to be eaten by a Grue.',
"You are in a maze of twisty passages, all alike.",
'Your sword is glowing with a faint blue glow.'
)
NonTermError = @(
"A hollow voice says 'Fool.'",
'The mountains are impassable.',
'If you pray enough, your prayers may be answered.',
'Such language in a high-class establishment like this!'
)
TermError = @(
'Oh, no! You have walked into the slavering fangs of a lurking grue!',
'Aaaarrrrgggghhhh!'
)
}
|
deploy.psdeploy.ps1
|
zorkify-0.0.1
|
# Generic module deployment.
#
# ASSUMPTIONS:
#
# * folder structure either like:
#
# - RepoFolder
# - This PSDeploy file
# - ModuleName
# - ModuleName.psd1
#
# OR the less preferable:
# - RepoFolder
# - RepoFolder.psd1
#
# * Nuget key in $ENV:NugetApiKey
#
# * Set-BuildEnvironment from BuildHelpers module has populated ENV:BHPSModulePath and related variables
# Publish to gallery with a few restrictions
if(
$env:BHPSModulePath -and
$env:BHBuildSystem -ne 'Unknown' -and
$env:BHBranchName -eq "master" -and
$env:BHCommitMessage -match '!deploy'
)
{
Deploy Module {
By PSGalleryModule {
FromSource $ENV:BHPSModulePath
To PSGallery
WithOptions @{
ApiKey = $ENV:NugetApiKey
}
}
}
}
else
{
"Skipping deployment: To deploy, ensure that...`n" +
"`t* You are in a known build system (Current: $ENV:BHBuildSystem)`n" +
"`t* You are committing to the master branch (Current: $ENV:BHBranchName) `n" +
"`t* Your commit message includes !deploy (Current: $ENV:BHCommitMessage)" |
Write-Host
}
# Publish to AppVeyor if we're in AppVeyor
if(
$env:BHPSModulePath -and
$env:BHBuildSystem -eq 'AppVeyor'
)
{
Deploy DeveloperBuild {
By AppVeyorModule {
FromSource $ENV:BHPSModulePath
To AppVeyor
WithOptions @{
Version = $env:APPVEYOR_BUILD_VERSION
}
}
}
}
|
Zorkify.psm1
|
zorkify-0.0.1
|
$FunctionList = Get-ChildItem -Path $PSScriptRoot\Functions
foreach ($Function in $FunctionList) {
Write-Verbose -Message ('Importing function file: {0}' -f $Function.FullName)
. $Function.FullName
}
|
psake.ps1
|
zorkify-0.0.1
|
# PSake makes variables declared here available in other scriptblocks
# Init some things
Properties {
# Find the build folder based on build system
$ProjectRoot = $ENV:BHProjectPath
if(-not $ProjectRoot)
{
$ProjectRoot = $PSScriptRoot
}
$Timestamp = Get-date -uformat "%Y%m%d-%H%M%S"
$PSVersion = $PSVersionTable.PSVersion.Major
$TestFile = "TestResults_PS$PSVersion`_$TimeStamp.xml"
$lines = '----------------------------------------------------------------------'
$Verbose = @{}
if($ENV:BHCommitMessage -match "!verbose")
{
$Verbose = @{Verbose = $True}
}
}
Task Default -Depends Deploy
Task Init {
$lines
Set-Location $ProjectRoot
"Build System Details:"
Get-Item ENV:BH*
"`n"
}
Task Test -Depends Init {
$lines
"`n`tSTATUS: Testing with PowerShell $PSVersion"
# Gather test results. Store them in a variable and file
$TestResults = Invoke-Pester -Path $ProjectRoot\Tests -PassThru -OutputFormat NUnitXml -OutputFile "$ProjectRoot\$TestFile"
# In Appveyor? Upload our tests! #Abstract this into a function?
If($ENV:BHBuildSystem -eq 'AppVeyor')
{
(New-Object 'System.Net.WebClient').UploadFile(
"https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)",
"$ProjectRoot\$TestFile" )
}
Remove-Item "$ProjectRoot\$TestFile" -Force -ErrorAction SilentlyContinue
# Failed tests?
# Need to tell psake or it will proceed to the deployment. Danger!
if($TestResults.FailedCount -gt 0)
{
Write-Error "Failed '$($TestResults.FailedCount)' tests, build failed"
}
"`n"
}
Task Build -Depends Test {
$lines
# Bump the module version
Try
{
$Version = Get-NextPSGalleryVersion -Name $env:BHProjectName -ErrorAction Stop
Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value $Version -ErrorAction stop
}
Catch
{
"Failed to update version for '$env:BHProjectName': $_.`nContinuing with existing version"
}
}
Task Deploy -Depends Build {
$lines
$Params = @{
Path = $ProjectRoot
Force = $true
Recurse = $false # We keep psdeploy artifacts, avoid deploying those : )
}
Invoke-PSDeploy @Verbose @Params
}
|
build.ps1
|
zorkify-0.0.1
|
function Resolve-Module {
[Cmdletbinding()]
param(
[Parameter(Mandatory)]
[string[]]$Name
)
Process {
foreach ($ModuleName in $Name) {
$Module = Get-Module -Name $ModuleName -ListAvailable
Write-Verbose -Message "Resolving Module $($ModuleName)"
if ($Module) {
$Version = $Module | Measure-Object -Property Version -Maximum | Select-Object -ExpandProperty Maximum
$GalleryVersion = Find-Module -Name $ModuleName -Repository PSGallery | Measure-Object -Property Version -Maximum | Select-Object -ExpandProperty Maximum
if ($Version -lt $GalleryVersion) {
if ((Get-PSRepository -Name PSGallery).InstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
}
Write-Verbose -Message "$($ModuleName) Installed Version [$($Version.tostring())] is outdated. Installing Gallery Version [$($GalleryVersion.tostring())]"
Install-Module -Name $ModuleName -Force
Import-Module -Name $ModuleName -Force -RequiredVersion $GalleryVersion
} else {
Write-Verbose -Message "Module Installed, Importing $($ModuleName)"
Import-Module -Name $ModuleName -Force -RequiredVersion $Version
}
} else {
Write-Verbose -Message "$($ModuleName) Missing, installing Module"
Install-Module -Name $ModuleName -Force
Import-Module -Name $ModuleName -Force -RequiredVersion $Version
}
}
}
}
# Grab nuget bits, install modules, set build variables, start build.
Get-PackageProvider -Name NuGet -ForceBootstrap | Out-Null
Resolve-Module Psake, PSDeploy, Pester, BuildHelpers
Invoke-psake .\psake.ps1
exit ( [int]( -not $psake.build_success ) )
|
Zorkify.psd1
|
zorkify-0.0.1
|
#
# Module manifest for module 'Zorkify'
#
# Generated by: Joshua Barton
#
# Generated on: 11/14/2016
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'Zorkify.psm1'
# Version number of this module.
ModuleVersion = '0.0.1'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '20d7c38f-03b8-4a9b-b813-07daea6a61e4'
# Author of this module
Author = 'Joshua Barton'
# Company or vendor of this module
CompanyName = 'None'
# Copyright statement for this module
Copyright = '(c) 2016 Joshua Barton. All rights reserved.'
# Description of the functionality provided by this module
Description = 'A goofy script to return Zork quotes instead of actual errors or warnings'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
ScriptsToProcess = @('Scripts\ZorkOut.ps1')
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Zorkify'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Zorkify.Tests.ps1
|
zorkify-0.0.1
|
if(-not $ENV:BHProjectPath){
Set-BuildEnvironment -Path $PSScriptRoot\..
}
Remove-Module $ENV:BHProjectName -ErrorAction SilentlyContinue
Import-Module (Join-Path $ENV:BHProjectPath $ENV:BHProjectName) -Force
Describe -Name 'Zorkify' {
Context -Name 'Output Script ZorkOut.ps1' {
$ScriptPath = Join-Path -Path $ENV:BHProjectPath -ChildPath 'Scripts\ZorkOut.ps1'
It 'Should exist' {
$ScriptPath | Should Exist
}
# Source ZorkOut.ps1
. $ScriptPath
It 'Should be formatted correctly' {
$Results.Keys.Count | Should Be 4
$Results.Keys | Should Match 'Success|Warning|NonTermError|TermError'
$Results.Success | Should Not BeNullOrEmpty
$Results.Warning | Should Not BeNullOrEmpty
$Results.NonTermError | Should Not BeNullOrEmpty
$Results.TermError | Should Not BeNullOrEmpty
}
}
}
|
Zorkify.ps1
|
zorkify-0.0.1
|
function Zorkify () {
<#
.SYNOPSIS
A goofy script to return Zork quotes instead of actual errors or warnings
.DESCRIPTION
A goofy script to return Zork quotes instead of actual errors or warnings
.PARAMETER Command
Command/Script to run. Implemented with Invoke-Expression
.INPUTS
None
.OUTPUTS
$OutputFile
.NOTES
Version: 1.0
Author: Joshua Barton (@foobartn)
Creation Date: 11.14.2016
Purpose/Change: Initial script development
.EXAMPLE
Successful command
Zorkify -Command 'Get-Process'
.EXAMPLE
Command with Write-Error output
Zorkify -Command 'Write-Error "Nope"'
.EXAMPLE
Command with Write-Warning output
Zorkify -Command 'Write-Warning "Nope"'
.EXAMPLE
Command with Throw output
Zorkify -Command 'Throw "Nope"'
#>
param (
[parameter(Mandatory=$true)]
[string]$Command
)
try {
$CommandParams = @{
Command = $Command
ErrorVariable = 'CommandErrors'
WarningVariable = 'CommandWarnings'
}
$CommandData = Invoke-Expression @CommandParams 2>$null 3>$null
foreach ($CommandError in $CommandErrors) {
$NonTermErrorMsg = $Results.NonTermError | Get-Random
Write-Error $NonTermErrorMsg
}
foreach ($CommandWarning in $CommandWarnings) {
$WarningMsg = $Results.Warning | Get-Random
Write-Warning $WarningMsg
}
$CommandData
if (
$CommandErrors.Count -eq 0 -and
$CommandWarnings.Count -eq 0
) {
$SuccessMsg = $Results.Success | Get-Random
Write-Host "
$SuccessMsg" -ForegroundColor Green
}
} catch {
$TermErrorMsg = $Results.TermError | Get-Random
Throw $TermErrorMsg
}
}
|
zxsh-functions.ps1
|
zxsh-0.0.8
|
<#
.Description
This script defines the functions that are integrated in the usage of zxsh.
Declared functions:
1. Set-Title
2. Prompt
3. Get-EmptyFolders
4. Reset-Color
5. Get-IntegrityHash
#>
<#
.SYNOPSIS
Set-Title
.DESCRIPTION
Set title of console Window
.PARAMETER $args
Set title of console Window to $args
.EXAMPLE
# Set title of console Window to 'ps7'
Title ps7
#>
Function Set-Title {
(Get-Host).UI.RawUI.WindowTitle = $args
}
<#
.SYNOPSIS
Prompt
.DESCRIPTION
Defines the prompt in zxsh; Used internally.
#>
Function Prompt {
$current_path = (Get-Location).Path
$last_command = (Get-History -Count 1)
if ((($null -ne $last_command) -And ($last_command.CommandLine.Trim().ToLowerInvariant() -match "git\s+checkout\s+.+")) -Or ($Script:PrevPwd -ne $current_path))
{
$Script:BranchName = $(git branch --show-current)
$Script:GitBranchExitCode = $LASTEXITCODE
$Script:PrevPwd = $current_path
}
"`e[32m$env:USERDOMAIN>$env:USERNAME`e[39m $PWD $(if ($Script:GitBranchExitCode -eq 0) { "`e[36m($Script:BranchName)`e[39m" })`nPS> "
}
<#
.SYNOPSIS
Get-EmptyFolders
.DESCRIPTION
List all empty folders in a given path recursively.
.EXAMPLE
# Recursively list all empty folders starting from current folder
Get-EmptyFolders
.EXAMPLE
# Recursively list all empty folders starting from stated folder C:\temp
Get-EmptyFolders C:\temp
#>
Function Get-EmptyFolders {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidDefaultValueSwitchParameter', Scope='Function', Target='Recurse',
Justification='We intentionally want this to be the default behaviour')]
[CmdletBinding()]
param (
[Parameter()]
[string] $Path = ".",
[Parameter()]
[switch] $Recurse = $true
)
Get-ChildItem -Path $Path -Directory -Recurse:$Recurse | Where-Object { ($_.GetFiles().Count -eq 0) -and ($_.GetDirectories().Count -eq 0) } | Sort-Object { $_.FullName } | Select-Object FullName
}
<#
.SYNOPSIS
Reset-Color
.DESCRIPTION
Reset the color of the console to default
.EXAMPLE
# Reset the color of the console to default
Reset-Color
#>
Function Reset-Color {
[Console]::ResetColor()
}
<#
.SYNOPSIS
Get-IntegrityHash
.DESCRIPTION
Get the integrity hash for URL
.EXAMPLE
# Get SHA256 (default) hash for integrity attribute
Get-IntegrityHash "https://unpkg.com/react@17/umd/react.development.js"
# Get SHA384 hash for integrity attribute
Get-IntegrityHash "https://unpkg.com/react@17/umd/react.development.js" "sha384"
#>
function Get-IntegrityHash {
param (
[string] $url="",
[string] $hash="sha256"
)
switch ($hash.ToLowerInvariant())
{
"sha1" {
try {
$result = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA1]::Create().ComputeHash(
[System.Net.WebClient]::new().DownloadData($url)
)
)
}
catch {
Write-Error $_
}
}
"sha256" {
try {
$result = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA256]::Create().ComputeHash(
[System.Net.WebClient]::new().DownloadData($url)
)
)
}
catch {
Write-Error $_
}
}
"sha384" {
try {
$result = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA384]::Create().ComputeHash(
[System.Net.WebClient]::new().DownloadData($url)
)
)
}
catch {
Write-Error $_
}
}
"sha512" {
try {
$result = [Convert]::ToBase64String(
[System.Security.Cryptography.SHA512]::Create().ComputeHash(
[System.Net.WebClient]::new().DownloadData($url)
)
)
}
catch {
Write-Error $_
}
}
default {
throw "Invalid $hash"
}
}
Write-Host "$hash-$result"
}
<#
.SYNOPSIS
ConvertTo-IntId
.DESCRIPTION
Compute a string into an integer
.EXAMPLE
# Compute a string "MiniTools.Web.Controllers.LoginController" into an integer
ConvertTo-IntId MiniTools.Web.Controllers.LoginController
#>
Function ConvertTo-IntId {
param (
[string] $text=""
)
if ($text.Length -eq 0) {
Write-Host "Usage: ConvertTo-IntId 'MiniTools.Web.Controllers.LoginController' (Should yield result 251394) "
return
}
$w,$s=0; [System.Security.Cryptography.SHA1CryptoServiceProvider]::new().ComputeHash([Text.Encoding]::UTF8.GetBytes($text)).ForEach({$_*++$w}).ForEach({$s+=$_});"$s$($s%11)"
}
function Test-IsAdmin {
if (-not $IsWindows) {
return $false
}
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
return $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
|
zxsh.psm1
|
zxsh-0.0.8
|
<#
.Description
Main (basic) module
Sections:
1. Script variable(s) declaration
2. Script variable(s) initialization
3. Source function(s)
4. Define alias(es)
5. Module member export definitions
#>
########################################
# 1. Script variable(s) declaration
$Script:PrevPwd = $null
$Script:BranchName = $null
$Script:GitBranchExitCode = $null
########################################
# 2. Script variable(s) initialization
$Script:profilePath = [System.IO.Path]::GetDirectoryName($PROFILE)
if ($false -eq [System.IO.Directory]::Exists($Script:profilePath))
{
New-Item $Script:profilePath -ItemType Directory
}
########################################
# 3. Source function(s)
# zxsh-functions.ps1
# 1. Set-Title
# 2. Prompt
. (Join-Path $PSScriptRoot zxsh-functions.ps1)
########################################
# 4. Define alias(es)
if ($null -eq (Get-Alias | Where-Object { $_.Name -like 'title' })) {
New-Alias -Name title -Value Set-Title
}
if ($null -eq (Get-Alias | Where-Object { $_.Name -like 'isadmin' })) {
New-Alias -Name isadmin -Value Test-IsAdmin
}
########################################
# 5. Module member export definitions
# Functions
Export-ModuleMember -Function Set-Title, Prompt, Get-EmptyFolders, Reset-Color, Get-IntegrityHash, ConvertTo-IntId, Test-IsAdmin
# Aliases
Export-ModuleMember -Alias title, isadmin
|
zxsh.psd1
|
zxsh-0.0.8
|
#
# Module manifest for module 'zxsh'
#
# Generated by: Ong Zhi XIan
#
# Generated on: 2020-04-27
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'zxsh'
# Version number of this module.
ModuleVersion = '0.0.8'
# Supported PSEditions
CompatiblePSEditions = @("Core")
# ID used to uniquely identify this module
GUID = '327e4ed4-8f3f-4e89-91c6-f84cf4dffa14'
# Author of this module
Author = 'Ong Zhi Xian'
# Company or vendor of this module
CompanyName = 'Ong Zhi Xian'
# Copyright statement for this module
Copyright = '(c) Ong Zhi Xian. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Personalised PowerShell Core Shell'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '7.0'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @("Set-Title", "Prompt", "Get-EmptyFolders", "Reset-Color", "Get-IntegrityHash", "ConvertTo-IntId", "Test-IsAdmin")
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @("title", "isadmin")
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
FileList = @('zxsh.psm1', 'zxsh-functions.ps1')
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('shell')
# A URL to the license for this module.
LicenseUri = 'https://github.com/ongzhixian/pwsh-zxsh/blob/master/LICENSE'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/ongzhixian/pwsh-zxsh'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'https://github.com/ongzhixian/pwsh-zxsh/wiki/01-Release-Notes'
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://github.com/ongzhixian/pwsh-zxsh/wiki'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.