如何在PowerShell中自动执行Write-Host生成的GAMADV-XTD3命令?
问题:如何让PowerShell生成的GAMADV-XTD3命令自动执行?
我正在使用GAMADV-XTD3命令行工具,在Google Workspace中自动化处理邮箱签名、云端硬盘权限等事务。近期需要为员工设置外出自动回复,编写了PowerShell脚本用于输入用户邮箱、休假起止日期,生成对应的GAM命令字符串,但目前只能手动复制粘贴执行。请问如何实现命令的自动执行?
当前使用的脚本如下:
$email = Read-Host -Prompt "enter email" $startdate = Read-Host -Prompt "enter startdate" $enddate = Read-Host -Prompt "enter enddate" Write-Host "gam user $email vacation on subject "`"Out of Office from $startdate - $enddate`"" message "`"Out of the office from $startdate to $enddate. If there are any issues or emergencies that you need addressed in my absence please contact my manager `"" html startdate $startdate enddate $enddate"
解决方案
不需要通过Write-Host输出命令再手动执行,直接在PowerShell中调用GAM命令即可,PowerShell会自动完成变量替换和参数传递:
方法一:直接调用GAM命令(推荐)
这种方式避免了字符串转义的麻烦,也更安全(无命令注入风险):
$email = Read-Host -Prompt "enter email" $startdate = Read-Host -Prompt "enter startdate" $enddate = Read-Host -Prompt "enter enddate" # 直接执行GAM命令,无需生成字符串 gam user $email vacation on ` subject "Out of Office from $startdate - $enddate" ` message "Out of the office from $startdate to $enddate. If there are any issues or emergencies that you need addressed in my absence please contact my manager" ` html ` startdate $startdate ` enddate $enddate
方法二:构造命令字符串后执行(不推荐)
如果因特殊需求必须先生成命令字符串,可使用Invoke-Expression执行,但需注意变量内容的安全性:
$email = Read-Host -Prompt "enter email" $startdate = Read-Host -Prompt "enter startdate" $enddate = Read-Host -Prompt "enter enddate" # 构造命令字符串(注意双引号的转义) $gamCommand = "gam user $email vacation on subject `"Out of Office from $startdate - $enddate`" message `"Out of the office from $startdate to $enddate. If there are any issues or emergencies that you need addressed in my absence please contact my manager`" html startdate $startdate enddate $enddate" # 执行命令字符串 Invoke-Expression $gamCommand
内容的提问来源于stack exchange,提问作者Latif Bouzoubaa
相关产品推荐
相关产品推荐

