PowerShell Notes
Revision as of 12:16, 30 August 2017 by PeterHarding (talk | contribs)
Path
Powershell.exe
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Get version
$PSVersionTable.PSVersion
Example Scripts
Check in C:\Apps\ps for examples!
Notes
- https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/
- http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily/
PS C:\Scripts> Start-Process cmd -ArgumentList "/c 1.cmd" -WorkingDirectory c:\test
Blah
$installerPath = [IO.Path]::Combine($LocalModulePath, 'Install.ps1') Write-Host "Installer path: $installerPath" if (Test-Path $installerPath) { Write-Host 'Install.ps1 exists. Running Install.ps1' & $installerPath }
Blah
Write-Host "Installing module..." $eventSource = 'My.Module.Manager' try { $sourceExists = [System.Diagnostics.EventLog]::SourceExists($eventSource) } catch [Security.SecurityException] { Write-Verbose "Caught 'SecurityException': $_.Exception.Message" } if ($sourceExists) { Write-Host "...installation complete..." } else { #region ----- Ensure-ProcessIsElevated ----- if ($Verbose) { $VerbosePreference = "Continue" } if ($Debug) { $DebugPreference = "Continue" } Write-Debug "Command line is ___$($MyInvocation.Line)___" Write-Verbose "Entering script body" if ($ScriptPath) { Set-Location $ScriptPath Write-Verbose "Working directory: $pwd" } If (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "This script must be run with elevated privileges." Write-Warning "Restarting as an elevated process." Write-Warning "You will be prompted for authorization." Write-Warning "You may click 'No' and re-run manually, if you prefer." If ((Get-WmiObject Win32_OperatingSystem | select BuildNumber).BuildNumber -ge 6000) { Write-Verbose "This is a UAC-enabled system. Elevating ..." $CommandLine = "$($MyInvocation.Line.Replace($MyInvocation.InvocationName, $MyInvocation.MyCommand.Definition)) -ScriptPath $pwd" Write-Verbose "CommandLine: $CommandLine" Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList "$CommandLine" } else { Write-Verbose "The system does not support UAC: an elevated process cannot be started." Write-Warning "This script requires administrative privileges. Please re-run with administrative account." } Break } Write-Verbose "The script is now running with elevated privileges." #endregion ----- Ensure-ProcessIsElevated ----- New-EventLog -LogName Application -Source $eventSource Write-Host "...installation complete..." } Read-Host -Prompt "Press Enter to exit"
Blah
Blah
Write-Output "Backups complete at $(Get-Date -Format u)"
Blah
try { # Do your script's stuff } catch { Write-Error $_.Exception.ToString() Read-Host -Prompt "The above error occurred. Press Enter to exit." }
Blah
function Log-Message { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [string]$LogMessage ) Write-Output ("{0} - {1}" -f (Get-Date), $LogMessage) }
Now you can simple log using:
Log-Message "Starting Backups" Log-Message "Backups Completed"
Output:
22.07.2016 08:31:15 - Starting Backups 22.07.2016 08:31:15 - Backups Completed
To Change Directory:
Set-Location -Path Q:\MyDir
Blah:
Remove-EventLog -Source 'My.Module.Manager'
https://stackoverflow.com/questions/7834656/create-log-file-in-powershell
Put this at the top of your file:
$Logfile = "D:\Apps\Logs\$(gc env:computername).log" Function LogWrite { Param ([string]$logstring) Add-content $Logfile -value $logstring }
Then replace your Write-host calls with LogWrite.
OR:
Function Write-Log { [CmdletBinding()] Param( [Parameter(Mandatory=$False)] [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")] [String] $Level = "INFO", [Parameter(Mandatory=$True)] [string] $Message, [Parameter(Mandatory=$False)] [string] $logfile ) $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss") $Line = "$Stamp $Level $Message" If($logfile) { Add-Content $logfile -Value $Line } Else { Write-Output $Line } } . .\logger.ps1 Write-Log "debug message" Write-Log "info message" "INFO"
Using this Log-Entry framework:
Script:
Function Main { Log -File "D:\Apps\Logs\$Env:computername.log" $tcp = (get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductVersionRaw $dfs = (get-childitem C:\Windows\Microsoft.NET\Framework\v2.0.50727\dfsvc.exe).Versioninfo.ProductVersionRaw Log "TCPIP.sys Version on $computer is:" $tcp Log "DFSVC.exe Version on $computer is:" $dfs If (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {Log "The REMINST share exists on $computer"} Else {Log "The REMINST share DOES NOT exist on $computer - Please create as per standards"} "KB2450944", "KB3150513", "KB3176935" | ForEach { $hotfix = Get-HotFix -Id $_ -ErrorAction SilentlyContinue If ($hotfix) {Log -Color Green Hotfix $_ is installed} Else {Log -Color Red Hotfix $_ " is NOT installed - Please ensure you install this hotfix"} } }