Tag Archives: Powershell

Credentials in Powershell

http://duffney.io/AddCredentialsToPowerShellFunctions

function Set-RemoteRegistryValue {
    param(
        $ComputerName,
        $Path,
        $Name,
        $Value,
        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty        
    )

    if($Credential -ne [System.Management.Automation.PSCredential]::Empty) {
        Invoke-Command -ComputerName:$ComputerName -Credential:$Credential  {
            Set-ItemProperty -Path $using:Path -Name $using:Name -Value $using:Value
        }
    } else {
        Invoke-Command -ComputerName:$ComputerName {
            Set-ItemProperty -Path $using:Path -Name $using:Name -Value $using:Value
        }
    }
}

Debugging and Breakpoints in Powershell

Write-Debug

As long as a script is an advanced script then you can use Write-Debug.

Write-Debug -Message "Enter debug text here, variables can be included."

The script will pause at each Write-Debug and display the debug text, including any variables. This will display the current content of any variables in the debug text.

To run a script with debugging turned on you must run the script with the debug switch.

.\MyTestSwitch.ps1 -debug

Set-PSBreakpoint

Another method for debugging is to set breakpoints prior to running a script.

Set-PSBreakPoint -Script .\MyTestSwitch.ps1 -Line 5
Set-PSBreakPoint -Script .\MyTestSwitch.ps1 -Variable ComputerName 

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/set-psbreakpoint?view=powershell-6

Removing PS-Breakpoints

Get-PSBreakPoint | Remove-PSBreakPoint

Remoting in PowerShell

INVOKE

invoke-command -ComputerName (get-content C:\temp\TestComputers.txt) -ScriptBlock {get-eventlog -LogName Application -Newest 5}

invoke-command -ComputerName (get-adcomputer -filter *) -ScriptBlock {get-eventlog -LogName Application -Newest 5}

PS C:\temp> Enter-PSSession -ComputerName SGEN-TN01

[SGEN-TN01]: PS C:\Users\admin-its-tn\Documents> get-eventlog -LogName Application -Newest 5

   Index Time          EntryType   Source                 InstanceID Message                                                                                                                 

   —– —-          ———   ——                 ———- ——-                                                                                                                 

    3382 Sep 04 12:05  Information SceCli                 1073743528 Security policy in the Group policy objects has been applied successfully.                                              

    3381 Sep 04 12:05  Information gupdate                         0 The description for Event ID ‘0’ in Source ‘gupdate’ cannot be found.  The local computer may not have the necessary r…

    3380 Sep 04 10:59  Information Windows Error Rep…         1001 Fault bucket 1838438238644566740, type 5…                                                                             

    3379 Sep 04 10:35  Information gupdate                         0 The description for Event ID ‘0’ in Source ‘gupdate’ cannot be found.  The local computer may not have the necessary r…

    3378 Sep 04 10:35  0           Software Protecti…   1073742727 The Software Protection service has stopped….                                                                          

[SGEN-TN01]: PS C:\Users\admin-its-tn\Documents> Exit-PSSession

PS C:\temp> 

Returning just the value in PowerShell

This uses “-expand” or “-expanproperty”

Get-ADComputer -filter -searchbase “ou=domain controllers, dc=company,dc=primary”

…this will return a list of computer OBJECTS from the domain controllers OU.

You cannot use this command as a pipeline return….

Get-Service -computerName (Get-ADComputer -filter -searchbase “ou=domain controllers, dc=company,dc=primary”)

As “-ComputerName” is expecting a string and NOT an object. To resolve this we can use the “-expand” to extract a property……

Get-ADComputer -filter -searchbase “ou=domain controllers, dc=company,dc=primary” | Select-Object -expandproperty Name

So, this would work…..

Get-Service -computerName (Get-ADComputer -filter -searchbase “ou=domain controllers, dc=company,dc=primary” | Select-Object -expandproperty Name)

Get-Process -computerName (import-csv .\computers.csv | select-object -expandproperty hostname)

Syntax in PowerShell

Get-EventLog [-LogName] <String> [[-InstanceId] <Int64[]>] [-After <DateTime>] [-AsBaseObject] [-Before <DateTime>] [-ComputerName <String[]>] [-EntryType {Error | Information | FailureAudit | SuccessAudit | Warning}] [-Index <Int32[]>] [-Message <String>] [-Newest <Int32>] [-Source <String[]>] [-UserName <String[]>]
[<CommonParameters>]
Get-EventLog [-AsString] [-ComputerName <String[]>] [-List] [<CommonParameters>]
  • There are two possible combinations of parameters you can’t mix between them, some commands may have more than 2 sets.
  • Anything in square brackets is optional.
  • If you omit optional parameter names then they MUST be provided in the correct order! (e.g. ‘Get-EventLog Security 10’ is shorthand for  ‘Get-EventLog -LogName Security -InstanceID 10’. ‘Get-EventLog 10 Security’ will not work as there is no Event Log called 10).
[-LogName] <String>
  • The log name is not optional as its not in square brackets but actually writing the word LogName is!
[[-InstanceId] <Int64[]>]
  • Instance ID is optional (the whole thing is in square brackets
  • Writing ‘-InstanceID’ is optional
  • InstanceID expects a 64-bit integer (-9223372036854775808 to 9223372036854775807) and the additional square brackets indicate it will accept and array or list of them
[-List]
  • This is a switch, essentially a parameter without a value
[<CommonParameters>]
  • These are a bunch of parameters available to ALL commands

Alias in PowerShell

Finding the alias of a command:

get-alias -Definition "Get-Service"

Finding the command of an alias

Get-alias gsv
Help gsv

Finding the alias of a parameter (getting the alias of the computername parameter for ‘Get-EventLog’):

(get-command get-eventlog | select -ExpandProperty parameters) .computername.aliases

Finding the parameter of an alias (getting the parameter of the -Cn alias for ‘Get-EventLog’):

get-eventlog -Cn

(this will error with the error displaying the full parameter name of the Alias)