I'm trying to create userprincipalname as combination of username and hardcoded domainname
csv file:
name,displayname,givenname,surname
dhall,Don Hall,Don,Hall
Code:
Import-csv "c:\output.csv" | ForEach-Object {new-aduser -name $_.name -UserPrincipalName ("{0}#{1}" -f $_.name,"Dev.domain.Net") -DisplayName "$($_.givenname $_.surname)" -givenName $_.givenname -surname $_.surname -path "OU=Workspaces,DC=Dev,DC=domain,DC=Net" -AccountPassword (convertto-securestring passs -asplaintext -force) -Enabled [System.Convert]::toboolean($true)) -ChangePasswordAtLogon ([system.convert]::ToBoolean($true))}
And getting:
At line:1 char:159
+ ... -f $_.name,"Dev.domain.Net") -DisplayNa
+
Unexpected token '$_' in expression or stateme
+ CategoryInfo : ParserError: (:)
+ FullyQualifiedErrorId : UnexpectedToken
Tried also -UserPrincipalName ([string]::Concat($_.name,"#dev.domain.net"))
but same error
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 14393 1944
Windows server 2016
Not sure what's causing that error (don't have an AD controller to test against at the moment so can't validate) but in cases where I'm going to need to reuse a property multiple times I tend to assign it to a temporary variable (makes it slightly easier to write the code and don't run into issues with the pipeline variable getting updated).
Import-CSV "c:\output.csv" | ForEach-Object {
$name = $_.name
$upn = "{0}#{1}" -f $name,"dev.domain.net"
New-ADUser -Name $name -UserPrincipalName $upn #...
}
Related
I'm currently having an issue. Using Powershell, I'm trying to create deployments for multiple applications for multiple collections without having to hardcode anything. For example, lets say that if I have 4 collections and 4 applications. I want to be able to create an deployment with all 4 collections for all 4 for the applications. Currently this is the code that I have:
$dpgName = Get-CMDistributionPointGroup -Name "All_Distribution_Groups"
$collName = Get-CMCollection -Name "*Patching*"
foreach ($coll in $collName.Name){
(Get-CMApplication | Where-Object {$_.LocalizedDisplayName -like "Visual C++ Redistributable*"} | Select LocalizedDisplayName) | % {New-CMApplicationDeployment -CollectionName $coll -Name "$($_.LocalizedDisplayName)" -DeadlineDateTime (get-date) -TimeBaseOn LocalTime -DeployAction Install -DeployPurpose Required -OverrideServiceWindow $False -RebootOutsideServiceWindow $False -UserNotification DisplaySoftwareCenterOnly -EnableMomAlert $False -GenerateScomAlertOnFailure $False -DistributionPointGroupName $dpgName -DistributeContent}
}
But when I attempt to run this script, I get the following error:
New-CMApplicationDeployment : Validation of input parameters failed. Cannot continue.
At line:5 char:133
+ ... yName) | % {New-CMApplicationDeployment -CollectionName $coll -Name " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Microsoft.Confi...ationDeployment:NewApplicationDeployment) [New-CMApplicationDeployment], InvalidOperationException
+ FullyQualifiedErrorId : ValidationFailed,Microsoft.ConfigurationManagement.PowerShell.Cmdlets.Deployments.NewApplicationDeployment
I'm attempting to write a script that gives me a running list of computers whose name starts with SOU-C128*. I'm assigning the list to a variable and using it as input for the restart-computer cmdlet. However, I'm recieving the error provided:
restart-computer : Computer name #{Name=SOU-C127-04} cannot be resolved with the exception: One or more errors occurred..
At \\nas\user\IT\restart.ps1:2 char:1
+ restart-computer -computername $computers -force -wsmanauthentication ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (#{Name=SOU-C127-04}:String) [Restart-Computer], InvalidOperationException
+ FullyQualifiedErrorId : AddressResolutionException,Microsoft.PowerShell.Commands.RestartComputerCommand
This is the script
$computers=Get-ADComputer -Filter * | Where-Object {$_.Name -like "sou-c127*"} | Select -Property Name | Sort Name
restart-computer -computername $computers -force -wsmanauthentication Kerberos
Please assist!
Thanks.
Your immediate fix would be to use $computers.name or, expand the property in your Get-ADComputer by using Select-Objet -ExpandProperty 'Name'; foreach name would suffice too.
Wanted to suggest something though. In PowerShell when you're filtering, you always want to filter as far left as possible. This can become computationally expensive running a pipeline filter such as Where-Object on a large list. In your case: Get-ADComputer -Filter *, you're filtering for every computer, then filtering again. You can cut that out by filtering using the filter in your Get-ADComputer cmdlet to begin with:
$computers = Get-ADComputer -Filter "Name -like 'sou-c127*'" | Sort-Object -Property 'Name'
Restart-Computer -ComputerName $computers.Name
i have a line in PS script which goes to DC and try to do this:
$SWITCH = Invoke-Command -session $s -ScriptBlock {Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $using:listBox2.SelectedItem}}
here are the the variables:
$switch = "OU=office,DC=shahar,DC=local"
$s = credentials to enter the DC with an admin account.
if i run this line on the DC without the invoke command it works. if i run other code lines with invoking commands using these credentials it works as well.
if i run this line on powershell (not as a part of script) it works.
if i replace $switch with the actual string ("DC=...") it still doesnt work.
here is the error and i just cannot figure out whats the problem:
Cannot bind parameter 'Identity'. Cannot convert value "OU=Office,DC=shahar,DC=local" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit". Error: "Cannot convert the "OU=Office,DC=shahar,DC=local"
value of type "Deserialized.Microsoft.ActiveDirectory.Management.ADOrganizationalUnit" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit"."
+ CategoryInfo : InvalidArgument: (:) [Get-ADOrganizationalUnit], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADOrgani
zationalUnit
+ PSComputerName : dc01
any help would be much appriciated!
by the way the point of this is to get from the DC the GPO's names that linked to that OU.
try this:
ipmo ActiveDirectory,GroupPolicy
$OU = 'OU=office,DC=shahar,DC=local'
(Get-ADOrganizationalUnit $OU).DistinguishedName
$LinkedGPOs = Get-ADOrganizationalUnit $OU | select -ExpandProperty LinkedGroupPolicyObjects
$LinkedGPOGUIDs = $LinkedGPOs | % {$_.Substring(4,36)}
$LinkedGPOGUIDs | % {Get-GPO -Guid $_ | select -ExpandProperty Displayname}
I recently updated PSWindowsUpdate from version 1.6.1.1 to the latest version (2.1.0.1) and when I try to run the script:
Write-Host " Centralized Update"
Write-Host "================================"
ipmo activedirectory
$computers = Get-ADComputer -Filter {enabled -eq $true} -properties * -SearchBase "OU=Workstations, DC=contoso, DC=com" | select name
$Script = {ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll -Install -Verbose}
foreach ($computer in $computers) {
Write-Host "Running update on:" $computer.name
Invoke-WUJob -ComputerName $computer.name -Script $Script -Confirm:$false -RunNow
}
Write-Host "================================"
pause
I get the following error:
Invoke-WUJob : The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
At C:\Users\Administrator\Desktop\Update_Workstations.ps1:10
char:2
+ Invoke-WUJob -ComputerName $computer.name -Script $Script -Confir ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WUJob], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,PSWindowsUpdate.InvokeWUJob
The only edit to the script was to change:
Invoke-WUInstall -ComputerName $computer.name -Script $Script -Confirm:$false
To:
Invoke-WUJob -ComputerName $computer.name -Script $Script -Confirm:$false -RunNow
More details:
The version of PowerShell is 5.1 (both client and server side)
The list of terminals is correctly extracted from the "Workstations" organizational unit
I can connect via "enter-pssession" to all the terminals without problems
Using "Invoke-Command" instead of "Invoke-WUJob" run but fails at the time of download with the error "UnauthorizedAccessException"
What's wrong with the code ? before updating to version 2.1.0.1 it works fine
I was also getting the same error. By scratching my head for a day finally a found one power shell command needs to run on the target server before proceeding invoke-wujob
the command is Enable-WURemoting
This script exports the basic file metadata in PowerShell to a .csv.
PS K:\> Get-childitem -recurse -file | select-object length,lastwritetime,fullname | export-csv filelist.csv -notypeinformation
It works great on simple directory structures of 10-20K files, but when I run it on 500K+ files of complex, multi-level directory structures it freezes or gives me error:
At line:1 char:1
+ Get-childitem -recurse -file | select-object length,lastwritetime,ful ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CallDepthOverflow
Is this a problem with the -recurse or else? Using PowerShell 5 1 (Major Minor).
Test to see how long the filepaths are.
If the filepaths are more than 248 characters... That may be why you are getting the error.
To check to see if any come back with more than 248 characters you can do
Get-childitem "filepath" -recurse | % {
$filepath = $_.FullName
$charactercount = ($filepath | Measure-Object -Character).Characters
If ($charactercount -gt 248){write-host $filepath}
}