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?
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
Get-ADUser | .\\Groups.ps1
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.