PowerShell常用命令
·
2 min read
最近WebShell需要支持PowerShell环境下的文件管理,为了实现文件相关操作需要了解下相关命令。这里总结下
压缩文件夹
Compress-Archive -Path '${formatted}' -DestinationPath '${zipTempPath')}'
复制文件/文件夹
Copy-Item -Path '${filePath}' -Destination '${dirPath}' -Recurse -Force
移动文件/文件夹
Move-Item -Path '${filePath}' -Destination '${targetPath}' -Force
解压ZIP包
Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force
注意:Path参数必须zip后缀,否则报错。
删除文件/文件夹
Remove-Item -Path '${formatted}' -Recurse -Force
创建文件夹
New-Item -Path '${formatted}' -ItemType Directory
重命名
Rename-Item -Path '${formatted}' -NewName '${newName}'
多命令执行
如果需要执行多个命令,不同于Linux下以 &&
连接,powershell需要使用;
Move-Item -Path '${path}' -Destination '${path}.zip';Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force
常见问题
w2:无法加载文件 C:\Program Files\node js\w2.ps1,因为在此系统上禁止运行脚本。
# 管理员身份运行powershell
# 检查当前的 PowerShell 脚本执行策略
get-ExecutionPolicy
# 设置 PowerShell 的执行策略为 RemoteSigned,
set-executionpolicy remotesigned
Path包含[]
如果path中包含[],比如执行Move-Item,不报错,但执行不成功。原因是无论单双引号,路径中包含的半角[]均会被视为正则。解决办法2个
增加`对[]进行转义
比如
Move-Item -Path 'C:\Windows\Temp\`[漫威`] xxx.jar_1717312576427' -Destination 'C:\Windows\system32\config\systemprofile\`[漫威`] xxx.jar' -Force
将
-Path
修改为-LiteralPath
Move-Item -LiteralPath 'C:\Windows\system32\config\systemprofile\123 456\[漫威] xxx.jar' -Destination 'C:\Windows\system32\config\systemprofile\789\[漫威] xxx.jar' -Force
New-Item不支持LiteralPath参数,直接使用Path即可,也会被视为字符串。
写在最后
在windows时下执行命令时有PowerShell和CMD选择,如何选择呢。可以参考微软说法,官方是提倡使用PowerShell,CMD已进入维护阶段。