0

こんにちは私は私の言い回しが正しいかどうか正確にはわかりませんが、ログにデータを書き込むときはいつでも現在の日付/時刻を含む変数が必要です。毎回初期化せずにそれを行うにはどうすればよいですか?現在、更新が必要になるたびに、これらの両方のステートメントを一緒に使用します。これを行う他の方法はありますか?

$DateTime = get-date  | select datetime
Add-Content $LogFile -Value "$DateTime.DateTime: XXXXX"

私の質問に関する質問や説明があれば教えてください。

4

5 に答える 5

4

このスクリプトは、Powershellで実際の動的変数を作成します(Lee Holmesと彼のおかげでWindows PowerShell Cookbook The Complete Guide to Scripting Microsoft's Command Shell, 3rd Edition

##############################################################################
##
## New-DynamicVariable
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Creates a variable that supports scripted actions for its getter and setter

.EXAMPLE

PS > .\New-DynamicVariable GLOBAL:WindowTitle `
     -Getter { $host.UI.RawUI.WindowTitle } `
     -Setter { $host.UI.RawUI.WindowTitle = $args[0] }

PS > $windowTitle
Administrator: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PS > $windowTitle = "Test"
PS > $windowTitle
Test

#>

param(
    ## The name for the dynamic variable
    [Parameter(Mandatory = $true)]
    $Name,

    ## The scriptblock to invoke when getting the value of the variable
    [Parameter(Mandatory = $true)]
    [ScriptBlock] $Getter,

    ## The scriptblock to invoke when setting the value of the variable
    [ScriptBlock] $Setter
)

Set-StrictMode -Version 3

Add-Type @"
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace Lee.Holmes
{
    public class DynamicVariable : PSVariable
    {
        public DynamicVariable(
            string name,
            ScriptBlock scriptGetter,
            ScriptBlock scriptSetter)
                : base(name, null, ScopedItemOptions.AllScope)
        {
            getter = scriptGetter;
            setter = scriptSetter;
        }
        private ScriptBlock getter;
        private ScriptBlock setter;

        public override object Value
        {
            get
            {
                if(getter != null)
                {
                    Collection<PSObject> results = getter.Invoke();
                    if(results.Count == 1)
                    {
                        return results[0];
                    }
                    else
                    {
                        PSObject[] returnResults =
                            new PSObject[results.Count];
                        results.CopyTo(returnResults, 0);
                        return returnResults;
                    }
                }
                else { return null; }
            }
            set
            {
                if(setter != null) { setter.Invoke(value); }
            }
        }
    }
}
"@

## If we've already defined the variable, remove it.
if(Test-Path variable:\$name)
{
    Remove-Item variable:\$name -Force
}

## Set the new variable, along with its getter and setter.
$executioncontext.SessionState.PSVariable.Set(
    (New-Object Lee.Holmes.DynamicVariable $name,$getter,$setter))

ありますが、ここでSet-StrictMode -Version 3説明されているように、PowerShell V2.0セッションでフレームワーク4.0をロードできる場合は、-バージョン2として設定できます。

OPの用途は次のとおりです。

 New-DynamicVariable -Name GLOBAL:now -Getter { (get-date).datetime }

ここで、私が他の回答で使用した方法についてのLee Holmesの評価(本当の欠陥が何であるかが明らかです):

Note
There are innovative solutions on the Internet that use PowerShell's debugging facilities to create a breakpoint that changes a variable's value whenever you attempt to read from it. While unique, this solution causes PowerShell to think that any scripts that rely on the variable are in debugging mode. This, unfortunately, prevents PowerShell from enabling some important performance optimizations in those scripts.
于 2013-01-24T14:13:17.440 に答える
3

使用しない理由:

Add-Content $LogFile -Value "$((Get-Date).DateTime): XXXXX"

これにより、毎回現在の日時が取得されます。$( )文字列に挿入する前に、PowerShellで式を実行(日時を取得)する内部にあることに注意してください。

于 2013-01-23T14:45:50.420 に答える
2

2つのコマンドを関数でラップして、1回の呼び出しだけにしますか?

function add-log{
(param $txt)
$DateTime = get-date  | select -expand datetime
Add-Content $LogFile -Value "$DateTime: $txt"
}
于 2013-01-23T14:45:40.527 に答える
1

これらの他の方法(率直に言って、代わりに使用する可能性があります-ブレークポイントアプローチを除く)に加えて、次の実装を提供できるScriptPropertyを使用してカスタムオブジェクトを作成できます。

$obj = new-object pscustomobject
$obj | Add-Member ScriptProperty Now -Value { Get-Date }
$obj.now
于 2013-01-23T14:45:47.913 に答える
1

使用PsBreakPoint

$act= @'
$global:now = (get-date).datetime
'@
$global:sb = [scriptblock]::Create($act)
$now = Set-PSBreakpoint -Variable now -Mode Read -Action $global:sb

呼び出しは、$now現在の更新された日時値を返します

一発ギャグ:

$now = Set-PSBreakpoint -Variable now -Mode Read -Action { $global:now = (get-date).datetime }
于 2013-01-23T14:59:25.817 に答える