0

I'm trying to put a small collection of simple scripts together for PowerShell to make life easier but am having some problems with variables in these scripts.

In a Linux environment I would use a variable in my scripts (usually $1, $2, etc....) like this to make things easier

sed -i 's/$1/$2/g' filename.conf

So that all I would need to do is this

./findreplace.sh old new filename.conf

In powershell, I want to achieve similar, specifically with this command:

Get-ADPrincipalGroupMembership account.name | select name

In this case, the $1 would be where 'user.name' is, so that I would be doing:

 .\groups.ps1 user.name

Is there the facility for this?

1
  • 3
    $1 -> $args[0] Commented Feb 14, 2018 at 14:36

2 Answers 2

3

Groups.ps1 should have the following content:

param( $user )

Get-ADPrincipalGroupMembership $user | Select Name

You can then invoke it as shown, or as .\Groups.ps1 -user user.name.

However, I'd probably try to do it as an "advanced command", and allow it to handle multiple names, and also names passed in via the pipeline:

[CmdletBinding()]

param (
    [Parameter(ValueFromPipeline=$true;ValueFromPipelineByPropertyName=$true)]
    [Alias("Identity","sAMAccountName")
    string[] $Users
)

PROCESS {
    ForEach ($User in $Users) {
        Get-ADPrincipalGroupMembership $User | Select Name
    }
}

which would also allow you to do something like Get-ADUser | .\Groups.ps1

Sign up to request clarification or add additional context in comments.

5 Comments

So the first code comment works exactly as I would expect, only difference is that I do not use the '-user' part, instead just using: .\Groups.ps1 user.name.
The second code block throws up a load of errors :(
Which version of PowerShell are you using? It seems that not all AD objects are created equal, and I've had some problems using ADPrincipals where ADUsers are expected...
Major 5, Minor 1, Build 14393, Revision 1944
If you do the pipeline version, it may stop throwing errors if you do (Get-ADUser).samaccountname | .\Groups.ps1 (obviously, you can add parameters and filters to the Get-ADUser inside the parens - but don't pipe inside the parens)
1

You can add for loop form example script above:

for ($i = 0; $i -lt $args.Length; $i++) { Set-Variable -Scope Script -Name ($i + 1) -Value $args[$i] }

Write-Host "1: $1"
Write-Host "2: $2"

But more easy is just to declare script parameter as:

param($1, $2)

Write-Host "1: $1"
Write-Host "2: $2"

By the way it's bad practice to declare variables as numbers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.