【问题标题】:powershell function: why more values are returned?powershell 函数:为什么返回更多的值?
【发布时间】:2020-01-28 12:34:06
【问题描述】:

大家早上好, 我正在编写我的第一个 ps 脚本: 一个具有 3 个输入字符串和一个返回的输出字符串的函数,但对我来说听起来很奇怪: 这是我的代码:

function MyLogger($MyString, $MyFileName, $MyFilePath)
{

    $FullLogFile = ($MyFilePath +"\"+ $MyFileName)
    $DateForLog =  Get-Date -Format "yyyy-MM-dd HH:mm:ss" 
    $LogRow = ($DateForLog + " " + $MyString)
    return $LogRow
}

$LogFile = "logname.txt"

$dir = "C:\psscript\workingwithfiles"

$mystr = "stringgggg"

$ret = MyLogger($mystr, $LogFile, $dir)

Write-Host "***************print function res**************"

Write-Host $ret

Write-Host "***************end print function res**************"

为什么函数输出(返回$LogRow)是这样的:

2020-01-28 13:11:03 stringgggg logname.txt C:\psscript\workingwithfiles

不仅如此?

2020-01-28 13:11:03 stringgggg 

完整输出:

***************print function res**************

2020-01-28 13:11:03 stringgggg logname.txt C:\psscript\workingwithfiles

***************end print function res**************

谢谢大家

【问题讨论】:

  • 传递给 PowerShell 命令的参数应该用空格而不是逗号分隔。将MyLogger($mystr, $LogFile, $dir) 更改为MyLogger $mystr $LogFile $dir
  • Mathias R. Jessen - 非常感谢,不知道,这是我的第一个脚本,我今晚必须结束它,所以我只是从互联网上复制的,我没有是时候学习它了...非常感谢您

标签: function powershell return-value


【解决方案1】:

更好地使用 PowerShell 语法:

function MyLogger
{
    param(  [string]$MyString, 
            [string]$MyFileName, 
            [string]$MyFilePath)


    $FullLogFile = ($MyFilePath +"\"+ $MyFileName)
    $DateForLog =  Get-Date -Format "yyyy-MM-dd HH:mm:ss" 
    $LogRow = ($DateForLog + " " + $MyString)
    return $LogRow
}

$LogFile = "logname.txt"

$dir = "C:\psscript\workingwithfiles"

$mystr = "stringgggg"

$ret = MyLogger -MyString $mystr -MyFileName $LogFile -MyFilePath $dir

Write-Host "***************print function res**************"

Write-Host $ret

Write-Host "***************end print function res**************"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2019-01-08
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多