找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 14280|回复: 4

[问题求助] PowerShell如何把重复的代码定义为一个函数

[复制链接]
发表于 2022-1-25 11:15:08 | 显示全部楼层 |阅读模式
下面代码的红, 蓝字部分, 都是重复的, 怎样定义为一个函数,
例如定义为 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!")
发表于 2022-1-25 15:52:17 | 显示全部楼层
  1. function ifsuccess{
  2. if ($success -ne $true)
  3. {
  4.         $(iex('$'+$args+'.LastErrorText'))
  5.         exit
  6. }
  7. }
复制代码

评分

参与人数 1技术 +1 收起 理由
5i365 + 1 牛X, 乐于助人

查看全部评分

 楼主| 发表于 2022-1-25 17:38:27 | 显示全部楼层
回复 2# idwma


    还真能生效, 大侠 牛X
 楼主| 发表于 2022-1-25 17:54:01 | 显示全部楼层
回复 2# idwma


    为什么加个 iex 呢? 下面这样写好理解, 但是只会输出   $zip.LastErrorText
  1. function ifsuccess{
  2. if ($success -ne $true)
  3. {
  4.         $('$'+$args+'.LastErrorText')
  5.         exit
  6. }
  7. }
复制代码
发表于 2022-1-25 18:11:47 | 显示全部楼层
回复 4# 5i365


    help iex帮助里有说明
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 05:24 , Processed in 0.019394 second(s), 9 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表