我已经编写了一个powershell脚本来对Active Directory进行修改。 我得到一个有趣的错误。 这是脚本。Powershell脚本无法将ForEach-Object识别为有效的cmdlet
#imports the module active directory if it isn't there.
function add-ADmodule()
{
$modules = Get-Module | Where-Object{$_.Name -like "*ActiveDirectory*"}
if($modules -eq $null)
{
Import-Module ActiveDirectory
}
}
#import the data file
$user_csv = import-csv C:\temp\users.csv
#makes the ammendments to the AD object
function ammend-ADUsers($user_csv)
{#this is the loop to make ammendments to each object
$users_csv|ForEach-Object`
{
#assigns each user's AD object to a variable
$user_object = get-aduser -filter * `
-Properties mail |`
Where-Object{$_.mail -like $_."Email Address"}
#ammends the ad object in the above variable
set-aduser -Identity $user_object `
-OfficePhone $_."Office Number" `
-MobilePhone $_."Mobile Number" `
-StreetAddress $_."Street" `
-City $_."City" `
-PostalCode $_."PostCode"
}
}
#this is the main part of the code where it gets executed
add-ADmodule
Write-Verbose "Active Directory Module Added"
ammend-ADUsers($user_csv)
这是我得到的错误。
PS C:\Users\admin> C:\Scripts\ammend-aduser.ps1
ForEach-Object : The term 'ForEach-Object' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At C:\Scripts\ammend-aduser.ps1:18 char:20
+ $users_csv|ForEach-Object`
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (ForEach-Object:String) [], Com
mandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
我不知道什么可能导致此错误或为什么发生。
观看了这一点 - 'ammend-ADUsers($ user_csv)' - 这不是很好的PowerShell命令的参数语法,你应该使用'ammend-ADUsers $ user_csv'。你的代码可以工作,但与其他语言不一样 - 如果你尝试将它用于两个参数,例如'ammend-ADUsers($ user_csv,$ param2)',它们会中断,并将它们作为数组传递给第一个参数代替。 – TessellatingHeckler