PowerShell - 添加内容 - 无法将多个变量添加到文件中

时间:2018-04-26 09:31:21

标签: powershell

我试图将表达式添加到日志文件中,该日志文件包含Date,Time一些数据由";"分隔。不幸的是,每当我更改-value括号中项目的位置时,我都会收到错误。

什么似乎错了?

这是代码:

Add-Content -path C:\...\outlog.txt -Value($Date + ';' + $Time + ';Checked;' + $strFileName)

这是错误:

Cannot convert argument "1", with value: ";", for "op_Addition" to type "System.TimeSpan": "Cannot convert 
value ";" to type "System.TimeSpan". Error: "String was not recognized as a valid TimeSpan.""
At C:\...\Untitled1.ps1:8 char:64
+ ... \outlog.txt -Value($($Date + ';' + $Time + ';'+ $str))
+                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

1 个答案:

答案 0 :(得分:1)

试试这个 -

Add-Content -path C:\...\outlog.txt -Value("$Date; $Time; Checked; $strFileName")

如果您查看get-help Add-Content -full,并查看-value参数,您会看到 -

-Value <Object[]>
    Specifies the content to be added. Type a quoted string, such as "This data is for internal use only", or
    specify an object that contains content, such as the DateTime object that Get-Date generates.

    You cannot specify the contents of a file by typing its path, because the path is just a string, but you can
    use a Get-Content command to get the content and pass it to the Value parameter.

    Required?                    true
    Position?                    1
    Default value                None
    Accept pipeline input?       True (ByPropertyName, ByValue)
    Accept wildcard characters?  false

它表示它需要quoted stringobject that contains content。它在您的案例中缺失,因此+运算符正在尝试添加$datetime