powershell 有用的PS One Liners
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 有用的PS One Liners相关的知识,希望对你有一定的参考价值。
$downloadlink=' '
filename='$home\filename.exe'
(new-object net.webclient).DownloadFile("$downloadlink",$filename)
$downloadlink=' '
Start-BitsTransfer "$downloadlink" -Destination $Home
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/0fcd76d0761e565a8c4e/e62a66f046a5c4645ad5/start-cleanup'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/9ec120fe226da56cf43d/c32ef66cd8c7f6618f17/tivoli-log.ps1'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/c0cd27f2f899eee313b1/67d1893a0a361386d380/compress-winsxs.ps1'))
#loads as function so to call it
compress-winsxs
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/f0927e54b168e87b02c7/06b4f9b8d093a51b5bdb/Check-SSL.ps1'))
#This is a GUI for robocopy
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/730edfba75a5da59daf8/8c8f438dd1cf63a621b3/PowerCopyLite.ps1'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/9614b4b4a805aee8f8dc/eb8e7f145698b4ede26d/SQLOptimizer.ps1'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/ff11e689412a7f1858bb/288b6eacf63de841e5a5/Get-LocalUser.ps1'))
get-localuser
#This shows free drive space on all drivers inluding network drivers.
Get-PSDrive | Where {$_.Free -gt 0}
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host Check for IPV6 on NICS
Get-NetAdapterBinding -ComponentID ms_tcpip6
write-host Windows Firewall Stats
netsh advfirewall show allprofiles
Write-Host IPv4 IP Stats
netsh interface ipv4 show ipstats
Write-Host IPv4 TCP Stats
netsh interface ipv4 show tcpstats
Write-Host IPv6 IP Stats
netsh interface ipv6 show ipstats
Write-Host IPv6 TCP Stats
netsh interface ipv6 show tcpstats
$CheckFreeSpace = {Get-Counter -Counter "\LogicalDisk(_Total)\% Free Space" -MaxSamples 360 -SampleInterval 60 | Export-Counter -Path C:\CheckFreeSpace.csv -FileFormat CSV}
$MyTrigger = New-JobTrigger -Daily -At 1am
Register-ScheduledJob -Name "Check Free Space" -Trigger $MyTrigger -ScriptBlock $CheckFreeSpace
$CtrList = @(
"\System\Processor Queue Length",
"\Memory\Pages/sec",
"\Memory\Available MBytes",
"\Processor(*)\% Processor Time",
"\Network Interface(*)\Bytes Received/sec",
"\Network Interface(*)\Bytes Sent/sec",
"\LogicalDisk(C:)\% Free Space",
"\LogicalDisk(*)\Avg. Disk Queue Length"
)
Get-Counter -Counter $CtrList -SampleInterval 5 -MaxSamples 5 | Export-Counter -Path C:\temp\PerfExample.blg -FileFormat BLG -Force
# We need two objects
$MyDataCollection = New-Object System.Diagnostics.CounterCreationDataCollection
$MyFirstData = New-Object System.Diagnostics.CounterCreationData
# Variables for Counter Creation Data linked to $MyDataCollection
$MyFirstData.CounterName = "My-Custom-CounterName"
$MyFirstData.CounterType = "NumberOfItems32"
$MyFirstData.CounterHelp = "My first custom counter"
$MyDataCollection.Add($MyFirstData)
# Variables for Performance Counter Category
$CatName = "My-Custom-Category"
$CatHelp = "A Custom Performance object"
$CatType = [System.Diagnostics.PerformanceCounterCategoryType]::MultiInstance
# Create performance counter category linked to $MyDataCollection
[System.Diagnostics.PerformanceCounterCategory]::Create($CatName, $CatHelp, $CatType, $MyDataCollection)
# Create my first counter with a counter name + instance name and if it's read-only or not?
$Counter1 = New-Object System.Diagnostics.PerformanceCounter($CatName, "My-Custom-CounterName", "My-Custom-Instance", $false)
# Set a value
$Counter1.RawValue = 1024
# Check if "My-Custom-Category" exist ?
(get-counter -listset "My-Custom-Category").paths
# Now check the CookedValue
Get-Counter -Counter "\My-Custom-Category(*)\My-Custom-CounterName" | Select-Object -ExpandProperty CounterSamples
# And just check all the properties
$counter1
## later do this
[System.Diagnostics.PerformanceCounterCategory]::Delete("$CatName")
### CSS style
$css= "<style>"
$css= $css+ "BODY{ text-align: center; background-color:white;}"
$css= $css+ "TABLE{ font-family: 'Lucida Sans Unicode', 'Lucida Grande', Sans-Serif;font-size: 12px;margin: 10px;width: 100%;text-align: center;border-collapse: collapse;border-top: 7px solid #004466;border-bottom: 7px solid #004466;}"
$css= $css+ "TH{font-size: 13px;font-weight: normal;padding: 1px;background: #cceeff;border-right: 1px solid #004466;border-left: 1px solid #004466;color: #004466;}"
$css= $css+ "TD{padding: 1px;background: #e5f7ff;border-right: 1px solid #004466;border-left: 1px solid #004466;color: #669;hover:black;}"
$css= $css+ "TD:hover{ background-color:#004466;}"
$css= $css+ "</style>"
New-Item -ItemType Directory -Force -Path C:\temp
$StartDate = (get-date).adddays(-1)
$body = Get-WinEvent -FilterHashtable @{logname="Application"; starttime=$StartDate} -ErrorAction SilentlyContinue
$body | ConvertTo-HTML -Head $css MachineName,ID,TimeCreated,Message > C:\temp\LogAppView.html
invoke-item 'C:\temp\LogAppView.html'
<#
.DESCRIPTION
Outputs the SSL protocols that the client is able to successfully use to connect to a server.
.NOTES
Copyright 2014 Chris Duck
http://blog.whatsupduck.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.PARAMETER ComputerName
The name of the remote computer to connect to.
.PARAMETER Port
The remote port to connect to. The default is 443.
.EXAMPLE
Test-SslProtocols -ComputerName "www.google.com"
ComputerName : www.google.com
Port : 443
KeyLength : 2048
SignatureAlgorithm : rsa-sha1
Ssl2 : False
Ssl3 : True
Tls : True
Tls11 : True
Tls12 : True
#>
function Test-SslProtocols {
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Port = 443
)
begin {
$ProtocolNames = [System.Security.Authentication.SslProtocols] | gm -static -MemberType Property | ?{$_.Name -notin @("Default","None")} | %{$_.Name}
}
process {
$ProtocolStatus = [Ordered]@{}
$ProtocolStatus.Add("ComputerName", $ComputerName)
$ProtocolStatus.Add("Port", $Port)
$ProtocolStatus.Add("KeyLength", $null)
$ProtocolStatus.Add("SignatureAlgorithm", $null)
$ProtocolNames | %{
$ProtocolName = $_
$Socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$Socket.Connect($ComputerName, $Port)
try {
$NetStream = New-Object System.Net.Sockets.NetworkStream($Socket, $true)
$SslStream = New-Object System.Net.Security.SslStream($NetStream, $true)
$SslStream.AuthenticateAsClient($ComputerName, $null, $ProtocolName, $false )
$RemoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$SslStream.RemoteCertificate
$ProtocolStatus["KeyLength"] = $RemoteCertificate.PublicKey.Key.KeySize
$ProtocolStatus["SignatureAlgorithm"] = $RemoteCertificate.SignatureAlgorithm.FriendlyName
$ProtocolStatus["Certificate"] = $RemoteCertificate
$ProtocolStatus.Add($ProtocolName, $true)
} catch {
$ProtocolStatus.Add($ProtocolName, $false)
} finally {
$SslStream.Close()
}
}
[PSCustomObject]$ProtocolStatus
}
}
Test-SslProtocols
# Export Past incidents from Cherwell to .csv file and save them somewhere like c:\temp
# and then run this to search their title field (subject) line.
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/55db71dddfa567b0fe93/00e007d5c75b0ce2b9ce/icls-funct.ps1'))
#Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/c412642d82f6c7dd82d6/f918f95475fffd3eb775/Get-NetworkStatistics.PSD1'))
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.PARAMETER AddressFamily
Filter by IP Address family: IPv4, IPv6, or the default, * (both).
If specified, we display any result where both the localaddress and the remoteaddress is in the address family.
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Computername Computer1, Computer2
.EXAMPLE
'Computer1', 'Computer2' | Get-NetworkStatistics
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.github.io/
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$ProcessName='*',
[Parameter(Position=1)]
[System.String]$Address='*',
[Parameter(Position=2)]
$Port='*',
[Parameter(Position=3,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True)]
[System.String[]]$ComputerName=$env:COMPUTERNAME,
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$TempFile = "C:\netstat.txt",
[validateset('*','IPv4','IPv6')]
[string]$AddressFamily = '*'
)
begin{
#Define properties
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#store hostnames in array for quick lookup
$dnsCache = @{}
}
process{
foreach($Computer in $ComputerName) {
#Collect processes
if($ShowProcessNames){
Try {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $Computer. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#Handle remote systems
if($Computer -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$Computer", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $Computer to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $Computer -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $Computer converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#Filter IPv4/IPv6 if specified
if($AddressFamily -ne "*")
{
if($AddressFamily -eq 'IPv4' -and $localAddress -match ':' -and $remoteAddress -match ':|\*' )
{
#Both are IPv6, or ipv6 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
elseif($AddressFamily -eq 'IPv6' -and $localAddress -notmatch ':' -and ( $remoteAddress -notmatch ':' -or $remoteAddress -match '*' ) )
{
#Both are IPv4, or ipv4 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Filter the object
if($remotePort -notlike $Port -and $localPort -notlike $Port){
write-verbose "remote $Remoteport local $localport port $port"
Write-Verbose "Filtered by Port:`n$result"
continue
}
if($remoteAddress -notlike $Address -and $localAddress -notlike $Address){
Write-Verbose "Filtered by Address:`n$result"
continue
}
if($status -notlike $State){
Write-Verbose "Filtered by State:`n$result"
continue
}
if($proto -notlike $Protocol){
Write-Verbose "Filtered by Protocol:`n$result"
continue
}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames -or $PSBoundParameters.ContainsKey -eq 'ProcessName'){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | Where {$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
if($procName -notlike $ProcessName){
Write-Verbose "Filtered by ProcessName:`n$result"
continue
}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $Computer
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if ($dnsCache.containskey( $remoteAddress)) {
$remoteAddress = $dnsCache[$remoteAddress]
write-verbose "using cached REMOTE '$remoteAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache.add($tmpAddress, $remoteAddress)
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $Computer
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($dnsCache.containskey($localAddress)){
$localAddress = $dnsCache[$localAddress]
write-verbose "using cached LOCAL '$localAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache.add($localAddress, $tmpAddress)
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Write the object
New-Object -TypeName PSObject -Property @{
ComputerName = $Computer
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Increment the progress counter
$count++
}
}
}
}
}
Get-NetworkStatistics -State LISTENING -Protocol tcp -ProcessName * | Format-Table
Get-NetworkStatistics -State Established -Protocol tcp -ProcessName * -ShowHostnames | Format-Table
Function Get-LocalUser {
[Cmdletbinding()]
Param(
[Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[String[]]$Computername = $Env:Computername
)
Begin {
#region Helper Functions
Function ConvertTo-SID {
Param([byte[]]$BinarySID)
(New-Object System.Security.Principal.SecurityIdentifier($BinarySID,0)).Value
}
Function Convert-UserFlag {
Param ($UserFlag)
$List = New-Object System.Collections.ArrayList
Switch ($UserFlag) {
($UserFlag -BOR 0x0001) {[void]$List.Add('SCRIPT')}
($UserFlag -BOR 0x0002) {[void]$List.Add('ACCOUNTDISABLE')}
($UserFlag -BOR 0x0008) {[void]$List.Add('HOMEDIR_REQUIRED')}
($UserFlag -BOR 0x0010) {[void]$List.Add('LOCKOUT')}
($UserFlag -BOR 0x0020) {[void]$List.Add('PASSWD_NOTREQD')}
($UserFlag -BOR 0x0040) {[void]$List.Add('PASSWD_CANT_CHANGE')}
($UserFlag -BOR 0x0080) {[void]$List.Add('ENCRYPTED_TEXT_PWD_ALLOWED')}
($UserFlag -BOR 0x0100) {[void]$List.Add('TEMP_DUPLICATE_ACCOUNT')}
($UserFlag -BOR 0x0200) {[void]$List.Add('NORMAL_ACCOUNT')}
($UserFlag -BOR 0x0800) {[void]$List.Add('INTERDOMAIN_TRUST_ACCOUNT')}
($UserFlag -BOR 0x1000) {[void]$List.Add('WORKSTATION_TRUST_ACCOUNT')}
($UserFlag -BOR 0x2000) {[void]$List.Add('SERVER_TRUST_ACCOUNT')}
($UserFlag -BOR 0x10000) {[void]$List.Add('DONT_EXPIRE_PASSWORD')}
($UserFlag -BOR 0x20000) {[void]$List.Add('MNS_LOGON_ACCOUNT')}
($UserFlag -BOR 0x40000) {[void]$List.Add('SMARTCARD_REQUIRED')}
($UserFlag -BOR 0x80000) {[void]$List.Add('TRUSTED_FOR_DELEGATION')}
($UserFlag -BOR 0x100000) {[void]$List.Add('NOT_DELEGATED')}
($UserFlag -BOR 0x200000) {[void]$List.Add('USE_DES_KEY_ONLY')}
($UserFlag -BOR 0x400000) {[void]$List.Add('DONT_REQ_PREAUTH')}
($UserFlag -BOR 0x800000) {[void]$List.Add('PASSWORD_EXPIRED')}
($UserFlag -BOR 0x1000000) {[void]$List.Add('TRUSTED_TO_AUTH_FOR_DELEGATION')}
($UserFlag -BOR 0x04000000) {[void]$List.Add('PARTIAL_SECRETS_ACCOUNT')}
}
$List -join ', '
}
#endregion Helper Functions
}
Process {
ForEach ($Computer in $Computername) {
$adsi = [ADSI]"WinNT://$Computername"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | ForEach {
[pscustomobject]@{
UserName = $_.Name[0]
SID = ConvertTo-SID -BinarySID $_.ObjectSID[0]
PasswordAge = [math]::Round($_.PasswordAge[0]/86400)
LastLogin = If ($_.LastLogin[0] -is [datetime]){$_.LastLogin[0]}Else{'Never logged on'}
UserFlags = Convert-UserFlag -UserFlag $_.UserFlags[0]
MinPasswordLength = $_.MinPasswordLength[0]
MinPasswordAge = [math]::Round($_.MinPasswordAge[0]/86400)
MaxPasswordAge = [math]::Round($_.MaxPasswordAge[0]/86400)
BadPasswordAttempts = $_.BadPasswordAttempts[0]
MaxBadPasswords = $_.MaxBadPasswordsAllowed[0]
}
}
}
}
}
$TotalCounter = Get-Counter -ListSet *
$totalcounter | get-member
$TotalCounter.count
$totalcounter.counter.count
#and if you want to see them all just do
$totalcounter.counter
209.35.110.8 vcenter.support.cogecopeer1.local
209.35.110.4 vhost01.support.cogecopeer1.local
209.35.110.5 vhost02.support.cogecopeer1.local
209.35.110.6 vhost03.support.cogecopeer1.local
209.35.110.7 vhost04.support.cogecopeer1.local
209.35.110.196 ce-jumpbox.support.cogecopeer1.local
tnc example.com -port 21
$name = 'corp'
#Test-Connection $name -count 1 | select @{Name="Computername";Expression={$_.Address}},Ipv4Address
Resolve-DNSName -Name $name -type A | Select Name,IPAddress
Get-VMHost | Foreach {
Start-VMHostService -HostService ($_ | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} )
}
#We can also list all of our hosts and see if the service is running using the following one-liner:
Get-VMHost | Get-VMHostService | Where { $_.Key -eq "TSM-SSH" } |select VMHost, Label, Running
Get-VM | Select Name, @{N="IP Address";E={@($_.guest.IPAddress[0])}}
https://github.com/Sycnex/Windows10Debloater
https://github.com/W4RH4WK/Debloat-Windows-10/archive/master.zip
$AppsList = ‘Microsoft.3DBuilder’,
‘Microsoft.BingFinance’,
‘Microsoft.BingNews’,
‘Microsoft.BingSports’,
‘Microsoft.MicrosoftSolitaireCollection’,
‘Microsoft.People’,
‘Microsoft.Windows.Photos’,
‘Microsoft.WindowsCamera’,
‘microsoft.windowscommunicationsapps’,
‘Microsoft.WindowsPhone’,
‘Microsoft.WindowsSoundRecorder’,
‘Microsoft.XboxApp’,
‘Microsoft.ZuneMusic’,
‘Microsoft.ZuneVideo’,
‘Microsoft.Getstarted’,
‘Microsoft.WindowsFeedbackHub’,
‘Microsoft.XboxIdentityProvider’,
‘Microsoft.MicrosoftOfficeHub’
ForEach ($App in $AppsList){
$PackageFullName = (Get-AppxPackage $App).PackageFullName
$ProPackageFullName = (Get-AppxProvisionedPackage -online | where {$_.Displayname -eq $App}).PackageName
write-host $PackageFullName
Write-Host $ProPackageFullName
if ($PackageFullName){
Write-Host “Removing Package: $App”
remove-AppxPackage -package $PackageFullName
}
else{
Write-Host “Unable to find package: $App”
}
if ($ProPackageFullName){
Write-Host “Removing Provisioned Package: $ProPackageFullName”
Remove-AppxProvisionedPackage -online -packagename $ProPackageFullName
}
else{
Write-Host “Unable to find provisioned package: $App”
}
}
(Get-AppxPackage).name
Mkdir d:\backups_audit
cd "C:\Program files\Tivoli\TSM\baclient"
dsmc q b -ina -sub=yes C:* > "D:\backups_audit\CDriveProtectedFiles.txt"
sort /r "D:\backups_audit\CDriveProtectedFiles.txt" > "D:\backups_audit\CDriveProtectedFiles-Sorted.txt"
dsmc q b -ina -sub=yes D:* > "D:\backups_audit\DDriveProtectedFiles.txt"
sort /r "D:\backups_audit\DDriveProtectedFiles.txt" > "D:\backups_audit\DDriveProtectedFiles-Sorted.txt"
dsmc q b -ina -sub=yes E:* > "D:\backups_audit\EDriveProtectedFiles.txt"
sort /r "D:\backups_audit\EDriveProtectedFiles.txt" > "D:\backups_audit\EDriveProtectedFiles-Sorted.txt"
dsmc q b -ina -sub=yes F:* > "D:\backups_audit\FDriveProtectedFiles.txt"
sort /r "D:\backups_audit\FDriveProtectedFiles.txt" > "D:\backups_audit\FDriveProtectedFiles-Sorted.txt"
dsmc q b -ina -sub=yes f:* > "D:\backups_audit\FDriveProtectedFiles.txt"
sort /r "D:\backups_audit\FDriveProtectedFiles.txt" > "D:\backups_audit\FDriveProtectedFiles-Sorted.txt"
dsmc q b -ina -sub=yes G:* > "D:\backups_audit\GDriveProtectedFiles.txt"
sort /r "D:\backups_audit\GDriveProtectedFiles.txt" > "D:\backups_audit\GDriveProtectedFiles-Sorted.txt"
cd "C:\Program files\Tivoli\TSM\TDPSql"
tdpsqlc q tsm * full /fileinfo /all > "D:\backups_audit\DatabasesProtected.txt"
cd "C:\Program files\Tivoli\TSM\baclient"
type dsm.opt
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/7ec1e22ec277a516032d/7297a934dd927bbd6e0c/tivoli-backups-audit.ps1'))
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/e128168df5034c16e0fb/3984be3344371e9682f6/firewall.ps1'))
https://viewdns.info/dnsreport/?domain=dogshow.ca
http://dns.squish.net/
https://www.dotcom-tools.com/DNS-lookup-tools.aspx
https://stackoverflow.com/questions/38021/how-do-i-find-the-authoritative-name-server-for-a-domain-name
https://manytools.org/network/query-dns-records-online/
https://ns.tools/dogshow.ca
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
# ------------------------------------------------------
# SMTP configuration: username, password, SSL and so on
# ------------------------------------------------------
$email_username = "username@yourdomain.com";
$email_password = "yourpassword";
$email_smtp_host = "smtp.yourdomain.com";
$email_smtp_port = 465;
$email_smtp_SSL = 1;
$email_from_address = "username@yourdomain.com";
$email_to_addressArray = @("to1@yourdomain.com", "to2@yourdomain.com");
# [...]
# ------------------------------------------------------
# E-Mail message configuration: from, to, subject, body
# ------------------------------------------------------
$message = new-object Net.Mail.MailMessage;
$message.From = $email_from_address;
foreach ($to in $email_to_addressArray) {
$message.To.Add($to);
}
$message.Subject = "Subject goes here";
$message.Body = "Message body goes here";
# [...]
# ------------------------------------------------------
# Create SmtpClient object and send the e-mail message
# ------------------------------------------------------
$smtp = new-object Net.Mail.SmtpClient($email_smtp_host, $email_smtp_port);
$smtp.EnableSSL = $email_smtp_SSL;
$smtp.Credentials = New-Object System.Net.NetworkCredential($email_username, $email_password);
$smtp.send($message);
$message.Dispose();
#example
New-PSDrive -Name m -Root '\\192.168.0.12\d$' -PSProvider FileSystem -Scope Global -Persist:$true -credential usr094205
Install-Module TestConnectionAsync -scope CurrentUser
get-command -Module TestConnectionAsync
# Make a list IP or Domains to ping and save it as IPAddresses.txt
# Example calls, all piping the contents of an IPAddresses.txt file to the command.
Get-Content .\IPAddresses.txt |
Test-ConnectionAsync -MaxConcurrent 250 -Quiet
Get-Content .\IPAddresses.txt |
Test-ConnectionAsync -MaxConcurrent 500 |
Select-Object -Property $PingQuickSelectPropertyList
Get-Content .\IPAddresses.txt |
Test-ConnectionAsync -MaxConcurrent 500 |
Format-Table -Property $PingQuickFormatPropertyList
here is a set of netsh command lines which I use very often.
Show Interface configuration
netsh interface ipv4 show config
Only IP Addresses of all LAN adapters
netsh interface ipv4 show address
Show global TCP/IP Parameters
netsh interface ipv4 show global
Disable and enable a Interface
netsh int set int name="ethernet" admin=disabled
netsh int set int name="ethernet" admin=enabled
Show all network interfaces and its link state
netsh interface ipv4 show interfaces
Print the routing table
netsh interface ipv4 show route
Show all tcp connections
netsh interface ipv4 show tcpconnections
Which Multicast groups are joined
netsh interface ipv4 show joins
Show dynamic portrange for outgoing connections
netsh interface ipv4 show dynamicportrange protocol=tcp
Set a static IP Address (172.16.254.2), Subnet Mask (255.255.255.192) and Gateway (172.16.254.1) on a specific interface (Local Area Connection 2) persistent
netsh interface ipv4 set address name="Local Area Connection 2" static 172.16.254.2 255.255.255.192 172.16.254.1 store=persistent
and temporary up to the next reboot and the parameters at full length. After the reboot the IP Address is empty.
netsh interface ipv4 set address name="Local Area Connection 2" static address=172.16.254.2 mask=255.255.255.192 gateway=172.16.254.1 store=active
Set DNS Servers without a DNS check, the set dnsservers command supports only one server as argument
netsh interface ipv4 set dnsservers name="Local Area Connection 2" source=static address="172.16.254.250" validate=no
you have to add a second DNS Server with the add dnsservers directive
netsh interface ipv4 add dnsservers name="Local Area Connection 2" address="172.16.254.251" validate=no index=2
Set IP Address assignment on Interface to DHCP
netsh interface ipv4 set address name="Local Area Connection 2" source=dhcp
and also the DNS Servers
netsh interface ipv4 set dnsservers name="Local Area Connection 2" source=dhcp
Add a route for subnet 172.16.1.0/24 over interface “Local Area Connection 2” and router 172.16.254.254
netsh interface add route prefix=172.16.1.0/24 interface="Local Area Connection 2" nexthop=172.16.254.254
Note: Since Windows Vista its not possible to set the dns search suffix with netsh, you have to use WMI for this.
To set the DNS search suffix use powershell and wmi.
Define your Domains
[string[]]$aDNSSearchSuffixes=@("subdomain.domain1.local","subdomain.domain2.local")
$oNetworkadapterConfiguration=[wmiclass]"Win32_NetworkadapterConfiguration" $oNetworkadapterConfiguration.SetDNSSuffixSearchOrder($aDNSSearchSuffixes)
Invoke-WmiMethod -Class Win32_NetworkadapterConfiguration -Name SetDNSSuffixSearchOrder -ArgumentList @(@("subdomain.domain1.local","subdomain.domain2.local"),$null)
Invoke-WmiMethod -Class Win32_NetworkadapterConfiguration -Name SetDNSSuffixSearchOrder -ArgumentList @($aDNSSearchSuffixes,$null)
Function Get-ClientWSUSSetting {
<#
.SYNOPSIS
Retrieves the wsus client settings on a local or remove system.
.DESCRIPTION
Retrieves the wsus client settings on a local or remove system.
.PARAMETER Computername
Name of computer to connect to. Can be a collection of computers.
.PARAMETER ShowEnvironment
Display only the Environment settings.
.PARAMETER ShowConfiguration
Display only the Configuration settings.
.NOTES
Name: Get-WSUSClient
Author: Boe Prox
DateCreated: 02DEC2011
.LINK
https://learn-powershell.net
.EXAMPLE
Get-ClientWSUSSetting -Computername TestServer
RescheduleWaitTime : NA
AutoInstallMinorUpdates : NA
TargetGroupEnabled : NA
ScheduledInstallDay : NA
DetectionFrequencyEnabled : 1
WUServer : http://wsus.com
Computername : TestServer
RebootWarningTimeoutEnabled : NA
ElevateNonAdmins : NA
ScheduledInstallTime : NA
RebootRelaunchTimeout : 10
ScheduleInstallDay : NA
RescheduleWaitTimeEnabled : NA
DisableWindowsUpdateAccess : NA
AUOptions : 3
DetectionFrequency : 4
RebootWarningTimeout : NA
ScheduleInstallTime : NA
WUStatusServer : http://wsus.com
TargetGroup : NA
RebootRelaunchTimeoutEnabled : 1
UseWUServer : 1
NoAutoRebootWithLoggedOnUsers : 1
Description
-----------
Displays both Environment and Configuration settings for TestServer
.EXAMPLE
Get-ClientWSUSSetting -Computername Server1 -ShowEnvironment
Computername : Server1
TargetGroupEnabled : NA
TargetGroup : NA
WUStatusServer : http://wsus.com
WUServer : http://wsus.com
DisableWindowsUpdateAccess : 1
ElevateNonAdmins : 0
Description
-----------
Displays the Environment settings for Server1
.Example
Get-ClientWSUSSetting -Computername Server1 -ShowConfiguration
ScheduledInstallTime : NA
AutoInstallMinorUpdates : 0
ScheduledInstallDay : NA
Computername : Server1
RebootWarningTimeoutEnabled : NA
RebootWarningTimeout : NA
NoAUAsDefaultShutdownOption : NA
RebootRelaunchTimeout : NA
DetectionFrequency : 4
ScheduleInstallDay : NA
RescheduleWaitTime : NA
RescheduleWaitTimeEnabled : 0
AUOptions : 3
NoAutoRebootWithLoggedOnUsers : 1
DetectionFrequencyEnabled : 1
ScheduleInstallTime : NA
NoAUShutdownOption : NA
RebootRelaunchTimeoutEnabled : NA
UseWUServer : 1
IncludeRecommendedUpdates : NA
Description
-----------
Displays the Configuration settings for Server1
#>
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine = $True)]
[string[]]$Computername = $Env:Computername,
[parameter()]
[switch]$ShowEnvironment,
[parameter()]
[switch]$ShowConfiguration
)
Begin {
$EnvKeys = "WUServer","WUStatusServer","ElevateNonAdmins","TargetGroupEnabled","TargetGroup","DisableWindowsUpdateAccess"
$ConfigKeys = "AUOptions","AutoInstallMinorUpdates","DetectionFrequency","DetectionFrequencyEnabled","NoAutoRebootWithLoggedOnUsers",
"NoAutoUpdate","RebootRelaunchTimeout","RebootRelaunchTimeoutEnabled","RebootWarningTimeout","RebootWarningTimeoutEnabled","RescheduleWaitTime","RescheduleWaitTimeEnabled",
"ScheduleInstallDay","ScheduleInstallTime","UseWUServer"
}
Process {
$PSBoundParameters.GetEnumerator() | ForEach {
Write-Verbose ("{0}" -f $_)
}
ForEach ($Computer in $Computername) {
If (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
$WSUSEnvhash = @{}
$WSUSConfigHash = @{}
$ServerReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$Computer)
#Get WSUS Client Environment Options
$WSUSEnv = $ServerReg.OpenSubKey('Software\Policies\Microsoft\Windows\WindowsUpdate')
$subkeys = @($WSUSEnv.GetValueNames())
$NoData = @(Compare-Object -ReferenceObject $EnvKeys -DifferenceObject $subkeys | Select -ExpandProperty InputObject)
ForEach ($item in $NoData) {
$WSUSEnvhash[$item] = 'NA'
}
$Data = @(Compare-Object -ReferenceObject $EnvKeys -DifferenceObject $subkeys -IncludeEqual -ExcludeDifferent | Select -ExpandProperty InputObject)
ForEach ($key in $Data) {
If ($key -eq 'WUServer') {
$WSUSEnvhash['WUServer'] = $WSUSEnv.GetValue('WUServer')
}
If ($key -eq 'WUStatusServer') {
$WSUSEnvhash['WUStatusServer'] = $WSUSEnv.GetValue('WUStatusServer')
}
If ($key -eq 'ElevateNonAdmins') {
$WSUSEnvhash['ElevateNonAdmins'] = $WSUSEnv.GetValue('ElevateNonAdmins')
}
If ($key -eq 'TargetGroupEnabled') {
$WSUSEnvhash['TargetGroupEnabled'] = $WSUSEnv.GetValue('TargetGroupEnabled')
}
If ($key -eq 'TargetGroup') {
$WSUSEnvhash['TargetGroup'] = $WSUSEnv.GetValue('TargetGroup')
}
If ($key -eq 'DisableWindowsUpdateAccess') {
$WSUSEnvhash['DisableWindowsUpdateAccess'] = $WSUSEnv.GetValue('DisableWindowsUpdateAccess')
}
}
#Get WSUS Client Configuration Options
$WSUSConfig = $ServerReg.OpenSubKey('Software\Policies\Microsoft\Windows\WindowsUpdate\AU')
$subkeys = @($WSUSConfig.GetValueNames())
$NoData = @(Compare-Object -ReferenceObject $ConfigKeys -DifferenceObject $subkeys | Select -ExpandProperty InputObject)
ForEach ($item in $NoData) {
$WSUSConfighash[$item] = 'NA'
}
$Data = @(Compare-Object -ReferenceObject $ConfigKeys -DifferenceObject $subkeys -IncludeEqual -ExcludeDifferent | Select -ExpandProperty InputObject)
ForEach ($key in $Data) {
If ($key -eq 'AUOptions') {
$WSUSConfighash['AUOptions'] = $WSUSConfig.GetValue('AUOptions')
}
If ($key -eq 'AutoInstallMinorUpdates') {
$WSUSConfighash['AutoInstallMinorUpdates'] = $WSUSConfig.GetValue('AutoInstallMinorUpdates')
}
If ($key -eq 'DetectionFrequency') {
$WSUSConfighash['DetectionFrequency'] = $WSUSConfig.GetValue('DetectionFrequency')
}
If ($key -eq 'DetectionFrequencyEnabled') {
$WSUSConfighash['DetectionFrequencyEnabled'] = $WSUSConfig.GetValue('DetectionFrequencyEnabled')
}
If ($key -eq 'NoAutoRebootWithLoggedOnUsers') {
$WSUSConfighash['NoAutoRebootWithLoggedOnUsers'] = $WSUSConfig.GetValue('NoAutoRebootWithLoggedOnUsers')
}
If ($key -eq 'RebootRelaunchTimeout') {
$WSUSConfighash['RebootRelaunchTimeout'] = $WSUSConfig.GetValue('RebootRelaunchTimeout')
}
If ($key -eq 'RebootRelaunchTimeoutEnabled') {
$WSUSConfighash['RebootRelaunchTimeoutEnabled'] = $WSUSConfig.GetValue('RebootRelaunchTimeoutEnabled')
}
If ($key -eq 'RebootWarningTimeout') {
$WSUSConfighash['RebootWarningTimeout'] = $WSUSConfig.GetValue('RebootWarningTimeout')
}
If ($key -eq 'RebootWarningTimeoutEnabled') {
$WSUSConfighash['RebootWarningTimeoutEnabled'] = $WSUSConfig.GetValue('RebootWarningTimeoutEnabled')
}
If ($key -eq 'RescheduleWaitTime') {
$WSUSConfighash['RescheduleWaitTime'] = $WSUSConfig.GetValue('RescheduleWaitTime')
}
If ($key -eq 'RescheduleWaitTimeEnabled') {
$WSUSConfighash['RescheduleWaitTimeEnabled'] = $WSUSConfig.GetValue('RescheduleWaitTimeEnabled')
}
If ($key -eq 'ScheduleInstallDay') {
$WSUSConfighash['ScheduleInstallDay'] = $WSUSConfig.GetValue('ScheduleInstallDay')
}
If ($key -eq 'ScheduleInstallTime') {
$WSUSConfighash['ScheduleInstallTime'] = $WSUSConfig.GetValue('ScheduleInstallTime')
}
If ($key -eq 'UseWUServer') {
$WSUSConfighash['UseWUServer'] = $WSUSConfig.GetValue('UseWUServer')
}
}
#Display Output
If ((-Not ($PSBoundParameters['ShowEnvironment'] -OR $PSBoundParameters['ShowConfiguration'])) -OR `
($PSBoundParameters['ShowEnvironment'] -AND $PSBoundParameters['ShowConfiguration'])) {
Write-Verbose "Displaying everything"
$WSUSHash = ($WSUSEnvHash + $WSUSConfigHash)
$WSUSHash['Computername'] = $Computer
New-Object PSObject -Property $WSUSHash
} Else {
If ($PSBoundParameters['ShowEnvironment']) {
Write-Verbose "Displaying environment settings"
$WSUSEnvHash['Computername'] = $Computer
New-Object PSObject -Property $WSUSEnvhash
}
If ($PSBoundParameters['ShowConfiguration']) {
Write-Verbose "Displaying Configuration settings"
$WSUSConfigHash['Computername'] = $Computer
New-Object PSObject -Property $WSUSConfigHash
}
}
} Else {
Write-Warning ("{0}: Unable to connect!" -f $Computer)
}
}
}
}
Function Set-ClientWSUSSetting {
<#
.SYNOPSIS
Sets the wsus client settings on a local or remove system.
.DESCRIPTION
Sets the wsus client settings on a local or remove system.
.PARAMETER Computername
Name of computer to connect to. Can be a collection of computers.
.PARAMETER UpdateServer
URL of the WSUS server. Must use Https:// or Http://
.PARAMETER TargetGroup
Name of the Target Group to which the computer belongs on the WSUS server.
.PARAMETER DisableTargetGroup
Disables the use of setting a Target Group
.PARAMETER Options
Configure the Automatic Update client options.
Accepted Values are: "Notify","DownloadOnly","DownloadAndInstall","AllowUserConfig"
.PARAMETER DetectionFrequency
Specifed time (in hours) for detection from client to server.
Accepted range is: 1-22
.PARAMETER DisableDetectionFrequency
Disables the detection frequency on the client.
.PARAMETER RebootLaunchTimeout
Set the timeout (in minutes) for scheduled restart.
Accepted range is: 1-1440
.PARAMETER DisableRebootLaunchTimeout
Disables the reboot launch timeout.
.PARAMETER RebootWarningTimeout
Set the restart warning countdown (in minutes)
Accepted range is: 1-30
.PARAMETER DisableRebootWarningTimeout
Disables the reboot warning timeout
.PARAMETER RescheduleWaitTime
Time (in minutes) that Automatic Updates should wait at startup before applying updates from a missed scheduled installation time.
.PARAMETER DisableRescheduleWaitTime
Disables the RescheduleWaitTime
.PARAMETER ScheduleInstallDay
Specified Day of the week to perform automatic installation. Only valid when Options is set to "DownloadAndInstall"
Accepted values are: "Everyday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"
.PARAMETER ElevateNonAdmins
Allow non-administrators to approve or disapprove updates
Accepted values are: "Enable","Disable"
.PARAMETER AllowAutomaticUpdates
Enables or disables Automatic Updates
Accepted values are: "Enable","Disable"
.PARAMETER UseWSUSServer
Enables or disables use of a Windows Update Server
Accepted values are: "Enable","Disable"
.PARAMETER AutoInstallMinorUpdates
Enables or disables silent installation of minor updates.
Accepted values are: "Enable","Disable"
.PARAMETER AutoRebootWithLoggedOnUsers
Enables or disables automatic reboots after patching completed whether users or logged into the machine or not.
Accepted values are: "Enable","Disable"
.NOTES
Name: Set-WSUSClient
Author: Boe Prox
https://learn-powershell.net
DateCreated: 02DEC2011
DateModified: 28Mar2014
To do: Add -PassThru support
.LINK
http://technet.microsoft.com/en-us/library/cc708449(WS.10).aspx
.EXAMPLE
Set-ClientWSUSSetting -UpdateServer "http://testwsus.com" -UseWSUSServer Enable -AllowAutomaticUpdates Enable -DetectionFrequency 4 -Options DownloadOnly
Description
-----------
Configures the local computer to enable automatic updates and use testwsus.com as the update server. Also sets the update detection
frequency to occur every 4 hours and only downloads the updates.
.EXAMPLE
Set-ClientWSUSSetting -UpdateServer "http://testwsus.com" -UseWSUSServer Enable -AllowAutomaticUpdates Enable -DetectionFrequency 4 -Options DownloadAndInstall -RebootWarningTimeout 15
-ScheduledInstallDay Monday -ScheduledInstallTime 20
Description
-----------
Configures the local computer to enable automatic updates and use testwsus.com as the update server. Also sets the update detection
frequency to occur every 4 hours and performs the installation automatically every Monday at 8pm and configured to reboot 15 minutes (with a timer for logged on users) after updates
have been installed.
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(Position=0,ValueFromPipeLine = $True)]
[string[]]$Computername = $Env:Computername,
[parameter(Position=1)]
[string]$UpdateServer,
[parameter(Position=2)]
[string]$TargetGroup,
[parameter(Position=3)]
[switch]$DisableTargetGroup,
[parameter(Position=4)]
[ValidateSet('Notify','DownloadOnly','DownloadAndInstall','AllowUserConfig')]
[string]$Options,
[parameter(Position=5)]
[ValidateRange(1,22)]
[Int32]$DetectionFrequency,
[parameter(Position=6)]
[switch]$DisableDetectionFrequency,
[parameter(Position=7)]
[ValidateRange(1,1440)]
[Int32]$RebootLaunchTimeout,
[parameter(Position=8)]
[switch]$DisableRebootLaunchTimeout,
[parameter(Position=9)]
[ValidateRange(1,30)]
[Int32]$RebootWarningTimeout,
[parameter(Position=10)]
[switch]$DisableRebootWarningTimeout,
[parameter(Position=11)]
[ValidateRange(1,60)]
[Int32]$RescheduleWaitTime,
[parameter(Position=12)]
[switch]$DisableRescheduleWaitTime,
[parameter(Position=13)]
[ValidateSet('EveryDay','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')]
[ValidateCount(1,1)]
[string[]]$ScheduleInstallDay,
[parameter(Position=14)]
[ValidateRange(0,23)]
[Int32]$ScheduleInstallTime,
[parameter(Position=15)]
[ValidateSet('Enable','Disable')]
[string]$ElevateNonAdmins,
[parameter(Position=16)]
[ValidateSet('Enable','Disable')]
[string]$AllowAutomaticUpdates,
[parameter(Position=17)]
[ValidateSet('Enable','Disable')]
[string]$UseWSUSServer,
[parameter(Position=18)]
[ValidateSet('Enable','Disable')]
[string]$AutoInstallMinorUpdates,
[parameter(Position=19)]
[ValidateSet('Enable','Disable')]
[string]$AutoRebootWithLoggedOnUsers
)
Begin {
}
Process {
$PSBoundParameters.GetEnumerator() | ForEach {
Write-Verbose ("{0}" -f $_)
}
ForEach ($Computer in $Computername) {
If (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
$WSUSEnvhash = @{}
$WSUSConfigHash = @{}
$ServerReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$Computer)
#Check to see if WSUS registry keys exist
$temp = $ServerReg.OpenSubKey('Software\Policies\Microsoft\Windows',$True)
If (-NOT ($temp.GetSubKeyNames() -contains 'WindowsUpdate')) {
#Build the required registry keys
$temp.CreateSubKey('WindowsUpdate\AU') | Out-Null
}
#Set WSUS Client Environment Options
$WSUSEnv = $ServerReg.OpenSubKey('Software\Policies\Microsoft\Windows\WindowsUpdate',$True)
If ($PSBoundParameters['ElevateNonAdmins']) {
If ($ElevateNonAdmins -eq 'Enable') {
If ($pscmdlet.ShouldProcess("Elevate Non-Admins","Enable")) {
$WsusEnv.SetValue('ElevateNonAdmins',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
} ElseIf ($ElevateNonAdmins -eq 'Disable') {
If ($pscmdlet.ShouldProcess("Elevate Non-Admins","Disable")) {
$WsusEnv.SetValue('ElevateNonAdmins',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['UpdateServer']) {
If ($pscmdlet.ShouldProcess("WUServer","Set Value")) {
$WsusEnv.SetValue('WUServer',$UpdateServer,[Microsoft.Win32.RegistryValueKind]::String)
}
If ($pscmdlet.ShouldProcess("WUStatusServer","Set Value")) {
$WsusEnv.SetValue('WUStatusServer',$UpdateServer,[Microsoft.Win32.RegistryValueKind]::String)
}
}
If ($PSBoundParameters['TargetGroup']) {
If ($pscmdlet.ShouldProcess("TargetGroup","Enable")) {
$WsusEnv.SetValue('TargetGroupEnabled',1,[Microsoft.Win32.RegistryValueKind]::Dword)
}
If ($pscmdlet.ShouldProcess("TargetGroup","Set Value")) {
$WsusEnv.SetValue('TargetGroup',$TargetGroup,[Microsoft.Win32.RegistryValueKind]::String)
}
}
If ($PSBoundParameters['DisableTargetGroup']) {
If ($pscmdlet.ShouldProcess("TargetGroup","Disable")) {
$WsusEnv.SetValue('TargetGroupEnabled',0,[Microsoft.Win32.RegistryValueKind]::Dword)
}
}
#Set WSUS Client Configuration Options
$WSUSConfig = $ServerReg.OpenSubKey('Software\Policies\Microsoft\Windows\WindowsUpdate\AU',$True)
If ($PSBoundParameters['Options']) {
If ($pscmdlet.ShouldProcess("Options","Set Value")) {
If ($Options -eq 'Notify') {
$WsusConfig.SetValue('AUOptions',2,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($Options = 'DownloadOnly') {
$WsusConfig.SetValue('AUOptions',3,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($Options = 'DownloadAndInstall') {
$WsusConfig.SetValue('AUOptions',4,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($Options = 'AllowUserConfig') {
$WsusConfig.SetValue('AUOptions',5,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['DetectionFrequency']) {
If ($pscmdlet.ShouldProcess("DetectionFrequency","Enable")) {
$WsusConfig.SetValue('DetectionFrequencyEnabled',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
If ($pscmdlet.ShouldProcess("DetectionFrequency","Set Value")) {
$WsusConfig.SetValue('DetectionFrequency',$DetectionFrequency,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['DisableDetectionFrequency']) {
If ($pscmdlet.ShouldProcess("DetectionFrequency","Disable")) {
$WsusConfig.SetValue('DetectionFrequencyEnabled',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['RebootWarningTimeout']) {
If ($pscmdlet.ShouldProcess("RebootWarningTimeout","Enable")) {
$WsusConfig.SetValue('RebootWarningTimeoutEnabled',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
If ($pscmdlet.ShouldProcess("RebootWarningTimeout","Set Value")) {
$WsusConfig.SetValue('RebootWarningTimeout',$RebootWarningTimeout,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['DisableRebootWarningTimeout']) {
If ($pscmdlet.ShouldProcess("RebootWarningTimeout","Disable")) {
$WsusConfig.SetValue('RebootWarningTimeoutEnabled',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['RebootLaunchTimeout']) {
If ($pscmdlet.ShouldProcess("RebootLaunchTimeout","Enable")) {
$WsusConfig.SetValue('RebootLaunchTimeoutEnabled',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
If ($pscmdlet.ShouldProcess("RebootLaunchTimeout","Set Value")) {
$WsusConfig.SetValue('RebootLaunchTimeout',$RebootLaunchTimeout,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['DisableRebootLaunchTimeout']) {
If ($pscmdlet.ShouldProcess("RebootWarningTimeout","Disable")) {
$WsusConfig.SetValue('RebootLaunchTimeoutEnabled',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['ScheduleInstallDay']) {
If ($pscmdlet.ShouldProcess("ScheduledInstallDay","Set Value")) {
If ($ScheduleInstallDay = 'EveryDay') {
$WsusConfig.SetValue('ScheduledInstallDay',0,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Monday') {
$WsusConfig.SetValue('ScheduledInstallDay',1,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Tuesday') {
$WsusConfig.SetValue('ScheduledInstallDay',2,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Wednesday') {
$WsusConfig.SetValue('ScheduledInstallDay',3,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Thursday') {
$WsusConfig.SetValue('ScheduledInstallDay',4,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Friday') {
$WsusConfig.SetValue('ScheduledInstallDay',5,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Saturday') {
$WsusConfig.SetValue('ScheduledInstallDay',6,[Microsoft.Win32.RegistryValueKind]::DWord)
} ElseIf ($ScheduleInstallDay = 'Sunday') {
$WsusConfig.SetValue('ScheduledInstallDay',7,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['RescheduleWaitTime']) {
If ($pscmdlet.ShouldProcess("RescheduleWaitTime","Enable")) {
$WsusConfig.SetValue('RescheduleWaitTimeEnabled',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
If ($pscmdlet.ShouldProcess("RescheduleWaitTime","Set Value")) {
$WsusConfig.SetValue('RescheduleWaitTime',$RescheduleWaitTime,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['DisableRescheduleWaitTime']) {
If ($pscmdlet.ShouldProcess("RescheduleWaitTime","Disable")) {
$WsusConfig.SetValue('RescheduleWaitTimeEnabled',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['ScheduleInstallTime']) {
If ($pscmdlet.ShouldProcess("ScheduleInstallTime","Set Value")) {
$WsusConfig.SetValue('ScheduleInstallTime',$ScheduleInstallTime,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
If ($PSBoundParameters['AllowAutomaticUpdates']) {
If ($AllowAutomaticUpdates -eq 'Enable') {
If ($pscmdlet.ShouldProcess("AllowAutomaticUpdates","Enable")) {
$WsusConfig.SetValue('NoAutoUpdate',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
} ElseIf ($AllowAutomaticUpdates -eq 'Disable') {
If ($pscmdlet.ShouldProcess("AllowAutomaticUpdates","Disable")) {
$WsusConfig.SetValue('NoAutoUpdate',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['UseWSUSServer']) {
If ($UseWSUSServer -eq 'Enable') {
If ($pscmdlet.ShouldProcess("UseWSUSServer","Enable")) {
$WsusConfig.SetValue('UseWUServer',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
} ElseIf ($UseWSUSServer -eq 'Disable') {
If ($pscmdlet.ShouldProcess("UseWSUSServer","Disable")) {
$WsusConfig.SetValue('UseWUServer',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['AutoInstallMinorUpdates']) {
If ($AutoInstallMinorUpdates -eq 'Enable') {
If ($pscmdlet.ShouldProcess("AutoInstallMinorUpdates","Enable")) {
$WsusConfig.SetValue('AutoInstallMinorUpdates',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
} ElseIf ($AutoInstallMinorUpdates -eq 'Disable') {
If ($pscmdlet.ShouldProcess("AutoInstallMinorUpdates","Disable")) {
$WsusConfig.SetValue('AutoInstallMinorUpdates',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
If ($PSBoundParameters['AutoRebootWithLoggedOnUsers']) {
If ($AutoRebootWithLoggedOnUsers -eq 'Enable') {
If ($pscmdlet.ShouldProcess("AutoRebootWithLoggedOnUsers","Enable")) {
$WsusConfig.SetValue('NoAutoRebootWithLoggedOnUsers',1,[Microsoft.Win32.RegistryValueKind]::DWord)
}
} ElseIf ($AutoRebootWithLoggedOnUsers -eq 'Disable') {
If ($pscmdlet.ShouldProcess("AutoRebootWithLoggedOnUsers","Disable")) {
$WsusConfig.SetValue('NoAutoRebootWithLoggedOnUsers',0,[Microsoft.Win32.RegistryValueKind]::DWord)
}
}
}
} Else {
Write-Warning ("{0}: Unable to connect!" -f $Computer)
}
}
}
}
get-vm * |sort-object| ft -auto Name,path,configurationlocation,snapshotfilelocation,@{L="Disks";E={$_.harddrives.path}}
Get-VM | ForEach { $Vm = $_; $_.HardDrives } | ForEach {
$GetVhd = Get-VHD -Path $_.Path
[pscustomobject]@{
Vm = $Vm.Name
Name = $_.Name
Type = $GetVhd.VhdType
ProvisionedGB = ($GetVhd.Size / 1GB)
CommittedGB = ($GetVhd.FileSize / 1GB)
}
}
GET-VM | GET-VMmemory
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$UserName = "usr194106"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
import-module -Name VMware.PowerCLI -Scope Local
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
Connect-VIServer localhost
Invoke-VMScript -VM 'VMG0501.AppGarden-5289048' -GuestCredential $Credentials -ScriptType Bat -Scripttext "dir"
Invoke-VMScript -VM 'VMG0501.AppGarden-5289048' -GuestCredential $Credentials -ScriptType Powershell -Scripttext "get-service"
Disconnect-VIServer localhost -Confirm:$false
$downloadlink='https://www.digicert.com/util/DigiCertUtil.zip'
new-item -ItemType Directory -Path $Env:USERPROFILE'\DigiCertUtil' -force
$digicert = Join-Path $Env:USERPROFILE DigiCertUtil
Start-BitsTransfer "$downloadlink" -Destination $digicert
Expand-Archive $digicert'\digicertutil.zip' -DestinationPath $digicert
cd $digicert
& .\DigiCertUtil.exe
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/4830e6e55719ef2dec60/a2153950616f63766e3a/get-windowsupdateconfiguration.ps1'))
$netcatagory = Read-Host -Prompt 'enter Private or DomainAuthenticated or public'
Write-Host Before
Get-NetConnectionProfile
Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory $netcatagory
Write-Host After
Get-NetConnectionProfile
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
choco install grep -y
Get-Service | Select-Object -Property Name,Status,StartType | where-object {$_.StartType -eq "disabled"} | Format-Table -auto
choco install powershell-core --install-arguments='"ADDEXPLORERCONTEXTMENUOPENPOWERSHELL=1 REGISTERMANIFEST=1 ENABLEPSREMOTING=1"' --packageparameters '"/CleanUpPath"' -y
#install vscode for editor
choco install vscode -y
# "terminal.integrated.shell.windows": "C:\\Program Files\\PowerShell\\6.0.1\\pwsh.exe",
New-ItemProperty -Path HKLM:Software\Microsoft\Windows\CurrentVersion\policies\system -Name EnableLUA -PropertyType DWord -Value 0 -Force
clear-host
get-content "C:\Program Files\tivoli\tsm\baclient\dsm.opt"
$input = "INCLUDE ""C:\Data\AltaroV5\43eac2fe-6c95-42be-942d-c4bbe112b3ca\11864300-DFDE-4721-9075-55E6EA849A8D\*.bck"
$input2 = "INCLUDE ""C:\Data\AltaroV5\43eac2fe-6c95-42be-942d-c4bbe112b3ca\11864300-DFDE-4721-9075-55E6EA849A8D\*.bak"
Write-host "match for the two changes"
get-content "C:\Program Files\tivoli\tsm\baclient\dsm.opt" | Select-String -Pattern $input -SimpleMatch
get-content "C:\Program Files\tivoli\tsm\baclient\dsm.opt" | Select-String -Pattern $input2 -SimpleMatch
write-host @"
To run a Tivoli Audit copy and paste the line below and they can be found in D:\backups_audit
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/7ec1e22ec277a516032d/7297a934dd927bbd6e0c/tivoli-backups-audit.ps1'))
To Edit the DSM.opt
notepad "C:\Program Files\tivoli\tsm\baclient\dsm.opt"
"@
get-nettcpconnection | select local*,remote*,state,@{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}} | ft
# Module Logging
$PSModuleLogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4100,4103}
$s= Get-WinEvent -FilterHashtable $PSModuleLogs -MaxEvents 50
# Script Block logging
$PSScriptBlocklogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4104,4105,4106}
$x = Get-WinEvent -FilterHashtable $PSScriptBlocklogs -MaxEvents 50
# all
$PSLogs = @{ProviderName = "Microsoft-Windows-PowerShell";ID=4100,4103,4104,4105,4106,24579,24577}
$logs = Get-WinEvent -FilterHashtable $PSLogs -MaxEvents 100
#**********************************************************************
# Test-LDAPConnectivity.ps1
# This script is designed to Test the connectivity to LDAP, wether it is Open LDAP or Active Directory
# Author: Mike Burr
# Modified On: 29-SEP-2016
# Modifed By: Harmik Singh Batth
# Version: 1.0
# Change History:
#
#
#**********************************************************************
Function Test-LdapConnectivity
{
param(
[String]$ServerName = "",
[UInt16]$Port = 389,
[String]$UserName = "",
[String]$Password = ""
)
#Main script
Clear-host
#Check if all arguments are passedd
if (!$serverName -or !$Port -or !$UserName -or !$Password)
{
Write-Host "USAGE: Test-LDAPConnectivity.ps1 ServerName Port UserName Password"
write-host "Paramaters not defined properly, script will exit now"
break
}
if (!$serverName) {write-host "Please define Server Name"}
if (!$Port) {write-host "Please define Port"}
if (!$UserName) {write-host "Please define Username"}
if (!$Password) {write-host "Please define Password"}
#Load the assemblies
[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")
[System.Reflection.Assembly]::LoadWithPartialName("System.Net")
#Connects to Server on the standard port
$dn = "$ServerName"+":"+"$Port"
$c = New-Object System.DirectoryServices.Protocols.LdapConnection "$dn"
$c.SessionOptions.SecureSocketLayer = $false;
$c.SessionOptions.ProtocolVersion = 3
# Pick Authentication type:
# Anonymous, Basic, Digest, DPA (Distributed Password Authentication),
# External, Kerberos, Msn, Negotiate, Ntlm, Sicily
$c.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
$credentials = new-object "System.Net.NetworkCredential" -ArgumentList $UserName,$Password
# Bind with the network credentials. Depending on the type of server,
# the username will take different forms. Authentication type is controlled
# above with the AuthType
Try
{
$c.Bind($credentials);
Write-Verbose "Successfully bound to LDAP!" -Verbose
return $true
}
catch
{
Write-host $_.Exception.Message
return $false
}
}
-------------------------------------------------------------------------
USAGE:
#e.g.
#Test-LDAPConnectivity.ps1 (Read-host "Enter Server Name") (Read-host "Enter LDAP Port") (Read-host "Enter LDAP Admin username") (Read-host "Enter Password" -AsSecureString)
Disable-NetAdapterChecksumOffload -Name "*" -TcpIPv6
Disable-NetAdapterChecksumOffload -Name "*" -TcpIPv4
Get-NetAdapter | Disable-NetAdapterLso
query inclexcl
dsmc selective "C:\Users\spike\my.*"
#see http://www.tsmtutorials.com/2014/11/incl-excl-statements.html
#see https://help.it.ox.ac.uk/print/12531
#see https://www.ibm.com/support/knowledgecenter/en/SSGSG7_7.1.0/com.ibm.itsm.tshoot.doc/r_pdg_excldirexcludefiles.html
function Get-Size
{
param([string]$pth)
"{0:n2}" -f ((gci -path $pth -recurse | measure-object -property length -sum).sum /1mb) + " mb"
}
# Add registry value to enable Developer Mode
New-ItemProperty -Path $RegistryKeyPath -Name AllowDevelopmentWithoutDevLicense -PropertyType DWORD -Value 1
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Ubuntu.appx -UseBasicParsing
Add-AppPackage .\Ubuntu.appx
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/?view=powershell-5.1
$Password = Read-Host -AsSecureString
New-LocalUser "Skrudland" -Password $Password -FullName "Skrudland" -Description "Support account."
New-LocalUser "bsierra" -Password $Password -FullName "bsierra" -Description "Support account."
Add-LocalGroupMember -Group "Administrators" -Member "bsierra", "Skrudland"
$user=[ADSI]'WinNT://localhost/Skrudland'
$user.passwordExpired = 1
$user.setinfo()
$user=[ADSI]'WinNT://localhost/bsierra'
$user.passwordExpired = 1
$user.setinfo()
function Get-UrlStatusCode([string] $Url)
{
try
{
(Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
}
catch [Net.WebException]
{
[int]$_.Exception.Response.StatusCode
}
}
$statusCode = Get-UrlStatusCode 'httpstat.us/500'
$links = @(get-content "C:\temp\ch3.m3u8")
foreach ($link in $links)
{
Get-UrlStatusCode $links
}
$env:Path += ";C:\ProgramData\ffmpeg\ffmpeg-20190312-d227ed5-win64-static\bin\"
#Text file of copy and paste from PIPS location
$raw = get-content h:\ip.txt
#Regx string to filter out IP addresses
$regex = [regex] "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
#filter out IP addresses and write a new text file
$regex.Matches($raw) | %{ $_.value } | out-file -FilePath "h:\ip_addresses.txt" -Append
#Text file of new file that contains only the IP addresses
$ips = get-content H:\ip_addresses-new.txt
#this copies off the above and could probably be combined
$test = $regex.Matches($ips) | %{ $_.value }
#read each line of text file and add text to it
foreach ($line in $test)
{ write-host set security address-book Trust address $line/32 $line/32 }
#read each line of text file and add text to it
foreach ($line in $test)
{write-host set security address-book Trust address-set Allowed_HTTP_IPs address $line/32}
#read each line of text file and add text to it
foreach ($line in $test)
{write-host set security address-book Trust address-set Allowed_HTTPS_IPs address $line/32}
write-host delete security policies from-zone UnTrust to-zone Trust policy 4 match destination-address All_Trust_IPs
write-host delete security policies from-zone UnTrust to-zone Trust policy 5 match destination-address All_Trust_IPs
write-host delete security address-book Trust address-set Allowed_HTTP_IPs address 207.21.220.11/32
write-host delete security address-book Trust address-set Allowed_HTTPS_IPs address 207.21.220.11/32
write-host set security policies from-zone UnTrust to-zone Trust policy 4 match destination-address Allowed_HTTP_IPs
write-host set security policies from-zone UnTrust to-zone Trust policy 5 match destination-address Allowed_HTTPS_IPs
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$UserName = "vmsvc@vsphere.local"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
install-module -Name VMware.PowerCLI -Scope CurrentUser
import-module -Name VMware.PowerCLI -Scope Local
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
Connect-VIServer 69.0.149.100
get-vm -name ClientVM4* | Shutdown-VMGuest
get-vm -name ClientVM4* |Stop-VM -
get-vm -name ClientVM4* | Set-VM -MemoryGB 16
get-vm -name ClientVM4* | Start-VM
Disconnect-VIServer localhost -Confirm:$false
====================================================================
PS H:\> get-vm -name ClientVM4*
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
ClientVM4.Softnet... PoweredOn 4 8.000
PS H:\> get-vm -name ClientVM4* | Stop-VM
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
ClientVM4.Softnet... PoweredOff 4 8.000
PS H:\> get-vm -name ClientVM4*
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
ClientVM4.Softnet... PoweredOff 4 8.000
PS H:\> get-vm -name ClientVM4* | Set-VM -MemoryGB 16
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
ClientVM4.Softnet... PoweredOff 4 16.000
PS H:\> get-vm -name ClientVM4* | Start-VM
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
ClientVM4.Softnet... PoweredOn 4 16.000
$AutoUpdateNotificationLevels= @{0="Not configured"; 1="Disabled" ; 2="Notify before download";
3="Notify before installation"; 4="Scheduled installation"}
$AutoUpdateDays=@{0="Every Day"; 1="Every Sunday"; 2="Every Monday"; 3="Every Tuesday"; 4="Every Wednesday";
5="Every Thursday"; 6="Every Friday"; 7="EverySaturday"}
Function Set-WindowsUpdateConfig
{Param ($NotificationLevel , $Day, $hour, $IncludeRecommended)
$AUSettings = (New-Object -com "Microsoft.Update.AutoUpdate").Settings
if ($NotificationLevel) {$AUSettings.NotificationLevel =$NotificationLevel}
if ($Day) {$AUSettings.ScheduledInstallationDay =$Day}
if ($hour) {$AUSettings.ScheduledInstallationTime=$hour}
if ($IncludeRecommended) {$AUSettings.IncludeRecommendedUpdates=$IncludeRecommended}
$AUSettings.Save
}
Function Get-WindowsUpdateConfig
{$AUSettings = (New-Object -com "Microsoft.Update.AutoUpdate").Settings
$AUObj = New-Object -TypeName System.Object
Add-Member -inputObject $AuObj -MemberType NoteProperty -Name "NotificationLevel" ` -Value $AutoUpdateNotificationLevels[$AUSettings.NotificationLevel]
Add-Member -inputObject $AuObj -MemberType NoteProperty -Name "UpdateDays" ` -Value $AutoUpdateDays[$AUSettings.ScheduledInstallationDay]
Add-Member -inputObject $AuObj -MemberType NoteProperty -Name "UpdateHour" ` -Value $AUSettings.ScheduledInstallationTime
Add-Member -inputObject $AuObj -MemberType NoteProperty -Name "Recommended updates" ` -Value $(IF ($AUSettings.IncludeRecommendedUpdates) {"Included."} else {"Excluded."})
$AuObj
}
Function Add-WindowsUpdate
{param ($Criteria="IsInstalled=0 and Type='Software'" ,
[switch]$AutoRestart,
[Switch]$ShutdownAfterUpdate)
$resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }
$updateSession = new-object -com "Microsoft.Update.Session"
write-progress -Activity "Updating" -Status "Checking available updates"
$updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates
if ($Updates.Count -eq 0) { "There are no applicable updates."}
else {
$downloader = $updateSession.CreateUpdateDownloader()
$downloader.Updates = $Updates
write-progress -Activity 'Updating' -Status "Downloading $($downloader.Updates.count) updates"
$Result= $downloader.Download()
if (($Result.Hresult -eq 0) –and (($result.resultCode –eq 2) -or ($result.resultCode –eq 3)) ) {
$updatesToInstall = New-object -com "Microsoft.Update.UpdateColl"
$Updates | where {$_.isdownloaded} | foreach-Object {$updatesToInstall.Add($_) | out-null }
$installer = $updateSession.CreateUpdateInstaller()
$installer.Updates = $updatesToInstall
write-progress -Activity 'Updating' -Status "Installing $($Installer.Updates.count) updates"
$installationResult = $installer.Install()
$Global:counter=-1
$installer.updates | Format-Table -autosize -property Title,EulaAccepted,@{label='Result';
expression={$ResultCode[$installationResult.GetUpdateResult($Global:Counter++).resultCode ] }}
if ($autoRestart -and $installationResult.rebootRequired) { shutdown.exe /t 0 /r }
if ($ShutdownAfterUpdate) {shutdown.exe /t 0 /s }
}
}
}
netsh interface ip set address "Primary NIC" static 64.77.94.195 255.255.255.224 64.77.94.193
netsh interface ip set dns name="Primary NIC" source=static addr=216.187.125.130 register=primary
netsh interface ip add dns name="Primary NIC" addr=216.187.125.131 index=2
netsh interface ip add address "Primary NIC" 216.25.41.52 255.255.255.240 216.25.41.49
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/898598777ca38441db95/6c09832784166632580e/frontend-get-traceroute.ps1'))
Get-WinEvent -FilterHashtable @{logname='System'; id=1074} | ForEach-Object {
$rv = New-Object PSObject | Select-Object Date, User, Action, Process, Reason, ReasonCode, Comment
$rv.Date = $_.TimeCreated
$rv.User = $_.Properties[6].Value
$rv.Process = $_.Properties[0].Value
$rv.Action = $_.Properties[4].Value
$rv.Reason = $_.Properties[2].Value
$rv.ReasonCode = $_.Properties[3].Value
$rv.Comment = $_.Properties[5].Value
$rv
} | Select-Object Date, Action, Reason, User
Function Get-RebootHistory {
<#
.SYNOPSIS
Retrieves historical information about shutdown/restart events from one or more remote computers.
.DESCRIPTION
The Get-RebootHistory function uses Windows Management Instrumentation (WMI) to retrieve information about all shutdown events from a remote computer.
Using this function, you can analyze shutdown events across a large number of computers to determine how frequently shutdown/restarts are occurring, whether unexpected shutdowns are occurring and quickly identify the source of the last clean shutdown/restart.
Data returned includes date/time information for all available boot history events (e.g. restarts, shutdowns, unexpected shutdowns, etc.), date/time information for unexpected reboots and detailed information about the last clean shutdown including date/time, type, initiating user, initiating process and reason.
Because Get-RebootHistory uses WMI to obtain shutdown event history from the system event log, it is fully supported against both legacy and current versions of Windows including legacy versions that do not support filtering of event logs through standard methods.
.PARAMETER ComputerName
Accepts a single computer name or an array of computer names separated by commas (e.g. "prod-web01","prod-web02").
This is an optional parameter, the default value is the local computer ($Env:ComputerName).
.PARAMETER Credential
Accepts a standard credential object.
This is an optional parameter and is only necessary when the running user does not have access to the remote computer(s).
.EXAMPLE
.\Get-RebootHistory -ComputerName prod-web01,prod-web02 -Credential (Get-Credential)
Get boot history for multiple remote computers with alternate credentials.
.EXAMPLE
.\Get-RebootHistory -ComputerName prod-web01,prod-web02 -Credential (Get-Credential) | ? { $_.PercentDirty -ge 30 }
Get a list of computers experiencing a high percentage of unexpected shutdown events.
.EXAMPLE
.\Get-RebootHistory -ComputerName prod-web01,prod-web02 -Credential (Get-Credential) | ? { $_.RecentShutdowns -ge 3 }
Return information about servers that have been experiencing frequent shutdown/reboot events over the last 30 days.
.OUTPUTS
System.Management.Automation.PSCustomObject
Return object includes the following properties:
Computer
BootHistory : Array of System.DateTime objects for all recorded instances of the system booting (clean or otherwise).
RecentShutdowns : The number of shutdown/restart events in the last 30 days.
UnexpectedShutdowns : Array of System.DateTime objects for all recorded unexpected shutdown events.
RecentUnexpected : The number of unexpected shutdown events in the last 30 days.
PercentDirty : The percentage of shutdown events that were unexpected (UnexpectedShutdowns/BootHistory).
LastShutdown : System.DateTime object of the last clean shutdown event.
LastShutdownType : Type of the last clean shutdown event (Restart | Shutdown).
LastShutdownUser : The user who initiated the last clean shutdown event.
LastShutdownProcess : The process that initiated the last clean shutdown event.
LastShutdownReason : If available, the reason code and comments for the last clean shutdown event.
.NOTES
Author : Eric Westfall
Email : eawestfall@gmail.com
Script Version : 1.1
Revision Date : 11/26/2014
#>
Param (
[Parameter(Mandatory = $False, Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Alias("CN","Computer")]
[Array]$ComputerName = $Env:ComputerName,
[Parameter(Mandatory = $False, Position = 1, ValueFromPipeline = $False)]
[Alias("Cred")]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
)
Begin {
$i = 0
$RecentShutdowns = 0
$RecentUnexpected = 0
$BootHistory = @()
$ShutdownDetail = @()
$UnexpectedShutdowns = @()
# Store original credential, if we attempt to make a local connection we need to
# temporarily empty out the credential object.
$Original_Credential = $Credential
# Select properties defined to ensure proper display order.
$BootInformation = @(
"Computer"
"BootHistory"
"RecentShutdowns"
"UnexpectedShutdowns"
"RecentUnexpected"
"PercentDirty"
"LastShutdown"
"LastShutdownType"
"LastShutdownUser"
"LastShutdownProcess"
"LastShutdownReason"
)
# Arguments to be passed to our WMI call.
$Params = @{
ErrorAction = 'Stop'
ComputerName = $Computer
Credential = $Credential
Class = 'Win32_NTLogEvent'
Filter = "LogFile = 'System' and EventCode = 6009 or EventCode = 6008 or EventCode = 1074"
}
}
Process {
ForEach ($Computer In $ComputerName) {
$Params.ComputerName = $Computer
# You can't use credentials when connecting to the local machine so temporarily empty out the credential object.
If ($Computer -eq $Env:ComputerName) {
$Params.Credential = [System.Management.Automation.PSCredential]::Empty
}
If ($ComputerName.Count -gt 1) {
Write-Progress -Id 1 -Activity "Retrieving boot history." -Status ("Percent Complete: {0:N0}" -f $($i / $($ComputerName.Count)*100)) -PercentComplete (($i / $ComputerName.Count)*100); $i++
} Else {
Write-Progress -Id 1 -Activity "Retrieving boot history." -Status "Retrieving boot history."
}
Try {
$d = 0
$Events = Get-WmiObject @Params
ForEach ($Event In $Events) {
Write-Progress -Id 2 -ParentId 1 -Activity "Processing reboot history." -PercentComplete (($d / $Events.Count)*100) -Status "Processing reboot history."; $d++
# Record the relevant details for the shutdown event.
Switch ($Event.EventCode) {
6009 { $BootHistory += (Get-Date(([WMI]'').ConvertToDateTime($Event.TimeGenerated)) -Format g) }
6008 { $UnexpectedShutdowns += ('{0} {1}' -f ($Event.InsertionStrings[1], $Event.InsertionStrings[0])) }
1074 { $ShutdownDetail += $Event }
}
}
# We explicitly ignore exceptions originating from this process since some versions of Windows may store dates in invalid formats (e.g. ?11/?16/?2014) in the event log after an unexpected shutdown causing this calculation to fail.
Try {
$RecentUnexpected = ($UnexpectedShutdowns | ? { ((Get-Date)-(Get-Date $_)).TotalDays -le 30 }).Count
} Catch {
$RecentUnexpected = "Unable to calculate."
}
# Grab details about the last clean shutdown and generate our return object.
$ShutdownDetail | Select -First 1 | ForEach-Object {
New-Object -TypeName PSObject -Property @{
Computer = $Computer
BootHistory = $BootHistory
RecentUnexpected = $RecentUnexpected
LastShutdownUser = $_.InsertionStrings[6]
UnexpectedShutdowns = $UnexpectedShutdowns
LastShutdownProcess = $_.InsertionStrings[0]
PercentDirty = '{0:P0}' -f (($UnexpectedShutdowns.Count/$BootHistory.Count))
LastShutdownType = (Get-Culture).TextInfo.ToTitleCase($_.InsertionStrings[4])
LastShutdown = (Get-Date(([WMI]'').ConvertToDateTime($_.TimeGenerated)) -Format g)
RecentShutdowns = ($BootHistory | ? { ((Get-Date)-(Get-Date $_)).TotalDays -le 30 }).Count
LastShutdownReason = 'Reason Code: {0}, Reason: {1}' -f ($_.InsertionStrings[3], $_.InsertionStrings[2])
} | Select $BootInformation
}
} Catch [System.Exception] {
# We explicitly ignore exceptions originating from Get-Date since some versions of Windows may store dates in invalid formats in the event log after an unexpected shutdown.
If ($_.CategoryInfo.Activity -ne 'Get-Date') {
Write-Warning ("Unable to retrieve boot history for {0}. `nError Details: {1}" -f ($Computer, $_))
}
}
# Reset credential object since we may have temporarily overwrote it to deal with local connections.
$Params.Credential = $Original_Credential
}
}
}
This script will create a dummy file, default size of 20mb, and copy to
and from a target server. The Mbps will be determined from the time it
takes to perform this operation.
A folder will be created in the designated Path location called SpeedTest.
The dummy file will be copied to and from that location to determine the
network speed.
.PARAMETER Path
Each Path specified must be in UNC format, i.e. \\server\share
.PARAMETER Size
Designate the size of the dummy file in MB
.INPUTS
<string> UNC of path
.OUTPUTS
PSCustomObject
Server Name of Server
TimeStamp Time when script was run
WriteTime TimeSpan object of how long the write test took
WriteMbps Mbps of the write test
ReadTime TimeSpan object of how long the read test took
ReadMbps Mbps of the read test
.EXAMPLE
.\Test-NetworkSpeed.ps1 -Path "\\server1\share","\\server2\share2"
.EXAMPLE
.\Test-NetworkSpeed.ps1 -Path (Get-Content c:\shares.txt) -Size 25 -Verbose
Pulls paths from c:\Shares.txt (in UNC format), creates a 25mb dummy file for
testing and produces Verbose output.
.EXAMPLE
Get-Content c:\shares.txt | .\Test-NetworkSpeed.ps1 -Size 100
Also pulls paths from c:\Shares.txt, but takes input from the pipeline. Dummy
file size will be 100mb.
.NOTES
Author: Martin Pugh
Twitter: @thesurlyadm1n
Spiceworks: Martin9700
Blog: www.thesurlyadmin.com
Changelog:
1.0 Initial Release
.LINK
http://community.spiceworks.com/scripts/show/2502-network-bandwidth-test-test-networkspeed-ps1
#>
#requires -Version 3.0
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,HelpMessage="Enter UNC's to server to test (dummy file will be saved in this path)")]
[String[]]$Path,
[ValidateRange(1,1000)]
[int]$Size = 20
)
Begin {
Write-Verbose "$(Get-Date): Test-NetworkSpeed Script begins"
Write-Verbose "$(Get-Date): Create dummy file, Size: $($Size)MB"
$Source = $PSScriptRoot
Remove-Item $Source\Test.txt -ErrorAction SilentlyContinue
Set-Location $Source
$DummySize = $Size * 1048576
$CreateMsg = fsutil file createnew test.txt $DummySize
Try {
$TotalSize = (Get-ChildItem $Source\Test.txt -ErrorAction Stop).Length
}
Catch {
Write-Warning "Unable to locate dummy file"
Write-Warning "Create Message: $CreateMsg"
Write-Warning "Last error: $($Error[0])"
Exit
}
Write-Verbose "$(Get-Date): Source for dummy file: $Source\Test.txt"
$RunTime = Get-Date
}
Process {
ForEach ($ServerPath in $Path)
{ $Server = $ServerPath.Split("\")[2]
$Target = "$ServerPath\SpeedTest"
Write-Verbose "$(Get-Date): Checking speed for $Server..."
Write-Verbose "$(Get-Date): Destination: $Target"
If (-not (Test-Path $Target))
{ Try {
New-Item -Path $Target -ItemType Directory -ErrorAction Stop | Out-Null
}
Catch {
Write-Warning "Problem creating $Target folder because: $($Error[0])"
[PSCustomObject]@{
Server = $Server
TimeStamp = $RunTime
Status = "$($Error[0])"
WriteTime = New-TimeSpan -Days 0
WriteMbps = 0
ReadTime = New-TimeSpan -Days 0
ReadMbps = 0
}
Continue
}
}
Try {
Write-Verbose "$(Get-Date): Write Test..."
$WriteTest = Measure-Command {
Copy-Item $Source\Test.txt $Target -ErrorAction Stop
}
Write-Verbose "$(Get-Date): Read Test..."
$ReadTest = Measure-Command {
Copy-Item $Target\Test.txt $Source\TestRead.txt -ErrorAction Stop
}
$Status = "OK"
$WriteMbps = [Math]::Round((($TotalSize * 8) / $WriteTest.TotalSeconds) / 1048576,2)
$ReadMbps = [Math]::Round((($TotalSize * 8) / $ReadTest.TotalSeconds) / 1048576,2)
}
Catch {
Write-Warning "Problem during speed test: $($Error[0])"
$Status = "$($Error[0])"
$WriteMbps = $ReadMbps = 0
$WriteTest = $ReadTest = New-TimeSpan -Days 0
}
[PSCustomObject]@{
Server = $Server
TimeStamp = $RunTime
Status = "OK"
WriteTime = $WriteTest
WriteMbps = $WriteMbps
ReadTime = $ReadTest
ReadMbps = $ReadMbps
}
Remove-Item $Target\Test.txt -ErrorAction SilentlyContinue
Remove-Item $Source\TestRead.txt -ErrorAction SilentlyContinue
}
}
End {
Remove-Item $Source\Test.txt -ErrorAction SilentlyContinue
Write-Verbose "$(Get-Date): Test-NetworkSpeed completed!"
}
$report = @()
$VMs = (Get-Datastore | Where {$_.Name -like 'FC_Datastore 1' -or $_.Name -like '*PROD*'} | Get-VM).Name | sort
Foreach ($VM in $VMs){
$line = Get-VM $VM | Select Name, @{N="vCPU";E={($_).NumCpu}}, @{N="Memory (GB)";E={($_).MemoryGB}}, @{N="Cluster";E={Get-Cluster -VM $_}}, @{N="Folder";E={$_.folder}}, @{N="Network";E={(Get-NetworkAdapter -VM $_).NetworkName}}, @{Expression={if (($_ | Get-HardDisk | Where {$_.DiskType -eq "RawPhysical"}) -eq $Null) {"No"} Else {"Yes"}}; Label="RDMs" }
$report += $line
}
$report | Export-Csv C:\Temp\ProductionVMs.csv -NoTypeInformation -UseCulture
$oldpw = 'old' #replace with old password
$newpw = 'new'#replace with new password
$user = $env:username
$computer = $env:USERDNSDOMAIN
$user = [adsi]"WinNT://$computer/$user"
$user.ChangePassword($oldpw, $newpw)
# PowerCLI Script for adding vmdk to VM and extending disk in windows
# @davidstamen
# http://davidstamen.com
param(
[string]$VM
)
$VM = Get-VM "VMG1001.AppGarden-5289042"
Get-VM $VM|Get-HardDisk|FT Parent, Name, CapacityGB -Autosize
$HardDisk = Read-Host "Enter VMware Hard Disk (Ex. 1)"
$HardDisk = "Hard Disk " + $HardDisk
$HardDiskSize = Read-Host "Enter the new Hard Disk size in GB (Ex. 50)"
$VolumeLetter = Read-Host "Enter the volume letter (Ex. c,d,e,f)"
Get-HardDisk -vm $VM | where {$_.Name -eq $HardDisk} | Set-HardDisk -CapacityGB $HardDiskSize -Confirm:$false
Invoke-VMScript -vm $VM -ScriptText "echo rescan > c:\diskpart.txt && echo select vol $VolumeLetter >> c:\diskpart.txt && echo extend >> c:\diskpart.txt && diskpart.exe /s c:\diskpart.txt" -ScriptType BAT
App1.PCC.ATL
FOR /L %A IN (243,1,245) DO netsh interface ipv4 add address “Primary NIC” 172.30.4.%A 255.255.255.224
FOR /L %A IN (243,1,245) DO ping 172.30.4.%A
App2.PCC.ATL
FOR /L %A IN (246,1,248) DO netsh interface ipv4 add address “Primary NIC” 172.30.4.%A 255.255.255.224
FOR /L %A IN (246,1,248) DO ping 172.30.4.%A
App3.PCC.ATL
FOR /L %A IN (249,1,251) DO netsh interface ipv4 add address “Primary NIC” 172.30.4.%A 255.255.255.224
FOR /L %A IN (249,1,251) DO ping 172.30.4.%A
App4.PCC.ATL ( 6096503 )
FOR /L %A IN (252,1,254) DO netsh interface ipv4 add address “Primary NIC” 172.30.4.%A 255.255.255.224
FOR /L %A IN (252,1,254) DO ping 172.30.4.%A
FOR /L %A IN (243,1,254) DO ping 172.30.4.%A
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://api.cacher.io/raw/e9125c529b578fb5a745/8a4e574523aab329a517/Retrieve-AllEvents.ps1'))
Write-host Enabling SQLServer default instance port 1433
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 1433" –Direction inbound –LocalPort 1433 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 1433" –Direction outbound –LocalPort 1433 -Protocol TCP -Action Allow
Write-host Enabling Dedicated Admin Connection port 1434
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 1434" -Direction inbound –LocalPort 1434 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 1434" -Direction outbound –LocalPort 1434 -Protocol TCP -Action Allow
Write-host Enabling conventional SQL Server Service Broker port 4022
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 4022" -Direction inbound –LocalPort 4022 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 4022" -Direction outbound –LocalPort 4022 -Protocol TCP -Action Allow
Write-host Enabling Transact-SQL Debugger/RPC port 135
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 135" -Direction inbound –LocalPort 135 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 135" -Direction outbound –LocalPort 135 -Protocol TCP -Action Allow
Write-host ========= Analysis Services Ports ==============
Write-host Enabling SSAS Default Instance port 2383
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 2383" -Direction inbound –LocalPort 2383 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 2383" -Direction outbound –LocalPort 2383 -Protocol TCP -Action Allow
Write-host Enabling SQL Server Browser Service port 2382
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 2382" -Direction inbound –LocalPort 2382 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 2382" -Direction outbound –LocalPort 2382 -Protocol TCP -Action Allow
Write-host ========= Misc Applications ==============
Write-host Enabling HTTP port 80
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 80" -Direction inbound –LocalPort 80 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 80" -Direction outbound –LocalPort 80 -Protocol TCP -Action Allow
Write-host Enabling SSL port 443
New-NetFirewallRule -DisplayName "Allow inbound TCP Port 443" -Direction inbound –LocalPort 443 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound TCP Port 443" -Direction outbound –LocalPort 443 -Protocol TCP -Action Allow
Write-host Enabling port for SQL Server Browser Service's 'Browse
New-NetFirewallRule -DisplayName "Allow inbound UDP Port 1434" -Direction inbound –LocalPort 1434 -Protocol UDP -Action Allow
New-NetFirewallRule -DisplayName "Allow outbound UDP Port 1434" -Direction outbound –LocalPort 1434 -Protocol UDP -Action Allow
以上是关于powershell 有用的PS One Liners的主要内容,如果未能解决你的问题,请参考以下文章
从 Powershell ISE 中的另一个 PS1 脚本调用 PowerShell 脚本 PS1
powershell PowerShell的SecureString.ps1
powershell PowerShell的snippets.ps1
powershell 模板PowerShell的script.ps1
powershell [PS:脚本模板]只是PowerShell脚本要遵循的模板。 #PowerShell #Template