2016-04-14 31 views
1

我想通過Invoke-Expression傳遞一個對象和一個字符串變量到「Get-ADUser」commandlet。Powershell傳遞對象和字符串來調用表達式

憑據建這樣的:

$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force 
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd) 

然後串由具有其他參數:

if ($dc) 
{ 
    $newVar = " -server $dc" 
} 

if ($ou) 
{ 
    $newVar = $newvar + " -Serchbase $ou" 
} 

,最後被執行

$AllADUsers = iex "Get-ADUser $newVar -Credential $($mycreds) -Filter * -Properties *" | Where-Object {$_.info -NE 'Migrated'} 

以下,但它帶來的如果我只是點擊確定,打開憑證對話框和錯誤

Get-ADUser:無法驗證參數'Credential'上的參數。參數爲空或空。提供一個不爲空或空的參數,然後再次嘗試該命令。 在線:1 char:54 + Get-ADUser -server srv-v-hh001.bwg.corp -Credential System.Management.Automatio ... + ~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo:InvalidData:(:) [獲取-ADUser便有],ParameterBindingValidationException + FullyQualifiedErrorId:ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

我認爲這是因爲iex將$ mycreds解析爲字符串,有沒有辦法告訴Powershell這是一個對象?

+0

請參閱https://stackoverflow.com/questions/26615658/calling-invoke-expression-with-parameters-in-powershell,瞭解使用帶調用參數的「Invoke-Expression」的示例。 –

回答

0

爲什麼你需要IEX?使用哈希表來構建參數Get-ADUser,然後就splat它:

$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force 
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd) 

$Splat = @{ 
    Credential = $mycreds 
    Filter = '*' 
    Properties = '*' 
} 

if ($dc) 
{ 
    $Splat.Server = $dc 
} 

if ($ou) 
{ 
    $Splat.SearchBase = $ou 
} 

$AllADUsers = Get-ADUser @Splat | Where-Object {$_.info -NE 'Migrated'} 

順便說一句,你有你的SearchBase參數名稱的拼寫錯誤。

+0

謝謝,這樣做! – Holger

相關問題