AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / 问题

Perguntas[powershell](coding)

Martin Hope
Simon Elms
Asked: 2025-04-28 19:32:17 +0800 CST

Crie uma instância no PowerShell de um tipo .NET sem um construtor

  • 9

Tenho um script do PowerShell para configurar um site no IIS. Ele inclui as seguintes funções:

function Set-IisWebsiteBinding (
    [Parameter(Mandatory = $true)]
    [string]$SiteName, 
    
    [Parameter(Mandatory = $true)]
    [Microsoft.Web.Administration.Site]$Website,
    
    [Parameter(Mandatory = $true)]
    [array]$WebsiteBindingSettings
)
{
    # Set up website bindings ...
}

Estou tentando escrever testes para a função no Pester. Gostaria de criar um objeto fictício $Website para passar para a função em teste. O problema é que o Microsoft.Web.Administration.Sitetipo não tem construtor. Como posso criar um objeto do tipo Microsoft.Web.Administration.Siteno PowerShell se ele não tem construtor?

Eu poderia criar um via , IISServerManager.Sites.CreateElement()mas gostaria de evitar ter que depender do uso de um IISServerManager. Alternativamente, eu poderia me livrar da coerção de tipo para o parâmetro de função $Website, para permitir que o código de teste passasse uma tabela de hash em vez de um objeto Microsoft.Web.Administration.Site. No entanto, prefiro manter a coerção de tipo para que fique óbvio para os futuros mantenedores do script qual $Websiteé o tipo do objeto.

Existe alguma maneira de contornar essa falta de um construtor sem usar um real IISServerManagerou remover a coerção de tipo?

powershell
  • 1 respostas
  • 92 Views
Martin Hope
Stan
Asked: 2025-04-26 04:22:45 +0800 CST

Os valores do nome do grupo Regex podem conter mais de 2 palavras

  • 6

Este código funciona bem

$pop = New-Object -ComObject wscript.shell
$string = "John Adams, Age: 204, Email: [email protected]"
# Regular expression pattern with named groups
$regex = '(?<Name>\w+\s\w+),\sAge:\s(?<Age>\d+),\sEmail:\s(?<Email>[^\s]+)'
# Apply the regex match
if ($string -match $regex) {
    # Access the groups using automatic variable $matches
    $name = $matches['Name']
    $age = $matches['Age']
    $email = $matches['Email']
    $pop.popup("Name: $name`nAge: $age`nEmail: $email",5,"Success",4096)
} else {
    $pop.popup("No Matches found.",4,"Oh Oh",4096)
}
Exit

Mas se eu alterar a string para começar com John Quincey Adams, o grupo de nomes retornará apenas Quincey Adams. Sei que poderia adicionar um \w+\s extra, mas existe uma maneira de capturar um nome com qualquer número de palavras para o grupo em um sentido genérico?

powershell
  • 1 respostas
  • 33 Views
Martin Hope
Maarten ten Velden
Asked: 2025-04-22 22:43:41 +0800 CST

Preservando aspas no arquivo Batch %*

  • 8

Quero encaminhar %*para um script do PowerShell a partir de um script em lote, que já funciona mais ou menos. O único problema é que não consigo encaminhar argumentos com espaços corretamente.

Exemplo.bat..

@echo off

set cwd=%~dp0
set argv=%*
powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%cwd%Example.ps1' %argv%"

Exemplo.ps1..

Param(
  $Message
)
If (!$Message)
{
  $Message = "Hello!!!"
}
Write-Host $Message

Eu consigo fazer isso ./Example.bat Ohmuito bem, o que imprime Oh. No entanto, ./Example.bat "Oh no"só imprime Ohtambém. ./Example "'Oh no'"funciona, mas não é limpo, pois o uso dos scripts não é mais idêntico, o que significa que qualquer uso dele se torna fortemente acoplado, o que eu não quero.

powershell
  • 4 respostas
  • 109 Views
Martin Hope
Ralf_Reddings
Asked: 2025-04-22 03:33:57 +0800 CST

'usando:' e outros métodos não funcionam com start-threadJob para carregar objetos na sessão de trabalho

  • 7

executar o seguinte retorna um erro:

$job=Start-ThreadJob -name maya6 -InitializationScript {. $using:profile} -ScriptBlock {ichild}   #this is an alias defined in the profile

erro:

InvalidOperation: A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer.
ichild: The term 'ichild' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Eu também tentei:

$job=start-threadJob {. $args ; ichild} -ArgumentList $profile      #ichild is an alias defined in my profile

e quando eu uso receive-job $jobele congela meu prompt e continuo recebendo o seguinte erro:

Oops, something went wrong.  
Please report this bug with ALL the details below, including both the 'Environment' and 'Exception' sections.  
Please report on GitHub: https://github.com/PowerShell/PSReadLine/issues/new?template=Bug_Report.yaml  
Thank you!  
  
### Environment  
PSReadLine: 2.3.4  
PowerShell: 7.4.6  
OS: Microsoft Windows 10.0.26100  
BufferWidth: 170  
BufferHeight: 21  
  
Last 49 Keys:

Pensei usingque fosse especificamente para esse commandlet...

estou no pwsh7.4

powershell
  • 1 respostas
  • 44 Views
Martin Hope
Lusiiky
Asked: 2025-04-20 07:36:16 +0800 CST

Como faço para reorientar um script do Powershell após um Start-Process?

  • 6

Tenho um script Pwsh com um menu que executa diversas operações diferentes para me ajudar no dia a dia.

Para uma das operações, eu inicio um processo com Start-Process, exceto que ele focaliza a janela iniciada, mas para facilitar eu gostaria que o script fosse focalizado novamente após o lançamento e não o processo iniciado.

Não quero usar os argumentos “PassThru” ou “NoNewWindow” porque não quero que o processo iniciado seja iniciado no script, nem “WindowStyle” com Minimized porque isso focaliza o processo iniciado de qualquer maneira, nem Hidden porque ainda preciso ver a janela do processo em algum lugar.

Eu tentei esse método que parece funcionar melhor:

Start-Process -FilePath "MyProcessPath"

Start-Sleep -Seconds 1

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WinAp {
 [DllImport("user32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 public static extern bool SetForegroundWindow(IntPtr hWnd);

 [DllImport("user32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
"@

$p = Get-Process | Where-Object { $_.MainWindowTitle -like "*ScriptTitle*" -and $_.ProcessName -eq "powershell" }

$h = $p.MainWindowHandle
[void] [WinAp]::SetForegroundWindow($h)
[void] [WinAp]::ShowWindow($h, 1)

Mas, infelizmente, não funciona. Parece que faz alguma coisa na janela, pois ela pisca na barra de tarefas, mas não foca. Parece que, embora o script seja executado como administrador, ele não funciona para focar uma janela de administrador como essa?

Entretanto, para outra parte do meu script, fiz isso:

$tempPath = [System.IO.Path]::GetTempFileName().Replace(".tmp", ".vbs")
$code = @'
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate "App.exe"
WScript.Sleep 250
WshShell.SendKeys "{ENTER}"
'@

$code | Out-File $tempPath -Encoding ASCII
Start-Process "wscript.exe" $tempPath -Wait
Remove-Item $tempPath

E funciona bem... ele foca a janela e, em seguida, pressiona a tecla solicitada (embora essa parte não seja necessária no meu problema atual). Tentei com o meu script, mas... nada. Principalmente porque o aplicativo é iniciado com o script, então como administrador também, eu acho? Então, não entendo por que funciona, mas não para o script em si.

Obrigado!

powershell
  • 3 respostas
  • 113 Views
Martin Hope
Goulven
Asked: 2025-04-19 22:26:06 +0800 CST

Prompt do Powershell, caractere vermelho à direita em caso de erro

  • 7


Estou tentando criar meu próprio prompt do Powershell em $profile.

Por enquanto, tenho o seguinte:

$ESC = [char]27
$RESET = "$ESC[0m"
$pwd = $executionContext.SessionState.Path.CurrentLocation

function prompt {
  $fontColor = "2;192;192;192m"
  $backColor = "2;64;96;128m"
  $shdwColor = "2;32;48;64m"

  $main   = "$RESET$ESC[38;$fontColor$ESC[48;$backColor"
  $shadow = "$RESET$ESC[38;$backColor$ESC[48;$shdwColor"
  $end    = "$RESET$ESC[38;$shdwColor"

  #      "$main $pwd  $shadow $end ";
  #      "$main $pwd  $shadow $end$RESET ";
  #      "$main $pwd  $shadow $end$ESC[0m ";
  #      "$main $pwd  $shadow $end$ESC[0 ";
  #      "$main $pwd  $shadow $end $RESET";
  #      "$main $pwd  $shadow $end $ESC[0m";
  return "$main $pwd  $shadow $end $ESC[0";
}

O que resulta da seguinte forma:
Perfil do Powershell como segue: C:\Windows\System32 / /

Quando eu digito lsou dir(por exemplo), tudo funciona bem.

Entretanto, quando digito uma string, meu zero à direita (de $ESC[0) aparece vermelho, e quando fecho a string, o zero muda para branco.
Prompt do Powershell com um "0" aparecendo

Isso também aparece quando coloco $RESETou $ESC[0mem vez de $ESC[0(mas com um "m" em vez de "0"), e quando os removo são os que aparecem em vermelho...
Mesma imagem acima, mas com  como caractere final

Também podemos ver que no prompt padrão do Powershell, o ">" fica vermelho quando abrimos uma string:
Prompt padrão do Powershell com ">" vermelho na abertura da string

Alguém já passou pelo mesmo problema ao fazer prompts e, se sim, como você removeu essa coloração ou como você se adaptou?

Obrigado !

powershell
  • 2 respostas
  • 62 Views
Martin Hope
marion
Asked: 2025-04-19 20:32:55 +0800 CST

Como faço para corrigir um problema do Powershell com a seleção de botões?

  • 7

Usei o ChatGPT para gerar o código e entender como fazer isso sozinho, e funciona na maior parte do tempo. O script verifica minhas pastas de TV e Filmes em busca de arquivos ausentes para melhorar o funcionamento do Plex (folder.jpg, theme.mp3 e assim por diante) e mostra quais estão faltando e quantos.

Funciona perfeitamente na pasta de filmes, mas eu não consigo (nem a IA) descobrir como consertar isso clicando no botão TV ou TV encerrada e fazendo com que ele pesquise nessas pastas.

Meu melhor palpite é que a variável $pathMap na linha 167 é a chave e não está sendo atualizada corretamente para esta parte - $global:fixedPath = $pathMap

Alguém poderia corrigir isso e me explicar como descobrir como fazer isso?

Windows 10 22H2 e Powershell PSVersão 5.1.19041.5737

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    
    # Create form
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Marion's Plex checker"
    $form.Size = New-Object System.Drawing.Size(700, 700)
    $form.StartPosition = "CenterScreen"
    
    # Fixed folder path
    $fixedPath = "D:\ServerFolders\Videos\02 - Movies"
    
    # Path label
    $label = New-Object System.Windows.Forms.Label
    $label.Text = "Checking subfolders in: $fixedPath"
    $label.Location = New-Object System.Drawing.Point(120, 20)
    $label.Size = New-Object System.Drawing.Size(550, 20)
    $form.Controls.Add($label)
    
    # Summary label
    $summaryLabel = New-Object System.Windows.Forms.Label
    $summaryLabel.Text = ""
    $summaryLabel.Location = New-Object System.Drawing.Point(120, 45)
    $summaryLabel.Size = New-Object System.Drawing.Size(550, 20)
    $form.Controls.Add($summaryLabel)
    
    # Output box
    $logBox = New-Object System.Windows.Forms.TextBox
    $logBox.Multiline = $true
    $logBox.ScrollBars = "Vertical"
    $logBox.Location = New-Object System.Drawing.Point(120, 75)
    $logBox.Size = New-Object System.Drawing.Size(550, 350)
    $logBox.Anchor = "Top,Bottom,Left,Right"
    $logBox.ReadOnly = $true
    $form.Controls.Add($logBox)
    
    # Search file buttons (on the left)
    $fileTypes = @("theme.mp3", "folder.jpg", "background.jpg", "poster.jpg")
    $fileButtons = @{}
    $yPos = 20
    $global:selectedFile = "theme.mp3"
    
    foreach ($file in $fileTypes) {
        $btn = New-Object System.Windows.Forms.Button
        $btn.Text = $file
        $btn.Tag = $file
        $btn.Location = New-Object System.Drawing.Point(10, $yPos)
        $btn.Size = New-Object System.Drawing.Size(100, 30)
        $form.Controls.Add($btn)
        $fileButtons[$file] = $btn
        $yPos += 40
    
        $btn.Add_Click({
            $global:selectedFile = $this.Tag
    
            # Reset styles
            foreach ($b in $fileButtons.Values) {
                $b.UseVisualStyleBackColor = $true
            }
    
            # Highlight selected
            # Reset styles
            foreach ($b in $fileButtons.Values) {
                $b.UseVisualStyleBackColor = $true
                $b.BackColor = [System.Drawing.SystemColors]::Control
            }
    
            # Highlight selected
            $this.UseVisualStyleBackColor = $false
            $this.BackColor = 'LightBlue'
    
            $summaryLabel.Text = "Selected file: $global:selectedFile"
        })
    }
    
    # Scan button
    $scanButton = New-Object System.Windows.Forms.Button
    $scanButton.Text = "Scan"
    $scanButton.Location = New-Object System.Drawing.Point(10, 440)
    $scanButton.Size = New-Object System.Drawing.Size(100, 30)
    $form.Controls.Add($scanButton)
    
    # Create a new button for Movies, positioned to the right of the Scan button
    $moviesButton = New-Object System.Windows.Forms.Button
    $moviesButton.Text = "Movies"
    $moviesButton.Size = New-Object System.Drawing.Size(100, 30)
    $moviesButton.Location = New-Object System.Drawing.Point(120, 440)
    
    # Create a new button for TV, positioned next to the Movies button
    $tvButton = New-Object System.Windows.Forms.Button
    $tvButton.Text = "TV"
    $tvButton.Size = New-Object System.Drawing.Size(100, 30)
    $tvButton.Location = New-Object System.Drawing.Point(230, 440)
    
    # Create a new button for TV Ended, positioned next to the TV button
    $tvEndedButton = New-Object System.Windows.Forms.Button
    $tvEndedButton.Text = "TV Ended"
    $tvEndedButton.Size = New-Object System.Drawing.Size(100, 30)
    $tvEndedButton.Location = New-Object System.Drawing.Point(340, 440)  # Right of the TV button
    $tvEndedButton.Add_Click({
        Start-Process "D:\ServerFolders\Videos\TV (Ended)"  # Link to the TV Ended path
    })
    $form.Controls.Add($tvEndedButton)
    
    # Path variables for Movies, TV, and TV Ended
    $pathMap = @{
        "Movies"     = "D:\ServerFolders\Videos\02 - Movies"
        "TV Current" = "D:\ServerFolders\Videos\01 - TV"
        "TV Ended"   = "D:\ServerFolders\Videos\TV (Ended)"
    }
    
    # Default path for Movies
    $global:fixedPath = $pathMap["Movies"]
    $pathLabel.Text = "Scanning path: $global:fixedPath"
    
    # Add click event for Movies button
    $moviesButton.Add_Click({
        $global:fixedPath = $pathMap["Movies"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $moviesButton.BackColor = 'LightGreen'
        $tvButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvEndedButton.BackColor = [System.Drawing.SystemColors]::Control
        # Start scanning the Movies path
        Write-Host "Scanning Movies path: $global:fixedPath"
        Scan-Folder -path $global:fixedPath
    })
    
    # Add click event for TV button
    $tvButton.Add_Click({
        $global:fixedPath = $pathMap["TV Current"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $tvButton.BackColor = 'LightGreen'
        $moviesButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvEndedButton.BackColor = [System.Drawing.SystemColors]::Control
        # Start scanning the TV Current path
        Write-Host "Scanning TV path: $global:fixedPath"
        Scan-Folder -path $global:fixedPath
    })
    
    # Add click event for TV Ended button
    $tvEndedButton.Add_Click({
        $global:fixedPath = $pathMap["TV Ended"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $tvEndedButton.BackColor = 'LightGreen'
        $moviesButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvButton.BackColor = [System.Drawing.SystemColors]::Control
        # Start scanning the TV Ended path
        Write-Host "Scanning TV Ended path: $global:fixedPath"
        Scan-Folder -path $global:fixedPath
    })
    
    # Function to scan the folder
    function Scan-Folder {
        param(
            [string]$path
        )
        Write-Host "Scanning folder: $path"
        # Insert the actual folder scanning logic here
    }
    
    
    # Path variables for Movies, TV, and TV Ended
    $pathMap = @{
        "Movies"     = "D:\ServerFolders\Videos\02 - Movies"
        "TV Current" = "D:\ServerFolders\Videos\01 - TV"
        "TV Ended"   = "D:\ServerFolders\Videos\TV (Ended)"
    }
    
    # Default path for Movies
    $global:fixedPath = $pathMap["Movies"]
    
    # Add click event for Movies button
    $moviesButton.Add_Click({
        $global:fixedPath = $pathMap["Movies"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $moviesButton.BackColor = 'LightGreen'
        $tvButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvEndedButton.BackColor = [System.Drawing.SystemColors]::Control
        # Trigger the scanning logic
        Scan-Folder -path $global:fixedPath
    })
    
    # Add click event for TV button
    $tvButton.Add_Click({
        $global:fixedPath = $pathMap["TV Current"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $tvButton.BackColor = 'LightGreen'
        $moviesButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvEndedButton.BackColor = [System.Drawing.SystemColors]::Control
        # Trigger the scanning logic
        Scan-Folder -path $global:fixedPath
    })
    
    # Add click event for TV Ended button
    $tvEndedButton.Add_Click({
        $global:fixedPath = $pathMap["TV Ended"]
        $pathLabel.Text = "Scanning path: $global:fixedPath"
        # Change button colors to indicate active path
        $tvEndedButton.BackColor = 'LightGreen'
        $moviesButton.BackColor = [System.Drawing.SystemColors]::Control
        $tvButton.BackColor = [System.Drawing.SystemColors]::Control
        # Trigger the scanning logic
        Scan-Folder -path $global:fixedPath
    })
    
    # Function to scan the folder
    function Scan-Folder {
        param(
            [string]$path
        )
        Write-Host "Scanning folder: $path"
        # Insert the actual scanning logic here to process the folder
    }
    
      # Right of the Movies button
    $tvButton.Add_Click({
        Start-Process "D:\ServerFolders\Videos\01 - TV"  # Link to the TV path
    })
    $form.Controls.Add($tvButton)
      # Right of the Scan button
    $moviesButton.Add_Click({
        Start-Process "D:\ServerFolders\Videos\02 - Movies"  # Link to the Movies path
    })
    $form.Controls.Add($moviesButton)
    
    
    # Globals
    $global:missingItems = @()
    
    function Run-Scan {
        $logBox.Clear()
        $summaryLabel.Text = ""
        $log = @()
        $logPath = Join-Path $fixedPath "missing_${global:selectedFile}_log.txt"
        $csvPath = Join-Path $fixedPath "missing_${global:selectedFile}_report.csv"
        $global:missingItems = @()
    
        if (-not (Test-Path $fixedPath)) {
            [System.Windows.Forms.MessageBox]::Show("Invalid folder path.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
            return
        }
    
        $folders = Get-ChildItem -Path $fixedPath -Directory
    
        foreach ($folder in $folders) {
            $targetFile = Join-Path $folder.FullName $global:selectedFile
            if (-not (Test-Path -LiteralPath $targetFile)) {
                $global:missingItems += $folder
                $logLine = "$($folder.Name)"
                $logBox.AppendText($logLine + "`r`n")
                $log += $logLine
            }
        }
    
        if ($global:missingItems.Count -eq 0) {
            $summaryLabel.Text = "All folders have $($global:selectedFile)."
        } else {
            $summaryLabel.Text = "Missing $($global:selectedFile) from [$($global:missingItems.Count)] folders."
        }
    
        $log | Out-File -FilePath $logPath -Encoding UTF8
    
        $logBox.AppendText("`r`nLog saved to: $logPath`r`n")
        $exportButton.Enabled = $global:missingItems.Count -gt 0
    }
    
    $scanButton.Add_Click({ Run-Scan })
    
    
    # Export to CSV button
    $exportButton = New-Object System.Windows.Forms.Button
    $exportButton.Text = "Export to CSV"
    $exportButton.Location = New-Object System.Drawing.Point(10, 400)
    $exportButton.Size = New-Object System.Drawing.Size(100, 30)
    $exportButton.Enabled = $false
    $form.Controls.Add($exportButton)
    
    $exportButton.Add_Click({
        $csvPath = Join-Path $fixedPath "missing_$($global:selectedFile)_report.csv"
    
        $csvPath = Join-Path $fixedPath "missing_$($global:selectedFile)_report.csv"
        $headerLines = @(
            "File type: $($global:selectedFile)",
            "Total missing: $($global:missingItems.Count)`r`n"
        )
        $headerLines | Out-File -FilePath $csvPath -Encoding UTF8
    
        $global:missingItems | ForEach-Object {
            [PSCustomObject]@{ FolderName = $_.Name; Path = $_.FullName }
        } | Export-Csv -Path $csvPath -Append -NoTypeInformation -Encoding UTF8
    
        $logBox.AppendText("CSV exported to: $csvPath`r`n")
    
    })
    
    
    $form.Topmost = $true
    $form.Add_Shown({ $form.Activate() })
    [void]$form.ShowDialog()

powershell
  • 1 respostas
  • 69 Views
Martin Hope
mr_evans2u
Asked: 2025-04-16 22:24:32 +0800 CST

O PowerShell compara, mas exclui arquivos .txt

  • 6

Tudo o que quero fazer é verificar se o(s) arquivo(s) que estão na pasta 1 também estão na pasta 2. Tudo o que preciso verificar é o nome do arquivo. Para fins de teste, sei que são o(s) mesmo(s) arquivo(s), mas não estou obtendo os resultados de que são iguais. Também preciso excluir um arquivo *.txt da pasta 1, no qual também não tive sucesso e nem mesmo o incluí nos meus dois exemplos. Sei que isso deve ser bem simples, mas estou com dificuldades. Se for importante, os arquivos zip com os quais estou testando são chamados de N324RA_TEST__20240423221326.zip e N335RT_TEST_20250410020632.zip. Eles estarão na pasta 1 com certeza, preciso verificar se também estão na pasta 2 ou não. Se um ou ambos não estiverem na pasta 2, preciso saber

Eu tentei:


$Temp = "C:\MaxTemp\"
$Temp2 = "C:\MaxTemp2\"

$files1 = Get-ChildItem  -Path $Temp -Recurse | Where-Object { ! $_.PSIsContainer }
$files2 = Get-ChildItem  -Path $Temp2 -Recurse | Where-Object { ! $_.PSIsContainer } 
write-host "$files1"
write-host "$files2"

if ($fiiles1 -eq $files2)
{write-host "same"
}
else
{write-host "not same"}

Isso resultou em arquivos não são os mesmos. Eu também tentei isso, mas ele descobre que os arquivos são os mesmos de qualquer maneira.


$Temp = "C:\MaxTemp\"
$Temp2 = "C:\MaxTemp2\"

$files1 = Get-ChildItem -Path $Temp -Recurse | Where-Object { ! $_.PSIsContainer }
$files2 = Get-ChildItem -Path $Temp2 -Recurse | Where-Object { ! $_.PSIsContainer }

if ($comparison) {
    Write-Host "Differences found:"
    $comparison | ForEach-Object {
        if ($_.SideIndicator -eq "<=") {
            Write-Host "Only in $($Temp): $($_.Name)"
        } 

        }
    } 
  else{ ($_.SideIndicator -eq "==") 
            Write-Host "No differences found. Both folders contain the same files."
        }  
powershell
  • 2 respostas
  • 33 Views
Martin Hope
RustyAndroid
Asked: 2025-04-16 08:32:23 +0800 CST

PowerShell - Mensagem de erro ao procurar sistemas

  • 5

Escrevi um script para reiniciar computadores em uma rede. Ele está funcionando perfeitamente, mas o único problema que estou enfrentando são mensagens de erro aparecendo no host. O script extrai uma lista de nomes de sistemas de um arquivo txt ( $Computers). Testei o script com um sistema que consegui acessar e a palavra "wrench" na lista para simular um sistema que não está na rede. Ao testar o script, ele gerou uma mensagem de erro ao procurar por "wrench". Aqui está o que tenho até o momento para a parte de reinicialização do meu script:

#Actual restart portion (for privacy reasons, real file path replaced with "file-path")
#Starts by moving most recent log to archive folder
Get-ChildItem -Path "\\file-path\Computer Restarts\Logs" -Recurse -File | Move-Item -Destination "\\file-path\Computer Restarts\Logs\Archive" -Force

     #Determine script location, create new script, get current time and date
     $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
     $Log = New-Item "\\file-path\Computer Restarts\Logs\$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Restarts.txt" -ItemType File -Force
     $Date = Get-Date -Format "dd-MMM-yyyy hh:mm:ss"
     $Now = [datetime]::Now

     Clear-Host
     Write-Host `n `n `n
     Write-Host "Rebooting all computers and verifying reboot status..." `n `n
     Write-Host "Please standby, process may take up to 30 minutes..." `n `n

     Restart-Computer -ComputerName $Computers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800 # Restarts all listed systems at once

     "----------------------------------Script executed on $Date----------------------------------" + "`r`n" | Out-File $Log -Append #First thing added to new log

     foreach($Computer in $Computers) #Checks each server to see if it has rebooted. Waits for confirmation before moving to next computer, skips computer if unresponsive after short time.
     {
         $LastBoot = (Get-CimInstance Win32_OperatingSystem -ComputerName $Computer -EA 0).LastBootUpTime
         $PingRequest = Test-Connection -ComputerName $Computer -Count 1 -Quiet

         if(($PingRequest -eq $true) -and ($LastBoot -gt $Now))
         {
             Add-Content -Path $Log -Value "$Computer`: Reboot Successful."
         }
         elseif ($PingRequest -eq $false)
         {
             Add-Content -Path $Log -Value "$Computer`: Computer not detected, please confirm."
         }
         else
         {
             Add-Content -Path $Log -Value "$Computer`: Restart not detected, please restart computer manually. Last detected boot up time is $LastBoot"
         }
     }

"Wrench" não quebra o script, pelo que sei, mas eu preferiria que o script apenas lidasse silenciosamente com os sistemas que ele não consegue encontrar, apenas anexando-o ao log e não exibindo uma mensagem de erro no host também.

powershell
  • 1 respostas
  • 33 Views
Martin Hope
9072997
Asked: 2025-04-14 22:19:21 +0800 CST

Qual é o tempo de vida de um ValidateScript no PowerShell?

  • 8

O PowerShell oferece suporte a scripts de validação para variáveis. Isso é mais comumente usado para validar parâmetros de função, mas pode ser aplicado a qualquer variável. Esses scripts de validação são executados sempre que o valor da variável é alterado.

# create a variable with a validation script
[ValidateScript({
    if (-not ($_.Length -in @(8, 16, 24))) {
        Write-Host 'Validate Failed'
        throw "Value '$_' has invalid length: $($_.Length)"
    } else {
        Write-Host 'Validate Success'
    }
    $true
})][System.String]$MyValidatedArg = "a" * 8 # prints "Validate Success"

# Each one of these will trigger the validation script
Write-Host "Several valid assignments..."
$MyValidatedArg = "b" * 8 # prints "Validate Success"
$MyValidatedArg = "b" * 8 # prints "Validate Success"
$MyValidatedArg = "b" * 16 # prints "Validate Success"
$MyValidatedArg = "b" * 24 # prints "Validate Success"

Se eu atribuísse um valor inválido à variável, isso geraria uma exceção

$MyValidatedArg = "foo" # throws an exception

Estranhamente, consigo ignorar o script de validação se eu especificar novamente a restrição de tipo durante a atribuição. Sei que "simplesmente não faça isso" é uma opção, mas o ponto principal da minha pergunta é: por que isso funciona?

[System.String]$MyValidatedArg = "123456789" # works even though this value is invalid

A princípio, pensei que fosse apenas um sombreamento de variáveis. Tipo, talvez eu estivesse criando uma segunda variável, objeto ou algo assim, especificando a restrição de tipo uma segunda vez. Tentei capturar uma referência à variável para ver se ela manteria o script de validação. Não mantém, mas não estou muito familiarizado com os detalhes internos do PowerShell para saber se este é um teste válido.

# create a reference and assign through the reference
Write-Host "Assigning through reference..."
$refToParameter = [ref] $MyValidatedArg
$refToParameter.Value = "c" * 24 # prints "Validate Success"
Write-Host " Read via variable: $MyValidatedArg"
Write-Host " Read via reference: $($refToParameter.Value)"

# the reference and the variable are linked
# Assignments to either trigger the validation script
Write-Host "Assigning through normal variable again..."
$MyValidatedArg = "d" * 24 # prints "Validate Success"
Write-Host " Read via variable: $MyValidatedArg"
Write-Host " Read via reference: $($refToParameter.Value)"

# This works, which is odd
Write-Host "Assigning with [System.String]..."
[System.String]$MyValidatedArg = "123456789" # invalid, nothing printed
Write-Host " No exceptions yet!"

# I thought this was some sort of variable shadowing thing, but the reference shows the new value too
Write-Host "The link between the variable and the reference is still there..."
$MyValidatedArg = "e" * 8 # valid, nothing printed
Write-Host " Read via variable: $MyValidatedArg"
Write-Host " Read via reference: $($refToParameter.Value)"

# and now we appear to have killed the validation script
Write-Host "Regular invalid assignment..."
$MyValidatedArg = "123456789" # invalid, nothing printed
Write-Host " It works now for some reason"
powershell
  • 1 respostas
  • 53 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve