2016-12-10 38 views
1

我正在研究將我的整套偏好變量導入到遠程作用域。 PowerShell是否實現了變量的集合?有偏好變量的集合嗎?如果是這樣,我能用$ using導入集合嗎?Powershell中偏好變量的集合

喜歡的東西:

Begin { 
    $scriptblock = { 
     Try { 
      $VerbosePreference = $Using:VerbosePreference 
      $ErrorActionPreference = $Using:ErrorActionPreference 
      ... 
     } 
     Catch{ #Ignore these errors } 

... 

我想導入所有的偏好變量,而如果單獨指定可能...

+0

開始{$ 腳本塊= { 嘗試{$ VerbosePreference = $使用:VerbosePreference $ ErrorActionPreference = $使用:ErrorActionPreference} 捕捉{ #Ignore這些錯誤 } –

+0

我d喜歡導入所有首選項變量,如果可能的話無需單獨指定。 –

回答

1

的PowerShell(V5.1開始):

  • 不執行集合的變量,
  • 並且有編程方式爲明確且詳盡地標識所有偏好變量。

有關所有首選變量的當前列表,請參閱Get-Help about_Preference_Variables

這就是說,你可以使用通配符表達*PreferenceGet-Variable定位選項變量至少一些 - 也許他們覆蓋您的需求:

> (Get-Variable *Preference).Name 
ConfirmPreference 
DebugPreference 
ErrorActionPreference 
InformationPreference 
ProgressPreference 
VerbosePreference 
WarningPreference 
WhatIfPreference 

如前所述,結果既不保證(例如,MaximumHistoryCount不匹配),也不排除潛在的誤報(例如,阻止您定義變量$FooPreference)。

如果您願意從about_Preference_Variables幫助主題中提取所有變量名稱 - 這不是完全健壯的 - 請參閱本文的底部。

總體而言,最好的逼近可能是下面的命令:

> Get-Variable | 
    Where-Object { 
    $_.Name -clike '*Preference' -or 
    ($_.Attributes -and $_.Options -notcontains 'ReadOnly') 
    } | % Name 
ConfirmPreference 
DebugPreference 
ErrorActionPreference 
InformationPreference 
MaximumAliasCount 
MaximumDriveCount 
MaximumErrorCount 
MaximumFunctionCount 
MaximumHistoryCount 
MaximumVariableCount 
OutputEncoding 
ProgressPreference 
PSDefaultParameterValues 
VerbosePreference 
WarningPreference 
WhatIfPreference 

這依賴於唯一的偏好變量有(驗證)屬性,這是通常真正的假設,但是,再次,您可以自由地使用驗證屬性來定義自己的變量,然後將其錯誤地包含進來。

$_.Options -notcontains 'ReadOnly'雜草出只讀變量,因爲根據定義,它們不能變量偏好,如果他們不能修改。


至於在遠程命令中使用這些變量/後臺作業:

沒有優雅的解決方案(和$using:只用文字變量名的作品),但你可以嘗試以下方法:

# Collect pref. variables, to the best of our ability. 
$prefVarDefs = Get-Variable | ? { $_.Name -clike '*Preference' -or ($_.Attributes -and $_.Options -notcontains 'ReadOnly') } 

# Pass them to the background/remote script block and have them 
# assigned there. 
Start-Job { $args | % { set-variable $_.Name $_.Value }; ... } -Args $prefVarDefs 

注意Start-Job被用作一個例子(因爲它可以在不遠程處理和在非提升會話中運行),但同樣的規則適用與Invoke-Command,例如,與相同的技術可與後者一起使用。


另一種選擇是解析about_Preference_Variables幫助主題,這是有點脆,但是它具有:

  • 依賴於主題的特定格式

  • 依靠話題要完整和準確。

(Get-Help about_Preference_Variables) -creplace '(?s)\A.*?\r?\n +?Variable +Default Value\r?\n +?-+ +-+\r?\n(.+?)\r?\n\r?\n.*\Z', '$1' -split '\r?\n' | % { (-split $_)[0] } 
+0

謝謝。我很驚訝。我將在PowerShell用戶語音中看到有關如何實現這些集合的建議。再次感謝。 –

+0

@ M.Anselmi我的榮幸。我用更好的_approximation_查找所有偏好變量來更新答案,但它不健壯。在https://windowsserver.uservoice.com/forums/301869-powershell尋求明確的功能是正確的方法。一旦您發佈了您的建議,我鼓勵您在此發佈具體鏈接,以便未來的讀者也可以輕鬆地投票,如果他們感興趣的話。 – mklement0

+1

https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/17407222-powershell-and-collections-in-particular-collect –