Contents

Invoke-Command wrapper function


Contents

A quick post this time about something that might be helpful for others, something that saves me from typing too much 🙂

I’ve noticed over the last week that I’ve been doing various remoting commands through Invoke-Command to the same machines, which require additional credentials to access.

Why re-type something when you can automate it 🙂

Before

I used to have to do the following:

1
2
3
4
5
$SCCMServers = 'CM01.contoso.com','CM02.contoso.com','CM03.contoso.com','CM04.contoso.com'

$cred_SCCM = Import-CliXml $CredStore\contoso.xml

Invoke-Command -ComputerName $SCCMServers -Credential $cred_SCCM -Scriptblock {whatever needed to be done}

Where my SCCM servers are in another forest as my management machine and $CredStore is my personal Credential folder which contains credentials for various systems/domains, as I use these regularly and I’m lazy

After

After some tinkering around and a great tip found on Thomas Maurer’s site, I’ve narrowed it down to:

1
Invoke-SCCMCommand -Script 'whatever I need to have done here'

I’ve personally decided to keep the 2 variables in my $profile as I tend to use those for other functions as well, but otherwise I would recommend placing these in the begin {} block.

The magic here is the converting of a string to an actual scriptblock by the PowerShell engine, accomplished by the following piece of code:

1
$ScriptBlock = [Scriptblock]::Create($Script)

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function Invoke-SCCMCommand {
<#

	.SYNOPSIS
		Wrapper function for Invoke-Command with specific parameters.

	.DESCRIPTION
		Wrapper function for Invoke-Command with specific parameters.
        Requires the SCCMServer and Cred_SCCM variables to be present.

	.PARAMETER Script
		Provide the script to be run on all SCCM machines

	.EXAMPLE
		PS C:\> Invoke-SCCMCommand -script 'Test-Connection -Name google.com'

		Runs a Test-Connection from all SCCM machines.

	.NOTES

    Created by: Robert Prüst
    Blog: http://powershellpr0mpt.com
    Version: 1.0

#>

    [cmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        $Script
    )
    begin {
        Write-Verbose "Script to run is '$Script'"
        Write-Verbose 'Converting script to actual scriptblock'

        $ScriptBlock = [Scriptblock]::Create($Script)
    }
    process {
        Invoke-Command -ComputerName $SCCMServers -Credential $cred_SCCM -ScriptBlock $ScriptBlock
    }

}

Happy Scripting! 🙂