2017-08-01 108 views
1

我已經編寫了一個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 

我不知道什麼可能導致此錯誤或爲什麼發生。

+1

觀看了這一點 - 'ammend-ADUsers($ user_csv)' - 這不是很好的PowerShell命令的參數語法,你應該使用'ammend-ADUsers $ user_csv'。你的代碼可以工作,但與其他語言不一樣 - 如果你嘗試將它用於兩個參數,例如'ammend-ADUsers($ user_csv,$ param2)',它們會中斷,並將它們作爲數組傳遞給第一個參數代替。 – TessellatingHeckler

回答

1

你的問題,是因爲你還沒有把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 
    } 
+0

非常感謝你爲這個標記。我不熟悉splatting,你能指出我對它有好的指導嗎? – DarkOverNerd

+0

當然,請檢查:https://technet.microsoft.com/en-us/library/gg675931.aspx。如上所示,它構建了希望它們具有的參數和設置的散列表,然後使用'@'字符而不是'$'將該散列表發送到cmdlet。 –

相關問題