这是我想的最佳实践问题.
在设计将在脚本中使用的函数时,处理函数内可能发生的错误的最佳方法是什么?
例如,假设我们有一个执行X和Y的基本功能:
Function Test-Function
{
Try
{
<# Something in here that would generate an error #>
}
Catch
{
Throw
}
Return $someReturnResultIWantInMyScript
}
Run Code Online (Sandbox Code Playgroud)
我的脚本调用此函数:
Try
{
$ValueIWantFromFunction = Test-Function
}
Catch
{
<# Do something here #>
}
Run Code Online (Sandbox Code Playgroud)
如果Test-Function遇到终止错误,它将抛给调用者.将Try/Catch围绕在我的脚本函数调用将收到此错误并击中了自己的渔获物.然后我可以决定做什么.
如果我没有在函数中抛出错误,脚本将看不到终止错误,然后我$ValueIWantFromFunction可能包含$Null或无用的东西.
这是在脚本中使用函数和函数调用进行错误处理的好方法吗?有没有更好的办法?
我正在编写.NET在Windows Server 2016上运行的应用程序,这些应用程序会对大量文件的大量内容执行http操作.这可以大大加快下载过程,因为您可以并行下载它们.不幸的是,一旦下载它们,将它们全部重新组合在一起需要相当长的时间.
有2-4k个文件需要组合.这将运行的服务器有很多内存,靠近800GB.我认为使用MemoryStreams存储下载的部分直到它们可以顺序写入磁盘是有意义的,但我只能2.5GB在出现System.OutOfMemoryException错误之前消耗大约内存.服务器有数百GB可用,我无法弄清楚如何使用它们.
我有板条箱oauth2(v4.1.0)和sqlx[json](v0.5.5):
[dependencies]
oauth2 = "4.1.0"
sqlx = { version = "0.5.5", features = ["json"] }
Run Code Online (Sandbox Code Playgroud)
当尝试构建时,我收到以下错误:
error: cyclic package dependency: package `ahash v0.7.4` depends on itself. Cycle:
package `ahash v0.7.4`
... which is depended on by `hashbrown v0.11.2`
... which is depended on by `indexmap v1.7.0`
... which is depended on by `serde_json v1.0.64`
... which is depended on by `wasm-bindgen v0.2.74`
... which is depended on by `js-sys v0.3.51`
... which is depended on by …Run Code Online (Sandbox Code Playgroud) 这是我的例子:
$Config = @{
AllNodes = @(
@{ NodeName = 'localhost'; PSDscAllowPlainTextPassword = $True }
)
}
Configuration LocalAdmin
{
Param([String[]]$Node='localhost',[PSCredential]$Cred)
Import-DscResource -ModuleName 'PSDscResources'
Node $Node
{
User 'LocalAdmin'
{
Username = 'Admin'
Description = 'DSC configuration test'
Ensure = 'Present'
FullName = 'Administrator Extraordinaire'
Password = $Cred
PasswordChangeRequired = $False
PasswordNeverExpires = $True
}
Group 'AddToAdmin'
{
GroupName = 'Administrators'
DependsOn = '[User]LocalAdmin'
Ensure = 'Present'
MembersToInclude = 'Admin'
}
}
}
Configuration DisableLocalAccounts
{
Param([String[]]$Node='localhost')
Import-DscResource -ModuleName 'PSDscResources' …Run Code Online (Sandbox Code Playgroud) 该脚本使用文件系统观察程序监视蜜罐文件夹,并报告任何更改(编辑,重命名,删除或创建),然后执行某些操作.
创建,重命名和删除时,操作可以正常工作.
但是在编辑时,我只能让脚本触发一次动作.因此,例如,如果测试设备尝试编辑honeypot文件夹上的文件,则会触发操作.但是同一设备尝试再次编辑同一个文件或不同的文件,编辑的观察者似乎无法工作,因为没有触发操作.
所以我尝试通过任务调度程序每5分钟重置一次脚本(每5分钟启动一次脚本),但结果仍然相同.
这是代码:
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "\\vmserver2\_Do_Not_Delete_Or_Rename"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
#Add-content "D:\log.txt" -value $logline
#write-host $logline
$targetdevice = Get-SmbOpenFile |
select clientusername, clientcomputername, path |
where {$_.Path -like 'E:\Data\Archive\_Do_Not_Delete_Or_Rename' }
$targetIP = $targetdevice.clientcomputername
$targetUser = …Run Code Online (Sandbox Code Playgroud) PS C:\> cd Program Files
Run Code Online (Sandbox Code Playgroud)
当我发出这个命令时,我不知道为什么,但它不接受Program Files. 相同的命令在cmd.
这是它显示的错误:
Set-Location : A positional parameter cannot be found that accepts argument 'Files'.
At line:1 char:1
+ cd Program Files
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
Run Code Online (Sandbox Code Playgroud) 我希望这是一个简单的解决方法,但是我找不到与此有关的任何文档或其他文章。我正在尝试编写一个脚本(cmd或pwsh),该脚本将在便携式安装中以我的喜好启动vscode。
当尝试code.exe使用任何参数执行vscode时,它会忽略它们并像我没有键入其他任何内容一样启动程序。我在测试中正在关注此文档。使用别名开关也不起作用。这一点的唯一论点确实似乎过程是,如果我有一个路径。
code.exe --help
code.exe --version
Run Code Online (Sandbox Code Playgroud)
此外,启动后code.exe,控制台会挂起,然后将vscode状态消息发送到该控制台(即使不使用--wait开关)。如果关闭控制台,则vscode将关闭。有办法解决这个问题吗?
windows command-line-interface command-line-arguments visual-studio-code vscode-settings
在 PowerShell 6.0 之前,为了提升您的会话,您运行了命令
Start-Process powershell -Verb runAs
Run Code Online (Sandbox Code Playgroud)
尝试在 PowerShell 6.0 中运行类似命令时
Start-Process pwsh -Verb runAs
Run Code Online (Sandbox Code Playgroud)
你得到这个输出:
Start-Process :此版本的 PowerShell 上的 cmdlet“Start-Process”不支持参数“-Verb”。
在 line:1 char:1
+ Start-Process pwsh -Verb runAs
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented : (:) [Start-Process], NotSupportedException
+fullyQualifiedErrorId : NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand
那么如何在 PowerShell 6.0 中提升为以管理员身份运行?
我正在运行 PowerShell Windows Nano Server docker 映像 (microsoft/powershell:nanoserver)
我正在尝试使用Format Documentvscode中的powershell 执行自定义规则和代码格式化(使用该工具).我已经阅读了相当多的PSScriptAnalyzer扩展文档,但我无法弄清楚如何使其工作.
如果我手动运行
Invoke-ScriptAnalyzer .\Example.ps1 -CustomRulePath .\Rule.psm1
Run Code Online (Sandbox Code Playgroud)
PSSA承认违规行为.更改设置路径后,我没有得到任何突出显示,而代码格式仍然有效.
如何settingsPath使用自定义规则,是否可以使用PSSA设置自定义代码格式(我已经看过这个广告但未记录/博客文章)?
.\Example.ps1
function Get-MYVar {
param (
[string]$VariableName
)
$results = $null
Get-Variable -Name $VariableName
}
Run Code Online (Sandbox Code Playgroud)
.\Rule.psm1
using module @{ModuleName = 'PSScriptAnalyzer'; ModuleVersion = '1.17'}
using namespace System.Management.Automation.Language
using namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
function FunctionCasing
{
[CmdletBinding()]
[OutputType([DiagnosticRecord[]])]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlockAst]
$ScriptBlockAst
)
try
{
@($ScriptBlockAst.FindAll({
$args[0] -is [FunctionDefinitionAst] -and
$args[0].Name -cmatch '[A-Z]{2,}'
}, $false)).ForEach({
[DiagnosticRecord]@{
Message = 'Avoid function names with …Run Code Online (Sandbox Code Playgroud) powershell powershell-5.0 visual-studio-code vscode-extensions
环境详细信息:
没有加载任何配置文件,我的本地PowerShell会话将返回
内存不足。
当我尝试执行help或man。无论我使用的是native powershell.exe还是conmumu,都会发生这种情况。
奇怪的是,我能够执行我尝试过的任何其他别名,并且它不会添加到$Error变量中,所以我不知道从哪里开始进行故障排除(我已经尝试过-ErrorAction Stop和$ErrorActionPreference = 'Stop')。
作为注脚,我没有任何特权。
经过一番探索,我发现它man实际上是一个别名,help不是的别名Get-Help,而是具有以下定义的函数:
function help {
<#
.FORWARDHELPTARGETNAME Get-Help
.FORWARDHELPCATEGORY Cmdlet
#>
[CmdletBinding(DefaultParameterSetName = 'AllUsersView', HelpUri = 'http://go.microsoft.com/fwlink/?LinkID=113316')]
param(
[Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)]
[string]
${Name},
[string]
${Path},
[ValidateSet('Alias', 'Cmdlet', 'Provider', 'General', 'FAQ', 'Glossary', 'HelpFile', 'ScriptCommand', 'Function', 'Filter', 'ExternalScript', 'All', 'DefaultHelp', 'Workflow', 'DscResource', 'Class', …Run Code Online (Sandbox Code Playgroud) powershell ×7
windows ×3
.net ×1
64-bit ×1
c# ×1
cmd ×1
dsc ×1
file-watcher ×1
memory ×1
rust ×1
rust-cargo ×1