Speaking at PSConfEU !

Hi together,

this week is starting with good news. I will be speaking at the PowerShell Conference EU 2016!

A big thanks herefore goes to Dr. Tobias Weltner.

Take the chance  and register now until it´s too late!

#PSConfEU
http://www.psconf.eu/

BannerSpeaker.png

Greetings,

David

Advertisements

PS – DynamicParam

Hello together,

in this post i want to show you a very rare function attribute. It is called dynamicparam and as the name says it adds some features to create parameters dynamically when the user writes the execution function:



function Test-DynamicParam 
{
    [CmdletBinding()]
    param( 
        [Parameter(ValueFromPipeline=$true)]
        $Count 
    )
    
    
    dynamicparam
    {
        $paramDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
        foreach ($Property in (1..$Count))
        {
            $attributes = New-Object System.Management.Automation.ParameterAttribute
            $attributes.ParameterSetName = '__AllParameterSets'
            $attributes.Mandatory = $false
            $attributeCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
            $attributeCollection.Add($attributes)
            $Name = "DynamicParam_$Property"
            $dynParam = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter($Name,
            [int32], $attributeCollection)
            $paramDictionary.Add($Name, $dynParam)
        }
            
        $paramDictionary
    }
    
    
    begin
    {}
    
    process
    {    "Entered: $Count"
    }
    
    end
    {}
}

Test-DynamicParam -Count 5 

In this example the user enters the function name and the parameter $count. As you can see in the dynamicparam block now additional parameters are created. If you enter for example the number 5 – 5 additional parameters show up and can be given to the function.

DynamicParam.png

So you can add or remove parameters depending on the parameters which the user entered which can be very powerful if you write very complex functions.

Give it a look

Greetings,

David

PowerTheShell – ISESteroids! PSConfEU!

Hello together,

i have arrived today from a very good Powershell Training with Dr. Tobias Weltner, MVP. I have learned plenty new stuff and will blog lots of the new knowledge in the upcoming weeks.

1

The first thing i have to tell you – get a damn ISESteroids license! I did try it previously and liked it very much but had some scepsis to invest the money. After investigating 3 days the functions which all come along with the Steroids i have to say – its just amazing and a must have. Here are just some of them:

  • WPF Dialog creator
  • Variable Monitor
  • Snippet Manager
  • Creating executable files (.exe)
  • Creating functions and modules withing a click
  • Build-in signing and – much – more

Try it by yourself and get a trial. Just take a look at http://www.powertheshell.com/ 

If you want to create good Powershell scripts this tool is just a must have at the moment.


 

Also a very important information for all powershell fanatics – take a look at the upcoming event Powershell Conference EU 2016 http://www.psconf.eu/

There will be some interesting speakers! Trust me!

Greetings,

David

PS – parameter by reference

Many developers know them – parameter by reference. By this way the variables will not be duplicated. A pointer is created which points to the actual variable. If you modify this referenced parameter you will modify the referenced variable. So you can make changes to many parameters and will not create a lot of functions with returnvalues.

[string]$Global = ''


function TestRefFunction([ref]$Param)
{
    [string]$Param.Value = '5'
    $Param | Out-Default
}

TestRefFunction([ref]$Global)

$Global | Out-Default

By this example the transmitted parameter “$global” is a reference. So all changes to it in the function will also be written into the global variable. In this example so 2 times a “5” will be given out.

~David

PS – download of csv-files of a folder from Sharepoint via webclient

In this example the assumption is that you don´t have a Sharepoint server on which you could use the Sharepoint commandlets. So only the standard webclient functions were used to allow you to download all files. Also you need some valid credentials to log onto the Sharepoint website otherwise you would get the error 401 (not authorized).

Here is the code herefore:


<# 
.Synopsis 
Download all files from a sharepoint folder. 
.DESCRIPTION 
download all files from a sharepoint aspx-site. 
.EXAMPLE 
$credentials=Get-Credential -Credential Domäne\Benutzer 
[string]$sharepointURL = 'https://domäne.de/ExportOrdner/Forms/Overview.aspx' Download-AllFilesFromSP -SP_ASPX_Page $sharepointURL -DestinationFolder 'C:\ExportDirectory' -Credentials $credentials 
.INPUTS SP_ASPX_Page - aspx-site DestinationFolder target  CredentialsSP - authentication 
.FUNCTIONALITY 
Web; Sharepoint; Download 
#>
  function Download-AllCSVFilesFromSP
        {
            PARAM (
                [parameter(Mandatory=$true)]
                $SP_ASPX_Page,
                [parameter(Mandatory=$true)]
                $DestinationFolder,
                [parameter(Mandatory=$true)]
                $CredentialsSP
            )

            #create Object            
            $webclient = New-Object System.Net.WebClient 

            #set credentials
            $webclient.Credentials = $CredentialsSP 
            
            #retrieve content
            $response = Invoke-WebRequest -Uri $SP_ASPX_Page -Credential $CredentialsSP -Method Get

            #parse content parsen and search for export-files
            $matches =[regex]::Matches($response.content,'(\sUrl=\")+[0-9,a-z,A-Z\/_-]*(.csv\"\s)') 

            #foreach found file
            foreach ($item in $matches)
            {
                    #clean the download string             
                    $downloadFileURL = ($item.Groups[0].Value).Split('"')[1]

                    #extract the domain
                    $UrlDomain = ([regex]::Matches($SP_ASPX_Page,'https://[0-9,a-z,A-Z_\-\.]*')).Value

                    #extract filename
                    $downloadFile = $downloadFileURL.Split('/')[-1]
                    
                    #download to destination folder
                    $webclient.downloadfile($UrlDomain + $downloadFileURL,  $DestinationFolder + '\' + $downloadFile) 
            }
        }

PS – remote execution of scripts

In this post i want to show you some ways how to execute remote execution of scripts.

First the complicated way:

connect – set execution policy – copy script, execute, delete – roll back execution policy

$Computername=Name
#"Start Session"
$s = New-PSSession -ComputerName $Computername
#"Enable Script Execution on remote System..."
Invoke-Command -Session $s -scriptblock { Set-executionpolicy unrestricted }
#Copy Script
Copy-Item H:\Skript.ps1 \\$Computername\c$\temp\Skript.ps1
#"Start Script..."
Invoke-Command -Session $s -scriptblock { c:\temp\Skript.ps1 }
#Delete Script
Remove-Item \\$Computername\c$\Skript.ps1
#Disable Script Execution on remote System...
Invoke-Command -Session $s -scriptblock { Set-executionpolicy default }
#End Session
Remove-PSSession $s

Next we use Invoke-Command – the scriptfile is copied and executed within the command itself:

Invoke-Command -computer Computername -FilePath C:\Skript.ps1

Next code connects to a computer NOT using Kerberos. This can become necessary if you want to connect to computers outside your domain:

$Computername=Name

#Not using Kerberos:
cd WSMan:\localhost\Client
Set-Item trustedhosts $Computername -force
Restart-Service winrm
Invoke-Command Computername { #Skript in here#} -authentication negotiate -credential Get-Credential

Have fun with it.

~David