2016-01-20 40 views
0

我對編程非常陌生,我有這樣的代碼。Powershell,Loop,Array有價值,爲什麼Powershell無法識別循環中的有價值

$azuresubscription = get-azuresubscription 



for($K = 0; $K -le $azuresubscription.Length -1; $K++){ 

$s= $azuresubscription[$K]|select SubscriptionName 

$s 
Write-Host "++++++++++++++++++++"; 
select-azuresubscription -SubscriptionName $s 

} 

和回聲出是

SubscriptionName                                                             
---------------- 
CAT                                                            
++++++++++++++++++++ 
select-azuresubscription : Must specify a non-null subscription name. 
Parameter name: name 
At line:12 char:1 
+ select-azuresubscription -SubscriptionName $s 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : CloseError: (:) [Select-AzureSubscription], ArgumentException 
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand 

Dog                                                              
++++++++++++++++++++ 
select-azuresubscription : Must specify a non-null subscription name. 
Parameter name: name 
At line:12 char:1 
+ select-azuresubscription -SubscriptionName $s 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : CloseError: (:) [Select-AzureSubscription], ArgumentException 
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand 

Bird                                                            
++++++++++++++++++++ 
select-azuresubscription : Must specify a non-null subscription name. 
Parameter name: name 
At line:12 char:1 
+ select-azuresubscription -SubscriptionName $s 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : CloseError: (:) [Select-AzureSubscription], ArgumentException 
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand 

所以我想這樣的

select-azuresubscription -SubscriptionName "CAT" 

它的工作原理, 據錯誤,似乎PowerShell的認爲$ s爲null

爲什麼Powershell無法將$ s識別爲CAT,Dog或Bird?我該如何改變它?

+1

主要的是要記住的PS是它的.NET,因此一切都是.NET對象。如果你想要字符串,那就是'-expand'進入的地方。 –

回答

3

您需要在select

$azuresubscription = get-azuresubscription 

for($K = 0; $K -le $azuresubscription.Length -1; $K++) { 
    $s = $azuresubscription[$K] | select -Expand SubscriptionName 

    Write-Verbose -Verbose "`$s = $s" 
    Write-Verbose -Verbose "++++++++++++++++++++"; 
    select-azuresubscription -SubscriptionName $s 
} 

使用-Expand選項在最初的形式,你要包含你所選擇的屬性的子集的PowerShell對象。用-ExpandProperty-Expand簡稱,您將得到名爲的屬性的實際值。

更PowerShell的-Y方式做到這一點也將是:

get-azuresubscription | 
    ForEach-Object { 
     select-azuresubscription -SubscriptionName $_.SubscriptionName 
    } 

,甚至可能更短(如果Azure的命令,支持正確的管道):

get-azuresubscription | select-azuresubscription