PowerShell Reference Notes
A few notes for reference, some are only available on server editions.
Remember you can use backtick ` for multiline.
Activate execution of scripts
PS C:\> Get-ExecutionPolicy (unrestricted is OK for a closed off host) PS C:\> Set-ExecutionPolicy unrestricted | remotesigned | restricted Or, if deploying to other systems, you can also bypass it as admin: powershell.exe -noprofile -executionpolicy bypass -file .\script.ps1
Handling files based on CreationTime,LastAccessTime,LastWriteTime
PS C:\> fsutil behavior query disablelastaccess ^ May output on Windows 10: DisableLastAccess = 3 (System Managed, Enabled) NOTE: This just means GPO is enabled to take care of it, but disabled. Query the possible values with: PS C:\> fsutil behavior set disablelastaccess ^ Output: 0x0 - User Managed, Updates are Enabled. 0x1 - User Managed, Updates are Disabled. 0x2 - System Managed, Updates are Enabled. 0x3 - System Managed, Updates are Disabled. So via fsutil we can via the user turn it off and on with 1 and 0 respectively. PS C:\> fsutil behavior set disablelastaccess [1 | 0] ^ NOTE: Notice the setting being enabled/disabled vs updates being enabled/disabled. It's easy to confuse one with the other. ENABLING this, will DISABLE updates. It's disabled for performance reasons, but it can be useful for e.g. backup, archival or like this example remove files that have not been accessed for 30 days:Get-ChildItem -Recurse -Path "C:\somepath" | Where-Object { $_.LastAccessTime -lt (Get-Date).AddDays(-30) } | Remove-Item
Windows Update Management
https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc/ Windows 10 should have the PowerShellGet module ready for instant use, it may trigger a few confirmations about also getting the NuGet package manager. With this you can set up PSWindowsUpdate in just a few steps without downloading cmdlets manually. Installing: PS C:\> Install-Module PSWindowsUpdate PS C:\> Get-Command –module PSWindowsUpdate PS C:\> Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d Example usage: PS C:\> Get-WUList –MicrosoftUpdate PS C:\> Get-WUInstall –MicrosoftUpdate –AcceptAll -Install –AutoReboot
Prepare drives for Storage Spaces (CanPool=True)
PS C:\> Get-PhysicalDisk PS C:\> Reset-PhysicalDisk -FriendlyName "FriendlyDiskName"
Scheduled tasks
PS C:\> Get-ScheduledTask (list existing tasks) -- # I'll normally just use server manager / computer management to create the task itself. # But here's a script for adding a daily ps1 script and run it as the SYSTEM service account. $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-executionpolicy bypass c:\path\script.ps1" $trigger = New-ScheduledTaskTrigger -Daily -At 3:01am $principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest Register-ScheduledTask -TaskName "mytask" -TaskPath "\MySpecialTasks" -Action $action -Trigger $trigger -Principal $principal -- Get-ScheduledTask | findstr export-vm UnRegister-ScheduledTask export-vm
Random numbers
PS C:\> 1..100 | Get-Random PS C:\> Get-Random -Minimum 1 -Maximum 100
Turn off automatic updates in Windows Server 2016
PS C:\> sconfig
System language
PS C:\> Set-WinUserLanguageList -LanguageList nb-NO PS C:\> Get-WinUserLanguageList PS C:\> control intl.cpl
Download through web-request
PS C:\> Invoke-WebRequest http://somewebsite.com/somefile.exe -OutFile C:\somewhere\somefile.exe
Roles and features
PS C:\> Get-WindowsFeature PS C:\> Uninstall/Install-WindowsFeature Feature1,Feature2,Role1,etc
Services
PS C:\> Get-Service | findstr Xbox* PS C:\> Stop-Service [servicename] PS C:\> sc.exe delete [servicename]
Enable/Disable Firewall
PS C:\> Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
Enable/Disable Windows Defender
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true
Disable VMQ on Broadcom NICs, on Microsoft host servers
PS C:\> Get-NetAdapterVmq (Get-NetAdapter can also be helpful) PS C:\> Set-NetAdapterVmq -Name "NIC Name" -Enabled $False
Converting 1st to 2nd gen VM (2012 R2 / 8.1 +)
PS C:\> .\Convert-VMGeneration.ps1 -VMName "vm1" -Path D:\ ^ disable replication first, add parameters as needed for success, lots of checks. Download script here (official) or here (my mirror). Tested OK on Hyper-V Server 2016, 01.01.2018.
Setting up Hyper-V remote management without domain
Perform the following steps procedurally: Hyper-V Server 2016 Steps ========================= 1. Enable-PSRemoting (configures private network fw rules) 2. Enable-WSManCredSSP -Role Server (allow access on public zone) 3. winrm quickconfig ('Y' to remote management) 4. Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False (or manage it) Windows 10 Client Steps ======================= 1. Get-NetAdapter (for index number, [n]) 2. Get-NetConnectionProfile (check public,private,domain - should be private) 3. Set-NetConnectionProfile -InterfaceIndex [n] -NetworkCategory Private (if needed) 4. Enable-PSRemoting 5. Set-Item WSMan:\localhost\Client\TrustedHosts -Value * (rel. cmdlets: Clear-Item, Get-Item) 6. Enable-WSManCredSSP -Role Client -DelegateComputer * 7. gpedit.msc > Computer Configuration > > Administrative Templates > > System > > Credentials Delegation > > Allow Fresh Credentials with NTLM-only Server Authentication Enable and add WSMAN/FQDN (add host in %windir%\System32\drivers\etc\hosts) 8. cmdkey /add:testlab1 /user:Administrator /pass:whatever This should open the doors for most of RSAT and Honolulu (requires WMF5+ on the server). Computer Management had problems with device- and disk management access though. WMF 5.1 for 2012 R2: https://go.microsoft.com/fwlink/?linkid=839516 HYPER-V Server 2016 added handy notes: HV > C:\> powercfg /s SCHEME_MIN (or copy and paste output from powercfg /l). HV > C:\> pnputil /add-driver *.inf /subdirs /install (run from driver collection directory) HV > C:\> sc query type=driver (check installed drivers) HV > C:\> net share (may need to Add-WindowsFeature FS-FileServer) HV > C:\> net use /persistent:yes HV > C:\> net use z: \\backupserver\storage /user:backupserver\backup password
Exporting Hyper-V VMs (Live exports if 2012R2 or later, to SAN or DAS)
PS C:\> Export-VM -Name [VM_Name] -Path [path] PS C:\> Get-VM | Export-VM -Path [path] (For exporting all) ^ -ComputerName can be added for remote exporting if RSAT/remote management is set up. Sample script code for automation, adapt as needed: -- # Where to store exports $BackupPath = "D:\Backup" # How many days to keep backups $LimitDays = 2 # Date format $Date = Get-Date -Format yyyyMMddmmss # Remove old backups Get-ChildItem "$BackupPath" -Directory -Recurse | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-$LimitDays)} | Remove-Item -Recurse # Export all VM's (or use -Name for specific ones instead of Get-VM): Get-VM | Export-VM -Path $BackupPath\$Date --
Unplanned failover of a VM in a script
# Do custom sanity checks before failing over (check that primary is down)... PS C:\> $VM = Start-VMFailover -ComputerName localhost -VMName vm1 -PassThru -Confirm:$false PS C:\> Start-VM -VM $VM
Checking drives and their blocksize
PS C:\> Get-CimInstance -ClassName Win32_Volume | Select-Object Label,Name,BlockSize
Measure IOPS, latency, read, write on VM's
# Turn on resource metering for all VM's. PS C:\> Get-VM | Enable-VMResourceMetering # Keep in mind that average IOPS and latency measure spans of 20 seconds. # Data written and read will count while metering is running and enabled. PS C:\> Get-VM | Measure-VM | Select-Object VMName,Aggregated* ^ Output: 4 hours of idle new-install runtime of Microsoft server systems: VMName : GuiWs2012R2test (2 GB RAM, 32 GB) AggregatedAverageNormalizedIOPS : 0 AggregatedAverageLatency : 0 AggregatedDiskDataRead : 35 AggregatedDiskDataWritten : 60 VMName : GuiWs2016test (2 GB RAM, 32 GB) AggregatedAverageNormalizedIOPS : 0 AggregatedAverageLatency : 0 AggregatedDiskDataRead : 88 AggregatedDiskDataWritten : 777 VMName : Hyper2016test (1 GB RAM, 32 GB) AggregatedAverageNormalizedIOPS : 0 AggregatedAverageLatency : 0 AggregatedDiskDataRead : 20 AggregatedDiskDataWritten : 67 (I then removed the Microsoft servers, installed GNU/Linux VM's and then let the GNU/Linux servers idle a total of 8 hours as I went to bed): VMName : CentOs7KvmTest (1 GB RAM, 32 GB) AggregatedAverageNormalizedIOPS : 0 AggregatedAverageLatency : 0 AggregatedDiskDataRead : 1380 AggregatedDiskDataWritten : 532 VMName : Debian9KvmTest (1 GB RAM, 32 GB) AggregatedAverageNormalizedIOPS : 0 AggregatedAverageLatency : 0 AggregatedDiskDataRead : 14 AggregatedDiskDataWritten : 145
Read lines from text files (as ps1 script)
# Read file exceptions. $files = "'"; foreach ($line in Get-Content .\FileExceptions.txt) { $files += $line +' '; } $files = $files.TrimEnd(); $files += "'"; # Use variable. echo $files;
Handle SMB versions on Windows Server 2012 R2 and 2016
SMB v1 Detect: PS C:\> Get-WindowsFeature FS-SMB1 Disable / Enable: PS C:\> Disable-WindowsOptionalFeature -Online -FeatureName smb1protocol PS C:\> Enable-WindowsOptionalFeature -Online -FeatureName smb1protocol SMB v2/v3 Detect: PS C:\> Get-SmbServerConfiguration | Select EnableSMB2Protocol Disable / Enable: PS C:\> Set-SmbServerConfiguration -EnableSMB2Protocol $false PS C:\> Set-SmbServerConfiguration -EnableSMB2Protocol $true
NOTE: SMBv2 also enables v3 on all these systems, they share the same stack.
Handle SMB versions on Windows 8.1 and 10
SMB v1 Protocol Detect/Disable/Enable: PS C:\> Get-WindowsOptionalFeature –Online –FeatureName SMB1Protocol PS C:\> Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol PS C:\> Enable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol SMB v2/v3 Protocol Detect/Disable/Enable: PS C:\> Get-SmbServerConfiguration | Select EnableSMB2Protocol PS C:\> Set-SmbServerConfiguration –EnableSMB2Protocol $false PS C:\> Set-SmbServerConfiguration –EnableSMB2Protocol $true
Repair Windows 10 Image (DISM alternative)
PS C:\> Repair-WindowsImage -Online -RestoreHealth As an alternative to CMD DISM variants (link to ESD to WIM DISM script): C:\> DISM.exe /Online /Cleanup-image /Restorehealth C:\> DISM.exe /Online /Cleanup-image /Restorehealth /source:esd:D:\sources\install.esd:1 /limitaccess