Differences between revisions 1 and 27 (spanning 26 versions)
Revision 1 as of 2018-09-26 21:11:43
Size: 373
Editor: scot
Comment:
Revision 27 as of 2020-06-11 14:20:40
Size: 5543
Editor: scot
Comment:
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:

<<TableOfContents>>

For the uninitiated:

|| Symbol || Meaning ||
|| % || shortcut for foreach object ||
|| $_ || current object in the pipeline ||
|| Get-Member || Will list the fields of the object you send it ||
|| Sort-Object -Property [property name] || Will sort the objects you send in by the property name(s) which can be a comma separated list ||
|| Where-Object {$_.property -like '*string*'} || Will filter the objects. Also short cut notation: ? {$_.property -like '*string*'} ||
|| Get-Command -Module PSWindowsUpdate || Lists all the commands in the PSWindowsUpdate module ||

= Windows and AD Scripts =

== Expand all zip files into directories with zip name ==

{{{#!highlight powershell
$list = Get-ChildItem | ? { $_.Name -like "*.zip" } | select Name
foreach ($line in $list) {
    $parts = $line.Name.Split(".")
    $outDir = ".\" + $parts[0]
    $inFile = $line.Name
    mkdir $outDir
    Expand-Archive $inFile -DestinationPath $outDir
}
}}}


== List of Listening Ports with their owning programs ==

{{{#!highlight powershell
$listening = (Get-NetTCPConnection | ? {($_.State -eq "Listen") -and ($_.RemoteAddress -eq "0.0.0.0")})
foreach ($l in $listening) {
    $procid = $l.OwningProcess
    $proc = Get-Process -PID $procid | SELECT ID,ProcessName
    Write-Host $($l.LocalPort) "||" $($procid) "||" $proc.ProcessName
}
}}}
Line 5: Line 44:
{{{
Get-ADUser -Filter * -SearchBase "dc=home,dc=scotnpatti,dc=com" -ResultPageSize 0 -Prop CN,samaccountname,lastLogonTimestamp | select CN, samaccountname,@{n="lastLogonDate";e={[datetime]::FromFileTime($_.LastLogonTimestamp)}}
{{{#!highlight powershell
Get-ADUser -Filter * -SearchBase "dc=home,dc=scotnpatti,dc=com" -ResultPageSize 0 -Prop CN,samaccountname,lastLogonTimestamp |       select CN, samaccountname,@{n="lastLogonDate";e={[datetime]::FromFileTime($_.LastLogonTimestamp)}}
Line 8: Line 48:

== List Memory Installed ==

{{{#!highlight powershell
Get-WmiObject win32_physicalmemory | Format-Table Manufacturer,Banklabel,Configuredclockspeed,Devicelocator,Capacity,Serialnumber -autosize
}}}


== List object from Registry - namely version of .NET installed ==

{{{#!highlight powershell
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' | sort pschildname -des | foreach-object {$_.name; $_.GetValue("Version");}
}}}

== Remote commands ==

{{{#!highlight powershell
Invoke-Command -ComputerName eve -ScriptBlock { date }
}}}

== Replace a string in a file using a regular expression ==

So I downloaded a bunch of files from "the way back machine" site and I needed to update the hard-coded links to be relative site links. The following little script did it for me.

{{{#!highlight powershell

$files = ls Level*.html
foreach ($item in $files) {
    (Get-Content -path $item) | % { $_ -Replace '(https://web.archive.org/nebula/level)([0123456789]{2})/', 'Level$2.html' } | Set-Content $item
}

}}}

== Adding DNS records to Windows DNS - For CPTR 446 class ==

{{{#!highlight powershell
Import-Csv googleips.csv | ForEach-Object {
    Add-DnsServerResourceRecordA -Name $_.DNSName -ComputerName dc1.cs.southern.edu -ZoneName cs.southern.edu $_.IP
}
}}}

= SCVMM Powershell scripts =


I needed this once when I was trying to refresh the Library share. It failed on refresh with an error saying that a DVD was in use and wouldn't refresh until it was no longer in use. The following commands allowed me to identify the machines.

In general all of these need:

{{{#!highlight powershell
Import-Module VirtualMachineManager
}}}

== Get a list of Virtual Machines that have a DVD attached ==

{{{#!highlight powershell
Get-SCVMMServer -ComputerName Samuel
Get-SCVirtualMachine | Get-SCVirtualDVDDrive | Where-Object {$_.Connection -eq "ISOImage"} | Select Name, Connection, ISO
}}}

== List VMs at the end of the semester to be deleted ==

{{{#!highlight powershell
Get-SCVirtualMachine | Select Name, MarkedAsTemplate, Owner | Sort-Object -Property Owner, Name | Export-Csv -Path .\vms2019w.csv
}}}

== Get a list of VM Mac Addresses for CPTR 427 ==

{{{#!highlight powershell
Get-SCVirtualMachine | Where-Object { $_.Name -like "*427*" } | select -ExpandProperty VirtualNetworkAdapters | select MacAddress
}}}

== Setting up a Windows 2019 Server for the first time ==

{{{#!highlight powershell
# Install the AVMA key.
slmgr /ipk TNK62-RXVTB-4P47B-2D623-4GF74

# Set the timezone
# First I'm going to search for the timezone I want
Get-TimeZone -ListAvailable | Where-Object {$_.DisplayName -like '*Eastern*'}
# This gave me the parameter needed to set the time zone.
Set-TimeZone -Name "Eastern Standard Time"

# Set the Hostname of the computer:
Rename-Computer -NewName "windows2019" -Restart

# Next we need to install Windows update and get it started.
# This will install nuget package too.
Install-Module PSWindowsUpdate

# Now start the update process
# First we'll look at what updates are there
Get-WUInstall
# Now install them
Install-WindowsUpdate
}}}

== Power shell to list of VM hard drives sizes ==

{{{#!highlight powershell
$vms = Get-SCVirtualDiskDrive -all
foreach ($v in $vms)
{
    $d = $v | select -ExpandProperty VirtualHardDisk
    Write-Output "$($v.Name), $($d.Size)"
}
}}}

== List the amount of memory used by virtual machines ==

{{{#!highlight powershell
Get-SCVirtualMachine | ForEach-Object { $size += $_.Memory }
}}}

Resources:

 * [[https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc#content|Powershell and Windows Update]]

Here is a list of Power Shell Scripts that are too cool to ignore

For the uninitiated:

Symbol

Meaning

%

shortcut for foreach object

$_

current object in the pipeline

Get-Member

Will list the fields of the object you send it

Sort-Object -Property [property name]

Will sort the objects you send in by the property name(s) which can be a comma separated list

Where-Object {$_.property -like '*string*'}

Will filter the objects. Also short cut notation: ? {$_.property -like '*string*'}

Get-Command -Module PSWindowsUpdate

Lists all the commands in the PSWindowsUpdate module

Windows and AD Scripts

Expand all zip files into directories with zip name

   1 $list = Get-ChildItem | ? { $_.Name -like "*.zip" } | select Name
   2 foreach ($line in $list) {
   3     $parts = $line.Name.Split(".")
   4     $outDir = ".\" + $parts[0]
   5     $inFile = $line.Name
   6     mkdir $outDir
   7     Expand-Archive $inFile -DestinationPath $outDir 
   8 }

List of Listening Ports with their owning programs

   1 $listening = (Get-NetTCPConnection | ? {($_.State -eq "Listen") -and ($_.RemoteAddress -eq "0.0.0.0")})
   2 foreach ($l in $listening) {
   3     $procid = $l.OwningProcess
   4     $proc = Get-Process -PID $procid | SELECT ID,ProcessName
   5     Write-Host $($l.LocalPort) "||" $($procid) "||" $proc.ProcessName
   6 }

List of AD accounts and the last time they logged in

   1 Get-ADUser -Filter * -SearchBase "dc=home,dc=scotnpatti,dc=com" -ResultPageSize 0 -Prop CN,samaccountname,lastLogonTimestamp | 
   2      select CN, samaccountname,@{n="lastLogonDate";e={[datetime]::FromFileTime($_.LastLogonTimestamp)}} 

List Memory Installed

   1 Get-WmiObject win32_physicalmemory | Format-Table Manufacturer,Banklabel,Configuredclockspeed,Devicelocator,Capacity,Serialnumber -autosize

List object from Registry - namely version of .NET installed

   1 gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' | sort pschildname -des | foreach-object {$_.name; $_.GetValue("Version");}

Remote commands

   1 Invoke-Command -ComputerName eve -ScriptBlock { date }

Replace a string in a file using a regular expression

So I downloaded a bunch of files from "the way back machine" site and I needed to update the hard-coded links to be relative site links. The following little script did it for me.

   1 $files = ls Level*.html
   2 foreach ($item in $files) {
   3     (Get-Content -path $item) | % { $_ -Replace '(https://web.archive.org/nebula/level)([0123456789]{2})/', 'Level$2.html' } | Set-Content $item
   4 } 

Adding DNS records to Windows DNS - For CPTR 446 class

   1 Import-Csv googleips.csv | ForEach-Object {
   2     Add-DnsServerResourceRecordA -Name $_.DNSName -ComputerName dc1.cs.southern.edu  -ZoneName cs.southern.edu $_.IP
   3 }

SCVMM Powershell scripts

I needed this once when I was trying to refresh the Library share. It failed on refresh with an error saying that a DVD was in use and wouldn't refresh until it was no longer in use. The following commands allowed me to identify the machines.

In general all of these need:

   1 Import-Module VirtualMachineManager

Get a list of Virtual Machines that have a DVD attached

   1 Get-SCVMMServer -ComputerName Samuel
   2 Get-SCVirtualMachine | Get-SCVirtualDVDDrive | Where-Object {$_.Connection -eq "ISOImage"} | Select Name, Connection, ISO

List VMs at the end of the semester to be deleted

   1 Get-SCVirtualMachine | Select Name, MarkedAsTemplate, Owner | Sort-Object -Property Owner, Name | Export-Csv -Path .\vms2019w.csv

Get a list of VM Mac Addresses for CPTR 427

   1 Get-SCVirtualMachine | Where-Object { $_.Name -like "*427*" } | select -ExpandProperty VirtualNetworkAdapters | select MacAddress

Setting up a Windows 2019 Server for the first time

   1 # Install the AVMA key.
   2 slmgr /ipk TNK62-RXVTB-4P47B-2D623-4GF74
   3 
   4 # Set the timezone 
   5 #  First I'm going to search for the timezone I want
   6 Get-TimeZone -ListAvailable | Where-Object {$_.DisplayName -like '*Eastern*'}
   7 #  This gave me the parameter needed to set the time zone. 
   8 Set-TimeZone -Name "Eastern Standard Time"
   9 
  10 # Set the Hostname of the computer:
  11 Rename-Computer -NewName "windows2019" -Restart
  12 
  13 # Next we need to install Windows update and get it started.
  14 # This will install nuget package too.
  15 Install-Module PSWindowsUpdate
  16 
  17 # Now start the update process
  18 #   First we'll look at what updates are there
  19 Get-WUInstall 
  20 #   Now install them
  21 Install-WindowsUpdate

Power shell to list of VM hard drives sizes

   1 $vms = Get-SCVirtualDiskDrive -all
   2 foreach ($v in $vms)
   3 {
   4     $d = $v | select -ExpandProperty VirtualHardDisk
   5     Write-Output "$($v.Name), $($d.Size)"
   6 }

List the amount of memory used by virtual machines

   1 Get-SCVirtualMachine | ForEach-Object { $size += $_.Memory }

Resources:

WindowsAdministration/PowerShellScripts (last edited 2024-02-06 23:03:14 by scot)