PowerShell提取子字符串:如何隔离任务名称“FWI Reboot”
Got it, let's break down how to pull "FWI Reboot" from your TaskName: \FWI Reboot output. Here are a few practical, PowerShell-native ways to do this:
Method 1: Split the String Directly
Since your output follows a fixed format (TaskName: \[TaskName]), you can use the -split operator to split the string at the : \ delimiter and grab the second part:
# Assuming $Taskname holds your output line: "TaskName: \FWI Reboot" $extractedTaskName = ($Taskname -split ': \\')[1] Write-Host $extractedTaskName # Outputs: FWI Reboot
The double backslash (\\) is needed to escape the literal backslash in the split pattern—PowerShell treats backslashes as escape characters in regex mode (which -split uses by default).
Method 2: Use Regular Expression Matching
For more flexibility (in case the output format ever changes slightly), regex is a solid choice. We'll use -match to capture everything after the \ character:
$Taskname = "TaskName: \FWI Reboot" if ($Taskname -match 'TaskName: \\(.+)') { $extractedTaskName = $matches[1] Write-Host $extractedTaskName # Outputs: FWI Reboot }
The regex pattern TaskName: \\(.+) targets the exact prefix, then captures all characters after the escaped backslash into a group. The $matches variable holds the captured groups after a successful -match.
Method 3: Optimize the Entire Workflow (Skip the Intermediate File)
You can also streamline your original script to avoid writing to a text file entirely—this cuts down on unnecessary IO operations and gets you the task name directly:
$String = "shutdown.exe -r -f" # Pipe the schtasks output directly through both Select-String calls, then extract the name $taskLine = schtasks /query /v /fo LIST | Select-String $String -Context 7 -SimpleMatch | Select-String 'TaskName' -SimpleMatch if ($taskLine -match 'TaskName: \\(.+)') { $extractedTaskName = $matches[1] Write-Host $extractedTaskName # Outputs: FWI Reboot }
All three methods will give you the isolated "FWI Reboot" string—pick the one that fits your script's structure best!
内容的提问来源于stack exchange,提问作者Sam Safronoff

