【问题标题】:Strings not working in my function as parameters powershell [duplicate]字符串在我的函数中不起作用作为参数powershell [重复]
【发布时间】:2016-11-21 09:34:48
【问题描述】:
function cee([string]$a,
[string]$b)
{
    Write-Host $a | ft
    $a.GetType()
    Write-Host $b | ft
    $b.GetType()
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($a,$b)
}

cee('C:\FAKE','C:\zipfile.zip')

当在这个庄园运行时,它会失败并出现以下错误:

C:\FAKE'C:\zipfile.zip

IsPublic IsSerial 名称 BaseType
-------- -------- ---- --------
True True String System.Object >

True 真字符串 System.Object
使用“2”参数调用“CreateFromDirectory”的异常:“不支持给定的 >path 格式。” 在行:10 字符:9 + [System.IO.Compression.ZipFile]::CreateFromDirectory($a, + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NotSupportedException

如果我将 'C:\FAKE\' 和 'C:\zipfile.zip' 存储为变量,手动运行每一行并将变量作为 $a 和 $b 的输入,它就可以正常工作。

如果我设置 [Parameter(Mandatory=$True)] ,运行函数,然后输入 C:\假\ 和 C:\zipfile.zip 在提示符下,它工作得很好。

【问题讨论】:

  • @PetSerAl 你用什么搜索词来找到另一个答案?很明显,你的 search-fu 比我的要好得多。还是知道我做错了什么让你更容易找到它?我宁愿做一个更好的搜索工作,而不是让社区陷入重复。
  • 我在搜索中使用[powershell] parenthesis。我不是第一次在调用 PowerShell 函数时看到这个错误,所以我已经知道要搜索什么了。
  • @PetSerAl 也谢谢你。

标签: string function powershell zipfile


【解决方案1】:

您没有正确调用您的函数。你使用这样的函数:

cee 'C:\FAKE' 'C:\zipfile.zip'

或者更全面地说,通过名称调用参数:

cee -a 'C:\FAKE' -b 'C:\zipfile.zip'

【讨论】:

  • 啊,是的,谢谢。我知道我的语法一定有问题。习惯 powershell 做事的方式很有趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多