您可以将powershell命令传递给powershell.exe,如下所示:
PowerShell -Command {Get-EventLog -LogName security}
但是如果命令包含 {或} 怎么办?如:
dir z:\test -fi "*.tmp" -r | ?{$_.creationtime -le (Get-Date).adddays(-30)} | del
感谢。
答案 0 :(得分:2)
命令参数可以接受脚本块和字符串,在顶部示例中,{}表示脚本块。所以只需将命令括在“”而不是{}。
PowerShell.exe -Command "dir z:\test -fi "*.tmp" -r | ?{$_.creationtime -le (Get-Date).adddays(-30)} | del"
唯一要记住的是,如果您将其指定为上面的字符串,则Command必须是您指定的最后一个参数,因为它之后的所有内容都被解释为您要运行的命令。
答案 1 :(得分:1)
PowerShell.exe -Command "dir z:\test -fi "*.tmp" -r | ?{$_.creationtime -le (Get-Date).adddays(-30)} | del"
答案 2 :(得分:1)
另一种可能性是对命令进行编码:
$command = "dir z:\test -fi '.tmp' -r | ?{$_.creationtime -le (Get-Date).adddays(-30)} | del "
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
答案 3 :(得分:0)
使用Invoke-Expression可以是一个选项
PowerShell -Command {Invoke-Expression "dir z:\test -fi `"*.tmp`" -r | ?{`$_.creationtime -le (Get-Date).adddays(-30)} | del"}