Powershell脚本无法将ForEach-Object识别为有效的cmdlet
我已经编写了一个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
我不知道什么可能导致此错误或为什么发生。
你的问题,是因为你还没有把cmdlet和反引号字符之间的空间,但它会更好,不使用反引号,而是只保留在同一行大括号{
:
$users_csv|ForEach-Object {
你也不需要管道角色后面的倒钩。您可能还想考虑使用splatting而不是反引号来改进您的格式(反引号通常是不鼓励的,因为它们很难被看到并且不便于使用)。我建议以下修订:
$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"}
$Props = @{
Identity = $user_object
OfficePhone = $_."Office Number"
MobilePhone = $_."Mobile Number"
StreetAddress = $_."Street"
City = $_."City"
PostalCode = $_."PostCode"
}
#ammends the ad object in the above variable
Set-ADUser @Props
}
非常感谢你为这个标记。我不熟悉splatting,你能指出我对它有好的指导吗? – DarkOverNerd
当然,请检查:https://technet.microsoft.com/en-us/library/gg675931.aspx。如上所示,它构建了希望它们具有的参数和设置的散列表,然后使用'@'字符而不是'$'将该散列表发送到cmdlet。 –
观看了这一点 - 'ammend-ADUsers($ user_csv)' - 这不是很好的PowerShell命令的参数语法,你应该使用'ammend-ADUsers $ user_csv'。你的代码可以工作,但与其他语言不一样 - 如果你尝试将它用于两个参数,例如'ammend-ADUsers($ user_csv,$ param2)',它们会中断,并将它们作为数组传递给第一个参数代替。 – TessellatingHeckler