So I am trying to create a Powershell menu that when the user selects a choice, it will ask for the value or values its trying to search (ex. Ping Multiple Computers). I am currently having a hard time getting that to work. I will post pictures to show what I mean
When I type in one name to search the command executes fine shown below:
When I try with multiple values it doesn't work:
Here is a snap of the code I have:
Any help of course is much appreciated.
UPDATE - 11/13
This is what I currently have:
function gadc {
Param(
[Parameter(Mandatory=$true)]
[string[]] $cname # Note: [string[]] (array), not [string]
)
$cname = "mw$cname"
Get-ADComputer $cname
}
This is the output in the Console
cmdlet gadc at command pipeline position 1
Supply values for the following parameters:
cname[0]: imanuel
cname[1]: troyw
cname[2]: hassan
cname[3]:
Get-ADComputer : Cannot convert 'System.String[]' to the type
'Microsoft.ActiveDirectory.Management.ADComputer' required by parameter 'Identity'. Specified
method is not supported.
At line:32 char:19
+ Get-ADComputer $cname
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.G
etADComputer
Press Enter to continue...:
**And here is the other way with the same result:**
cmdlet gadc at command pipeline position 1
Supply values for the following parameters:
cname[0]: imanuel, troyw
Get-ADComputer : Cannot convert 'System.String[]' to the type
'Microsoft.ActiveDirectory.Management.ADComputer' required by parameter 'Identity'. Specified
method is not supported.
At line:32 char:19
+ Get-ADComputer $cname
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.G
etADComputer
Press Enter to continue...:
You need to declare your mandatory parameter as an array, then PowerShell's automatic prompting will allow you to enter multiple values, one by one - simply press Enter by itself after having submitted the last value in order to continue:
function gadc {
param(
[Parameter(Mandatory)]
[string[]] $cname # Note: [string[]] (array), not [string]
)
# Get-ADComputer only accepts one computer name at a time
# (via the positionally implied -Identity parameter), so you must loop
# over the names.
# The following should work too, but is slightly slower:
# $cname | Get-ADComputer
foreach ($c in $cname) { Get-ADComputer $c }
}
Related
Trying to change msexchhidefromaddresslists property from Powershell for a specific user account. I did a search and found a basic script but am getting an error. I have tried directly from my system and fromm the server. Any ideas?
set-aduser ldap -replace #{msexchhidefromaddresslists="$true"}
set-aduser : The parameter is incorrect
At line:1 char:1
+ set-aduser ldap -replace #{msexchhidefromaddresslists="$true"}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (ldap:ADUser) [Set-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:87,Microsoft.ActiveDirectory.Management.Commands.SetADUser
The schema for the msExchHideFromAddressLists attribute specifies oMSyntax: 1, or Boolean.
LDAP allows a couple different representations of booleans, including integral values (0 for false, a non-zero value for true), or, more commonly the lower-case string representations true or false.
"$true", on the other hand, results in a string with value True (notice it's title-cased, not lowercase).
Use one of:
#{msExchHideFromAddressLists = 1}
#{msExchHideFromAddressLists = "true"} or
#{msExchHideFromAddressLists = $True}
In the last case, the $true value will be (correctly) translated by ADWS, rather than (incorrectly) by PowerShell's string conversion logic
I am searching through the active directory for users under a specific organisation unit, that I would like to change using ADSI.
# get all users from the organizational unit
$accounts = Get-ADObject -filter 'objectClass -eq "user"' -SearchBase $dsn
# iterate over user objects
foreach ($account in $accounts) {
# unfortunately we have to use ADSI over the set-aduser cmdlet as we neeed to touch remote desktop attribues
$user = [ADSI]"LDAP://" + ($account.DistinguishedName).ToString()
# get logon name
$SamAccountName = $user.psbase.InvokeGet("SamAccountName")
# Profile Attributes
$user.psbase.InvokeSet("ProfilePath", "")
$user.psbase.InvokeSet("ScriptPath", "DIR\Logon.cmd")
$user.psbase.InvokeSet("HomeDrive", "H:")
$user.psbase.InvokeSet("HomeDirectory", "\\host\users$\${SamAccountName}")
# Remote Desktop Services Attributes
$user.psbase.InvokeSet("TerminalServicesProfilePath", "")
$user.psbase.InvokeSet("TerminalServicesHomeDirectory", "\\host\users$\${SamAccountName}")
$user.psbase.InvokeSet("TerminalServicesHomeDrive", "H:")
# Write attributes back to global catalog
$user.SetInfo()
}
This all works fine, until it comes to the $user = [ADSI]"LDAP://" + ($account.DistinguishedName).ToString() part.
Method invocation failed because [System.DirectoryServices.DirectoryEntry] does not contain a method named 'op_Addition'.
At \\tsclient\D\SourceCode\PowerShell\Set-ADUserAttributes.ps1:37 char:5
+ $user = [ADSI]"LDAP://" + ($account.DistinguishedName).ToString()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Exception calling "InvokeGet" with "1" argument(s): "Unspecified error
"
At \\tsclient\D\SourceCode\PowerShell\Set-ADUserAttributes.ps1:40 char:5
+ $SamAccountName = $user.psbase.InvokeGet("SamAccountName")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
It seems there is no query getting executed. However, $account.DistinguishedName contains the correct LDAP path (which I have tested manually).
So what am I doing wrong here?.
You're trying to append to an ADSI object by casting "LDAP://" as [ADSI] before you do the append.
Cat your strings first, then do the cast:
$user = [ADSI]("LDAP://" + $account.DistinguishedName)
The casting operation has higher precedence than the concatenation operation, so you need to do the concatenation in a subexpression, either like this:
[adsi]("LDAP://" + $account.DistinguishedName)
or like this:
[adsi]"LDAP://$($account.DistinguishedName)"
The distinguished name is automatically converted to a string here, so you don't need to manually call ToString().
have the following function:
function appendToSB([System.Text.StringBuilder]$sb,
[string]$value){
[void]$sb.append($value)
$sb
}
$sb = new-object -typename system.text.stringbuilder
$sb = appendToSb($sb, "1,")
$sb.tostring() | out-host
i want to build string using StringBuilder using my function for that, but i receive the following error:
appendToSB : Cannot process argument transformation on parameter 'sb'.
Cannot convert the "System.Object[]" value of ty pe "System.Object[]"
to type "System.Text.StringBuilder". At E:\powershell\test.ps1:8
char:11
+ appendToSb([system.text.stringbuilder]$sb, "1,")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [appendToSB], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,appendToSB
does anybody can explain how function/function parameter/return values works in powershell?
Classic PowerShell issue. You don't use parens or comma separated args when calling commands or functions e.g.:
appendToSb $sb "1,"
You only use that syntax when calling .NET methods. If you use Set-StrictMode -Version 2 it will catch this sort of issue. What you passed ($sb, "1,") is how you would pass an array to a single parameter. Technically the parens aren't needed but don't change the value i.e. you could pass an array like this as well $sb, ",".
Morning,
I'm trying to use a CSV file with a list of users and automate the process to set an AD users extensionAttribute15 back to the "notset" value.
I use a similar code to populate the attribute, the CSV file consists of just two things, the users LAN ID and the value for the attribute.
Populating the field is not the problem, changing the values back to "not set" has been.
Here is the code I am using.
Import-module ActiveDirectory
Import-CSV "code.csv" | % {
$User = $_.cn
$user.Put(“extensionAttribute15”, #())
$user.SetInfo()
}
and here are the errors.
Method invocation failed because [System.String] doesn't contain a method named 'Put'.
At attribute.ps1:4 char:10
+ $user.Put <<<< (“extensionAttribute15”, #())
+ CategoryInfo : InvalidOperation: (Put:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [System.String] doesn't contain a method named 'SetInfo'.
At attribute.ps1:5 char:14
+ $user.SetInfo <<<< ()
+ CategoryInfo : InvalidOperation: (SetInfo:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any ideas what the problem could be?
Thanks,
When you read in a CSV file, the resulting objects are just simple property bags. They don't support any special methods, they just hold flat data. There is nothing in these objects that isn't present in the text of the CSV file itself.
If you want to obtain a rich object which has Active Directory context and capabilities, you will need to obtain one from a cmdlet in the ActiveDirectory module.
Something like this is probably along the lines you need
Import-module ActiveDirectory
Import-CSV "code.csv" | % {
$user = Get-ADUser $_.cn # get a rich object from the AD module, by passing a string
$user.Put(“extensionAttribute15”, #())
$user.SetInfo()
}
I have a PowerShell script:
param (
[Parameter(Mandatory=$true)][string]$input,
[Parameter(Mandatory=$true)][string]$table
)
Write-Host "Args:" $Args.Length
Get-Content $input |
% { [Regex]::Replace($_, ",(?!NULL)([^,]*[^\d,]+[^,]*)", ",'`$1'") } |
% { [Regex]::Replace($_, ".+", "INSERT INTO $table VALUES (`$1)") }
The Write-Host part is for debugging.
I run it as .\csvtosql.ps1 mycsv.csv dbo.MyTable (from powershell shell), and get
Args: 0
Get-Content : Cannot bind argument to parameter 'Path' because it is an empty s
tring.
At C:\temp\csvtosql.ps1:7 char:12
+ Get-Content <<<< $input |
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBinding
ValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
lowed,Microsoft.PowerShell.Commands.GetContentCommand
I get exactly the same error with any parameters that I pass, also the same error if I try to use named parameters.
What can cause parameters not to be passed in?
UPDATE: PowerShell ISE asks me for these parameters using GUI prompts, then gives me the same error about them not being passed in.
Unless you marked a parameter with the ValueFromRemainingArguments attribute (indicates whether the cmdlet parameter accepts all the remaining command-line arguments that are associated with this parameter), Args is "disabled". If all you need is the arguments count call the special variable:
$PSBoundParameters.Count
Do not mix. Make use of $args or parameters.
Also do note that $input is a special variable, don't declare it as a parameter. http://dmitrysotnikov.wordpress.com/2008/11/26/input-gotchas/
You're calling your script with positional parameters (i.e. unnamed) and PowerShell doesn't know how to map them to your script parameters. You need to either call your script using the parameter names:
.\csvtosql.ps1 -input mycsv.csv -table dbo.MyTable
or update your script to specify your preferred order of positional parameters:
param (
[Parameter(Mandatory=$true,Position=0)]
[string]
$input,
[Parameter(Mandatory=$true,Position=1)]
[string]
$table
)