ridicurious.com
Powershell

PowerShell Interview Questions

list of around 50+ Important PowerShell Interview Questions, Resources, Topics and Tips that I’ve collated from my own personal interview experience in Windows PowerShell Scripting and Automation space, which I do a lot! Just to stay in touch with basics and keeping my preparation in tune. This is not a constant list and will grow and get updated on frequent basis and if you feel like adding some questions or topics, feel free to do a Pull Request on the Github Repository  for this.

Many of the topics/questions may not come directly in your interview, but it would be a good idea to familiarize with them, in order to understand PowerShell better. Which will give you an edge in the interview and definitely leave a better impression on the interviewer if these topics are explained well.

Whole purpose of this list is to give you one stop for important topics and questions that can help you in an PowerShell interview, I have used this list in last minute revisions, or preparing for interviews scheduled next day and it has served me well! hoping same for you 🙂

 

PowerShell InterviewQuestions & Topics

What is PowerShell?


How does PowerShell differ from other scripting languages

TBD


PowerShell versions and differences

TBD


Execution Policies

Types of Execution Policy?

There are 6 types of execution policies

1. Restricted

This is the default. PowerShell will not run any script, including PowerShell profiles.

2. RemoteSigned

PowerShell will run any script that you create locally. But any script that has been detected as coming from the Internet, such as via Internet Explorer, Microsoft Outlook, Mozilla Firefox or Google Chrome must be digitally signed with a code signing certificate that is trusted by the computer.

3. AllSigned

PowerShell will not run any script unless it has been digitally signed with a trusted code signing certificate.

4. Unrestricted

PowerShell will make no attempts to hinder script execution and will run any script. If the script comes from an untrusted source, like the Internet, you will be prompted once to execute it. Though it is not preferred.

5. Bypass

There is also a Bypass policy, which I don’t recommend for daily use. This policy will run any script without question or prompting. The assumption is that you have taken steps outside of Nothing is blocked and there are no warnings or prompts.PowerShell to verify the safety and integrity of the script.

6. Undefined

There is no execution policy set in the current scope. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy.

What is the order in which execution policy is evaluated ?

Windows PowerShell determines the effective policy by evaluating the execution policies in the following precedence order –

  1. Group Policy: Computer Configuration
  2. Group Policy: User Configuration
  3. Execution Policy: Process (or PowerShell.exe -ExecutionPolicy) – CURRENT SCOPE
  4. Execution Policy: CurrentUser – SAVED in HKCU registry
  5. Execution Policy: LocalMachine – SAVED in HKLM registry

CIM vs WMI

Old WMI New WMI CIM
Stands for Windows Management Instrumentation Stands for Windows Management Instrumentation Stand for Common Information Model
Old WMI is Microsoft’s initial implementation of CIM New WMI was released with WMF v3 in 2012 which was compliant to new CIM standards Vendor-neutral, industry standard way of representing management information
Developed by MicroSoft Developed by MicroSoft Developed by the DMTF
Since PowerShell v1 Introduced in PowerShell v3
Microsoft used DCOM (Distributed COM) / RPCs (Remote Procedure Calls) Uses WSMan and no more DCOM errors Uses WSMan, a standard developed by DMTF
Windows only Windows only Any platform
Get-WMIObject Get-CimInstance, Get-CimClass, Invoke-CimMethod No cmdlets
More or less deprecated and you’re connected to LIVE objects and can play with them Not connected to LIVE objects, stateless relationship with the remote machine
RPC port- 135 WSMan Port – 5985 (HTTP), 5986(HTTPS) WSMan Port – 5985 (HTTP), 5986(HTTPS)

Old WMI

New WMI

OMI

CIM

Area of confusion

In 2012 with Windows Management Framework 3, Microsoft releases a new version of WMI. They fail to give it a unique name, which causes a lot of confusion, but it complies with all the latest CIM specifications.

The PowerShell cmdlets that uses this new WMI has CIM in their noun part of the cmdlet, like Get-CimInstance, Get-CimClass, Invoke-CimMethod But these aren’t CIM because CIM isn’t a protocol. They’re talking WS-MAN, which is what the new CIM standard specifies.

Credits:


WinRM and WSMan and DCOM

WSMan

WinRM

DCOM


Automatic variables

Some very common Automatic Variables

$$ – Contains the last token in the last line received by the session.

$? – Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

$^ – Contains the first token in the last line received by the session.

$_ – Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$Args – Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

$Error – Contains an array of error objects that represent the most recent errors. The most recent error is the first error object in the array ($Error[0]).

$ForEach – Contains the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. This variable exists only while the ForEach loop is running; it is deleted after the loop is completed. For detailed information

$Home – Contains the full path of the user’s home directory. This variable is the equivalent of the %homedrive%%homepath% environment variables, typically C:\Users<UserName>.

$OFS – $OFS is a special variable that stores a string that you want to use as an output field separator . Use this variable when you are converting an array to a string. By default, the value of $OFS is ” “, but you can change the value of $OFS in your session, by typing $OFS=”<value>”. If you are expecting the default value of ” ” in your script, module, or configuration output, be careful that the $OFS default value has not been changed elsewhere in your code.

$PID – Contains the process identifier (PID) of the process that is hosting the current Windows PowerShell session.

$Profile – Contains the full path of the Windows PowerShell profile for the current user and the current host application. You can use this variable to represent the profile in commands. For example, you can use it in a command to determine whether a profile has been created

Know more:

Get-Help about_Automatic_Variables

What is Splatting?

Use a hash table to splat parameter name and value pairs. You can use this format for all parameter types, including positional and named parameters and switch parameters.

$HashArguments = @{
  Path = "test.txt"
  Destination = "test2.txt"
  WhatIf = $true
}
Copy-Item @HashArguments

$Using variable

For using Local variables in remote sessions

$ps = "Windows PowerShell"
Invoke-Command -ComputerName S1 -ScriptBlock {
  Get-WinEvent -LogName $Using:ps
}

How to map Network Drives using PowerShell? and persist them


How to form credentials objects in PowerShell?

$UserName = 'Prateek'
$Password = 'Password@123' | ConvertTo-SecureString -AsPlainText -Force

# method 1
[pscredential]::new($Username,$Password)

# method 2
New-Object System.Management.Automation.PSCredential($UserName,$Password)

How to find installed applications on a Windows Computer?

Use the Get-ItemProperty cmlet to pull installed softwares from the registries. Searching the registry is a lot faster and can return some other useful information information such as the UninstallString.

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

You should AVOID using below WMI Query to Win32_Product class as it will as it trigger a consistency check on all installed products, as mentioned in following 2 articles

Get-WmiObject -Class Win32_Product | Format-wide -column 1

How to identify if a windows machine is 32/64 bit?

# method 1
$env:PROCESSOR_ARCHITECTURE

# method 2
[Environment]::Is64BitOperatingSystem

# method 3
gwmi win32_operatingsystem | select osarchitecture

# method 4
(wmic os get osarchitecture)[2]

How to find operating system name/version?

 (Get-WmiObject Win32_OperatingSystem).Name
 (Get-WmiObject Win32_OperatingSystem).caption

What is String Interpolation in PowerShell

TBD


#Require statement

#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -PSEdition <PSEdition-Name>
#Requires -ShellId <ShellId>

Parameter Binding

By Value

Get-Service bits | Stop-Service

Data-Type/ TypeName of the object decides if it will bind to a function or cmdlet, If you look closely in the help file of the cmdlet, the InputObject accepts ServiceController[] objects from pipeline – Accept pipeline input? True (ByValue)

PS C:\> Get-Help Stop-Service -Parameter inputobject

-InputObject <ServiceController[]>
    Specifies ServiceController objects that represent the services to stop. Enter a variable that contains the objects, or type a command or expression that gets the objects.

    Required?                    true
    Position?                    0
    Default value                None
    Accept pipeline input?       True (ByValue)
    Accept wildcard characters?  false

By PropertyName

$obj = [PSCustomObject]@{
    Name = 'icmp'
    Value = 'ping'
}

$obj | New-Alias -verbose

Binds parameter on basis of names of the property of the objects coming form the pipeline, you can check these properties like in the following example

PS C:\> Get-Help New-Alias -Parameter Name

-Name <String>
    Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number.

    Required?                    true
    Position?                    0
    Default value                None
    Accept pipeline input?       True (ByPropertyName)
    Accept wildcard characters?  false

PS C:\> Get-Help New-Alias -Parameter Value

-Value <String>
    Specifies the name of the cmdlet or command element that is being aliased.

    Required?                    true
    Position?                    1
    Default value                None
    Accept pipeline input?       True (ByPropertyName)
    Accept wildcard characters?  false

Parameter binding order

  1. ByValue with same Type (No Coercion)
  2. ByPropertyName with same Type (No Coercion)
  3. ByValue with type conversion (Coercion)
  4. ByPropertyName with type conversion (Coercion)

 


Powershell Pipelines

Trace-Command -name ParameterBinding -expression {
    Get-Service BITS | Stop-Service
} -pshost

Credits:


Powershell Scopes

Global

Local

Script

Private

Credits:


Powershell Workflows

  1. Persist
  2. Parallelism
    • Parallel
    • Foreach -Parallel
  3. Sequence
  4. InlineScript

How to extend a Boot Partition using PowerShell?

$part = Get-Partition |? {$_.isboot}
$size = Get-PartitionSupportedSize -DriveLetter $part.DriveLetter
Resize-Partition -DriveLetter $part.DriveLetter -Size $size.SizeMax -Verbose

How to write PowerShell scripts that can withstand reboots or Interruptions?


How to find free space on a drive using PowerShell?

PS C:\> Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
Alias                                  Alias
C                 294.11        623.80 FileSystem    C:\
Cert                                   Certificate   \
D                                      FileSystem    D:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan


PS C:\> gwmi win32_logicaldisk


DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 669797478400
Size         : 985600299008
VolumeName   : OS

DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    :
Size         :
VolumeName   :



PS C:\> Get-CimInstance cim_logicaldisk

DeviceID DriveType ProviderName VolumeName Size         FreeSpace
-------- --------- ------------ ---------- ----         ---------
C:       3                      OS         985600299008 669796954112
D:       5


PS C:\> Get-Volume

DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining      Size
----------- ------------ -------------- --------- ------------ ----------------- -------------      ----
C           OS           NTFS           Fixed     Healthy      OK                     623.8 GB 917.91 GB
            Image        NTFS           Fixed     Healthy      OK                    554.41 MB  11.07 GB
                         NTFS           Fixed     Healthy      OK                    334.54 MB    865 MB
            DELLSUPPORT  NTFS           Fixed     Healthy      OK                    539.16 MB   1.07 GB
            ESP          FAT32          Fixed     Healthy      OK                    433.32 MB    496 MB
D                        Unknown        CD-ROM    Healthy      Unknown                     0 B       0 B

Powershell adaptive systems

PowerShell does not have support for creating types directly, but instead favors monkey patching using PowerShell’s Adaptive Type System (ATS) to add variables, properties, methods, and ScriptBlocks to a PSObject instance.


Out-Host vs Write-Output vs Write-Host

TBD


Number of ways to create an Object in PowerShell

# 1. Using Hashtables
[pscustomobject]@{
    firstname = 'Prateek'
    lastname =  'Singh'
}

# 2. Using Select-Object
Select-Object @{n='firstname';e={'Prateek'}},@{n='lastname';e={'Singh'}} -InputObject ''

# 3. Using New-Object and Add-memeber
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name firstname -Value 'Prateek'
$obj | Add-Member -MemberType NoteProperty -Name lastname -Value 'Singh'

# 4. Using New-Object and hashtables
$properties = @{
    firstname = 'Prateek'
    lastname = 'Singh'
}       
$o = New-Object psobject -Property $properties; $o

 


How to Rename a Variable?

PS C:\> $a = 1..3
PS C:\> $a
1
2
3
PS C:\> Rename-Item -Path variable:a -NewName b
PS C:\> $b
1
2
3

How to find the Largest File in a Folder?

PS C:\> Get-ChildItem C:\Data\Powershell\PoshBot\ -recurse | Sort-Object Length -desc | Select-Object -f 1


    Directory: C:\Data\Powershell\PoshBot\PoshBot\en-US


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        4/19/2018  12:37 AM          97648 PoshBot-help.xml

Return vs Write-Output in a Function

TBD


Modules vs Snap-ins

Modules Snap-ins
A package that contains Windows PowerShell commands in form of functions, cmdlets etc. Are compiled cmdlets in to a DLL written in a .Net language
Can be imported directly Requires Installation, with Admin privileges
Extension: .psm1 Extension: .dll
New Deprecated
Get-Module -ListAvailable Get-PSSnapin -Registered
Stored in $env:PSModulePath Stored in registry: hklm:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\
Import-Module [name] Add-PSSnapIn [name] adds the PSSnapIn to the PowerShell Session

What is a Filter?

A filter is a function that just has a process scriptblock

PS C:\> filter myFilter {
         $_
 }
PS C:\> @(1,2,3) | myFilter
1
2
3

Other ways to use filters

function myFunction {
    $Input
}

Function myFunction {
    Process { $_ }
}

How to reverse order of a String

# Method 1
$a='String'.tochararray();  [array]::Reverse($a)

# Method 2
$a = '';for($i=$($Str.Length-1);$i -ge 0;$i--){$a+=$Str[$i]} ; $a

# Method 3
$str[$($str.Length-1)..0] -join ''

How to save credentials in your PowerShell Scripts

$user = "UserName"
$password = 'Password@123'| ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, ($password | ConvertTo-SecureString)

How to take Passwords input from users in a secure way?

Read-Host -AsSecureString

What is cryptographic algorithm used in ConvertTo-SecureString ?

  1. AES – Advanced Encryption Standard
  2. DPAPI – WIndows Data Protection API is used to encrypt your strings

Credits:


Explain what is the function of $input variable?


What is $_ and $PSItem variable

Both represents the Current object in pipeline


What are two ways of extending PowerShell?

PSSnapins
Modules

You have a script which uses Read-Host to prompt the user for an IP address. You need to make sure the user inputs a valid IP address. How would you do that ?

  1. Splitting the address in 4 elements and try to cast them to a [byte]
  2. A regular expression [regex]
  3. Cast the input string to the [System.Net.IPAddress] class

Advanced Functions

function foo {
[cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$True)]
        [string]$Name)
 
    Begin {}
    Process{
            write-verbose $Name
            }
    End{}
}

Credits:


PowerShell Output Streams

Stream Number Contents Usage Comments
Output 1 Output from commands Write-Output “Write-Output message” Default stream, all o/p goes to this stream even the end of pipeline
Error 2 Error messages Write-Error “Write-Error message”
Warning 3 Warning messages Write-Warning “Write-Warning message”
Verbose 4 Verbose output Write-Verbose “Write-Verbose message”
Debug 5 Debug messages Write-Debug “Write-Debug message”
Information 6 General information Write-Information “Write-Information” Since PowerShell v5

Stream Redirection

1-6 : Choice of PowerShell Streams
>   : Redirection operator
>>  : Redirect and append
&   : Adding PowerShell Streams
*   : All Streams

Examples –

3>&1    - Sends warnings (3) and Success output (1) stream
4>&1    - Sends verbose output (4) and success output (1)
*>&1    - Sends all output streams to Output Stream (1)

Credits:


Out* cmdlets

Cmdlet Functionality
Out-Host is the default when you don’t specify anything else
Out-Default In reality, the Out-Host portion of that is unnecessary, because Windows PowerShell has the Out-Default cmdlet hardcoded into the end of the pipeline. That cmdlet simply forwards things to Out-Host
Out-Printer sends output to a printer.
Out-File sends output to a file
Out-Grid Displays your objects in a graphical table with click-to-sort column headers and a search/filter box to help locate specific results
Write-Output Sends output to the pipeline

CredSSP issues in PowerShell and workarounds

Double Hop Issue

PowerShell remoting to connect to Server-1 which then attempts to connect from Server-1 to Server-2 but the second connection fails, this is a Double Hop issue.

Because, PSRemoting authenticates via Network Logon which works by showing possession of the credential, but since remote server doesn’t have the credential, it fails! the second Hop Server-1 to Server-2.

Workaround

# On client machine, from where you do the PowerShell Remoting
Enable-WSManCredSSP –Role Client –DelegateComputer Server2.ridicurious.com -Force

# Checking
Get-WSManCredSSP

# On Server
Enable-WSManCredSSP –Role Server -Force

# Usage - Make sure to use CredSSP Authentication
Enter-PSSession –ComputerName Server2.ridicurious.com –Credential RidiCurious\administrator –Authentication CredSSP

CAUTION

What is CredSSP

Credits


PowerShell Remoting ( PSRemoting )

Architecture

Credits:
https://github.com/devops-collective-inc/secrets-of-powershell-remoting/blob/master/manuscript/remoting-basics.md

How to enable PSRemoting on a server?

Server Side

Enable-PSRemoting -Force

# The asterisk is a wildcard symbol for all PCs. If instead you want to restrict computers that can connect, you can replace the asterisk with a comma-separated list of IP addresses or computer names for approved PCs.

Set-Item wsman:\localhost\client\trustedhosts *
        
# After running that command, you’ll need to restart the WinRM service so your new settings take effect. Type the following cmdlet and then hit Enter:

Restart-Service WinRM

Client Side

Set-Item wsman:\localhost\client\trustedhosts *

Testing the PSRemoting

Test-WSMan

or, you can run Get-PSSessionConfiguration cmdlet to see the PowerShell configurations

PS C:\> Get-PSSessionConfiguration


Name          : microsoft.powershell
PSVersion     : 5.1
StartupScript :
RunAsUser     :
Permission    : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users
                AccessAllowed

Name          : microsoft.powershell.workflow
PSVersion     : 5.1
StartupScript :
RunAsUser     :
Permission    : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed

Name          : microsoft.powershell32
PSVersion     : 5.1
StartupScript :
RunAsUser     :
Permission    : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users
                AccessAllowed

Remoting Returns Deserialized Data

What is Implicit remoting?

PS C:\> $s = New-PSSession -ComputerName Server01
PS C:\> Import-Module -PSSession $s PSWorkflow
PS C:\> Get-Module

ModuleType Name                ExportedCommands
---------- ----                ----------------
Manifest  Microsoft.PowerShell.Management   {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest  Microsoft.PowerShell.Utility    {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script   PSScheduledJob           {Add-JobTrigger, Disable-JobTrigger, Disable-ScheduledJob, Enable-Job...

The proxy commands look like the real commands, but they’re functions, NOT Cmdlets.

PS C:\> Get-Command -Module PSScheduledJob

CommandType   Name                        ModuleName
-----------   ----                        ----------
Function    Add-JobTrigger                PSScheduledJob
Function    Disable-JobTrigger            PSScheduledJob
Function    Disable-ScheduledJob          PSScheduledJob
Function    Enable-JobTrigger             PSScheduledJob
Function    Enable-ScheduledJob           PSScheduledJob
Function    Get-JobTrigger                PSScheduledJob
Function    Get-ScheduledJob              PSScheduledJob
Function    Get-ScheduledJobOption        PSScheduledJob
Function    New-JobTrigger                PSScheduledJob
Function    New-ScheduledJobOption        PSScheduledJob
Function    Register-ScheduledJob         PSScheduledJob
Function    Remove-JobTrigger             PSScheduledJob
Function    Set-JobTrigger                PSScheduledJob
Function    Set-ScheduledJob              PSScheduledJob
Function    Set-ScheduledJobOption        PSScheduledJob
Function    Unregister-ScheduledJob       PSScheduledJob

Try, Catch, Finally

Credits:


Errors

* terminating, non-terminating errors
* throw
* Write-error    
* $ErrorActionVariable, -ErrorAction parameter

SOAP and REST API

SOAP REST
SOAP stands for Simple Object Access Protocol REST stands for Representational State Transfer
SOAP has been around a while REST is a newcomer and fixes few problems with SOAP
Relies exclusively on XML Can also use other smaller message/data formats like JSON, CSV or even RSS
Have to use XML for requests by making RPC calls, and response if received in XML as well REST relies on a simple URL in many cases
Slow, requires bandwidth Fast – lighter weight alternative
In-Built error handling NA
SOAP is a protocol. SOAP was designed with a specification. It includes a WSDL (Web Service Definition Language) file which has the required information on what the web service does in addition to the location of the web service. REST is an Architectural style in which a web service can only be treated as a RESTful service if it follows the constraints of being Client ,Server, Stateless, Cacheable, Layered System, Uniform Interface
SOAP cannot make use of REST since SOAP is a protocol and REST is an architectural pattern. REST can make use of SOAP as the underlying protocol for web services, because in the end it is just an architectural pattern.
SOAP uses service interfaces to expose its functionality to client applications. In SOAP, the WSDL file provides the client with the necessary information which can be used to understand what services the web service can offer. REST use Uniform Service locators to access to the components on the hardware device.
SOAP requires more bandwidth for its usage. Since SOAP Messages contain a lot of information inside of it, the amount of data transfer using SOAP is generally a lot. REST does not need much bandwidth when requests are sent to the server. REST messages mostly just consist of JSON messages. Below is an example of a JSON message passed to a web server. You can see that the size of the message is comparatively smaller to SOAP. {“city”:“Mumbai”,“state”:“Maharastra”}
Tranfer on HTTP, FTP and SMTP etc Only HTTP

What is DSC

There are two types of architecture with DSC:

Push mode

The configurations are sent/pushed manually towards one or more units that we call “node”. This action is done by an administrator.

Pull mode

A “Pull Server” is created and the nodes contact this server at regular intervals so as to obtain their configuration.

DSC Resources

Items allowed to configure on the nodes, is called a DSC Resources. Run Get-DSCResource cmdlet to list all the DSC resources

PS C:\> Get-DscResource | select Name,Module,Properties | Ft -AutoSize

Name                      Module                      Properties
----                      ------                      ----------
File                                                  {DestinationPath, Attributes, Checksum, Contents...}
SignatureValidation                                   {SignedItemType, TrustedStorePath}
PackageManagement         PackageManagement           {Name, AdditionalParameters, DependsOn, Ensure...}
PackageManagementSource   PackageManagement           {Name, ProviderName, SourceUri, DependsOn...}
Archive                   PSDesiredStateConfiguration {Destination, Path, Checksum, Credential...}
Environment               PSDesiredStateConfiguration {Name, DependsOn, Ensure, Path...}
Group                     PSDesiredStateConfiguration {GroupName, Credential, DependsOn, Description...}
GroupSet                  PSDesiredStateConfiguration {DependsOn, PsDscRunAsCredential, GroupName, Ensure...}
Log                       PSDesiredStateConfiguration {Message, DependsOn, PsDscRunAsCredential}
Package                   PSDesiredStateConfiguration {Name, Path, ProductId, Arguments...}
ProcessSet                PSDesiredStateConfiguration {DependsOn, PsDscRunAsCredential, Path, Credential...}
Registry                  PSDesiredStateConfiguration {Key, ValueName, DependsOn, Ensure...}
Script                    PSDesiredStateConfiguration {GetScript, SetScript, TestScript, Credential...}
Service                   PSDesiredStateConfiguration {Name, BuiltInAccount, Credential, Dependencies...}
ServiceSet                PSDesiredStateConfiguration {DependsOn, PsDscRunAsCredential, Name, StartupType...}
User                      PSDesiredStateConfiguration {UserName, DependsOn, Description, Disabled...}
WaitForAll                PSDesiredStateConfiguration {NodeName, ResourceName, DependsOn, PsDscRunAsCredential...}
WaitForAny                PSDesiredStateConfiguration {NodeName, ResourceName, DependsOn, PsDscRunAsCredential...}
WaitForSome               PSDesiredStateConfiguration {NodeCount, NodeName, ResourceName, DependsOn...}
WindowsFeature            PSDesiredStateConfiguration {Name, Credential, DependsOn, Ensure...}
WindowsFeatureSet         PSDesiredStateConfiguration {DependsOn, PsDscRunAsCredential, Name, Ensure...}
WindowsOptionalFeature    PSDesiredStateConfiguration {Name, DependsOn, Ensure, LogLevel...}
WindowsOptionalFeatureSet PSDesiredStateConfiguration {DependsOn, PsDscRunAsCredential, Name, Ensure...}
WindowsPackageCab         PSDesiredStateConfiguration {Ensure, Name, SourcePath, DependsOn...}
WindowsProcess            PSDesiredStateConfiguration {Arguments, Path, Credential, DependsOn...}

Syntax

DSC syntax contains 3 basic components –

  1. Configuration
  2. Node – Name of server/machine
  3. Resource (DSC Resource)

To view the DSC Configuraiton use the cmdlet: Get-DscResource <Name of Resource> -Syntax

Writing a simple Configuration

Configuration FileCopy # Name of the configuration
{  
    param( # Configuration parameters
        [Parameter(Mandatory=$true)] 
        [String[]]$Servers, 
        [Parameter(Mandatory=$true)] 
        [String]$SourceFile, 
        [Parameter(Mandatory=$true)] 
        [String]$DestinationFile
    )

    Node $Servers # Node deploys the configuration on machine(s)
    {  
        File 'CopyHostFile'
        {    
            Ensure = "Present" 
            SourcePath = $SourceFile
            DestinationPath = $DestinationFile
        }
        
        Service 'StartService'
        {
            Name        = "Bits"
            StartupType = "Manual"
            State       = "Running"
        }
    }
}   

Applying DSC configuration

Following command will generate a MOF file, with name of the node, like localhost.mof

FileCopy -Servers localhost -SourceFile C:\test\out.txt -DestinationFile C:\test\filemov -OutputPath C:\test\mof -Verbose

Push the configuration using the .mof file

Start-DscConfiguration C:\test\mof\ -Verbose -wait

Checking past DSC Configuration

PS C:\> Get-DscConfigurationStatus

Status StartDate Type Mode RebootRequested NumberOfResources
—— ——— —- —- ————— —————–
Success 8/15/2018 7:58:41 PM Initial PUSH False 2

Testing DSC Resource configuration with the MOF Files

PS C:\> Get-DscConfigurationStatus

Status     StartDate                 Type            Mode  RebootRequested      NumberOfResources
------     ---------                 ----            ----  ---------------      -----------------
Success    8/15/2018 7:58:41 PM      Initial         PUSH  False                2

Testing DSC Resource configuration with the MOF Files

PS C:\> Test-DscConfiguration -Path C:\test\mof\

PSComputerName  ResourcesInDesiredState        ResourcesNotInDesiredState     InDesiredState
--------------  -----------------------        --------------------------     --------------
localhost                                      {[File]CopyHostFile::[FileC... False

My new book :  PowerShell Scripting Guide to Python

This PowerShell Scripting guide to Python is designed to make readers familiar with syntax, semantics and core concepts of Python language, in an approach that readers can totally relate with the concepts of PowerShell already in their arsenal, to learn Python fast and effectively, such that it sticks with readers for longer time.

“Use what you know to learn what you don’t. ” also known as Associative learning.

Book follows a comparative method to jump start readers journey in Python, but who is the target audience? and who should read this book –

  • Any System Administrator who want to step into Development or Programming roles, and even if you don’t want to be a developer, knowledge of another scripting language will make your skill set more robust.
  • Python Developers who want to learn PowerShell scripting and understand its ease of user and importance to manage any platform.

Python is one of the top programming languages and in fast changing IT scenarios to DevOps and Cloudto the future – Data ScienceArtificial Intelligence (AI) and Machine Learning Python is a must know.

But this PowerShell Scripting guide to Python would be very helpful for you if you already have some knowledge of PowerShell

NOTE! This is a Leanpub “Agile-published” book. That means the book is currently unfinished and in-progress. As I continue to complete the chapters, we will re-publish the book with the new and updated content. Readers will receive an email once a new version is published!

While the book is in progress, please review it and send any feedback or error corrections at prateek@ridicurious.com

Subscribe to our mailing list

* indicates required

Related posts

Consistent $Profile across All PowerShell Hosts and a Backup on GitHub

Prateek Singh
8 years ago

PowerShell Enum for Parameter Validation

Prateek Singh
8 years ago

Find Insecure WiFi with PowerShell

Prateek Singh
8 years ago
Exit mobile version