Board logo

标题: [问题求助] PowerShell如何把重复的代码定义为一个函数 [打印本页]

作者: 5i365    时间: 2022-1-25 11:15     标题: PowerShell如何把重复的代码定义为一个函数

下面代码的红, 蓝字部分, 都是重复的, 怎样定义为一个函数,
例如定义为 ifsuccess

红色字地方, 使用 ifsuccess glob
蓝色字地方, 使用 ifsuccess zip


$glob = New-Object Chilkat.Global
$success = $glob.UnlockBundle("Anything")
if ($success -ne $true)
{
        $($glob.LastErrorText)
        exit
}


$zip = New-Object Chilkat.Zip

$success = $zip.NewZip("test.zip")
if ($success -ne $true)
{
        $($zip.LastErrorText)
        exit
}


$recurse = $true
$success = $zip.AppendFiles("c:/temp/a/*", $recurse)
if ($success -ne $true)
{
        $($zip.LastErrorText)
        exit
}


$success = $zip.WriteZipAndClose()
if ($success -ne $true)
{
        $($zip.LastErrorText)
        exit
}


$("Zip Created!")
作者: idwma    时间: 2022-1-25 15:52

  1. function ifsuccess{
  2. if ($success -ne $true)
  3. {
  4.         $(iex('$'+$args+'.LastErrorText'))
  5.         exit
  6. }
  7. }
复制代码

作者: 5i365    时间: 2022-1-25 17:38

回复 2# idwma


    还真能生效, 大侠 牛X
作者: 5i365    时间: 2022-1-25 17:54

回复 2# idwma


    为什么加个 iex 呢? 下面这样写好理解, 但是只会输出   $zip.LastErrorText
  1. function ifsuccess{
  2. if ($success -ne $true)
  3. {
  4.         $('$'+$args+'.LastErrorText')
  5.         exit
  6. }
  7. }
复制代码

作者: idwma    时间: 2022-1-25 18:11

回复 4# 5i365


    help iex帮助里有说明




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2