Common PowerShell Commands

Common PowerShell Commands

3月 31, 2024 · 1 分钟阅读时长 · 421 字 · -阅读 -评论

Recently, WebShell needed to support file management under PowerShell. To perform file-related operations, it’s necessary to understand the relevant commands. Here’s the summary.

https://static.1991421.cn/2024/2024-03-31-114718.jpeg

Compress Folder

Compress-Archive -Path '${formatted}' -DestinationPath '${zipTempPath}'

Copy File/Folder

Copy-Item -Path '${filePath}' -Destination '${dirPath}' -Recurse -Force

Move File/Folder

Move-Item -Path '${filePath}' -Destination '${targetPath}' -Force

Extract ZIP Archive

Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force

Delete File/Folder

Remove-Item -Path '${formatted}' -Recurse -Force

Create Folder

New-Item -Path '${formatted}' -ItemType Directory

Rename

Rename-Item -Path '${formatted}' -NewName '${newName}'

Multiple Command Execution

If need to execute multiple commands, unlike using && in Linux, PowerShell requires ;.

Move-Item -Path '${path}' -Destination '${path}.zip';Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force

Common Issues

w2: Cannot load file C:\Program Files\node js\w2.ps1 because running scripts is disabled on this system.

# Run PowerShell as administrator

# Check the current PowerShell script execution policy
get-ExecutionPolicy
# Set PowerShell's execution policy to RemoteSigned
set-executionpolicy remotesigned

Path Contains Square Brackets []

If the path contains [], for example, executing Move-Item doesn’t throw an error but the execution is unsuccessful. The reason is that [] in the path is treated as regex, regardless of whether it’s a single or double quote. There are two solutions:

  1. Escape []

    For example:

    Move-Item -Path 'C:\\Windows\\Temp\\`[漫威`] xxx.jar_1717312576427' -Destination 'C:\\Windows\\system32\\config\\systemprofile\\`[漫威`] xxx.jar' -Force
    
  2. Change -Path to -LiteralPath

    Move-Item -LiteralPath 'C:\\Windows\\system32\\config\\systemprofile\\123 456\\[漫威] xxx.jar' -Destination 'C:\\Windows\\system32\\config\\systemprofile\\789\\[漫威] xxx.jar' -Force
    

Final Thoughts

When executing Windows commands, you can choose between PowerShell and CMD. According to Microsoft’s recommendation, using PowerShell is advised, as CMD has entered the maintenance phase.

Documentation

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源