Como verificar se um caminho existe usando o PowerShell

No âmbito da administração de sistemas e do gerenciamento de TI, a automatização das verificações de rotina é fundamental. Uma dessas verificações de rotina é a verificação da existência de um caminho ou de uma pasta específica, uma ação executada com frequência para garantir que um determinado software ou arquivos críticos estejam no lugar. O PowerShell surgiu como uma poderosa linguagem de script que facilita essas tarefas, permitindo que os profissionais de TI otimizem as operações com precisão.

Histórico

O script em foco tem como objetivo simplificar o processo de verificação do caminho, não apenas verificando se existe um caminho especificado, mas também atualizando um campo personalizado com base nesse resultado. Essa dupla funcionalidade é inestimável para profissionais de TI e provedores de serviços gerenciados (MSPs) que dependem de dados em tempo real para monitorar instalações, atualizações ou a integridade do software em vários sistemas. Ao integrar um mecanismo de feedback personalizado, o script permite que os usuários o adaptem de acordo com suas ferramentas e painéis de monitoramento específicos.

O roteiro

<#
.SYNOPSIS
    Updates a custom field with Yes or No, depending if the path exists or not.
.DESCRIPTION
    Updates a custom field with Yes or No, depending if the path exists or not.
.EXAMPLE
     -Path "$env:APPDATAZoombin" -CustomField "Zoom"
    Check if Zoom is installed for the current user. Set custom field "Zoom" to "Yes" if the folder exists or "No" if it doesn't.
.EXAMPLE
    PS C:> Set-IfPathExists.ps1 -Path "$env:APPDATAZoombin" -CustomField "Zoom"
    Check if Zoom is installed for the current user. Set custom field "Zoom" to "Yes" if the folder exists or "No" if it doesn't.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2008
    Release Notes:
    Initial Release
 By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>
[CmdletBinding()]
param (
    # Path to file or folder
    [Parameter(Mandatory = $true)][String]$Path,
    # THe custom field that we will be updating
    [Parameter(Mandatory = $true)][String]$CustomField,
    # Text that will be saved to the custom field when file/folder exists
    [Parameter(Mandatory = $false)][String]$Exists = "Yes",
    # Text that will be saved to the custom field when file/folder does not exist
    [Parameter(Mandatory = $false)][String]$NotExist = "No"
)

begin {}
process {
    $CustomFieldValue = $(
        if ($(Test-Path -Path $Path -ErrorAction SilentlyContinue)) {
            $Exists
        }
        else {
            $NotExist
        }
    )
    Ninja-Property-Set -Name $CustomField -Value $CustomFieldValue
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

Vamos detalhar os componentes do script:

Parâmetros:

  • $Path: Especifica o local do arquivo ou da pasta.
  • $CustomField: Refere-se ao campo personalizado a ser atualizado com base no resultado.
  • $Existe: Um campo de texto que indica a presença de um caminho.
  • $NotExist: Um campo de texto que indica a ausência de um caminho.

Bloco de processo:

  • O cmdlet Test-Path verifica se o $Path especificado existe.
  • Com base no resultado, a variável $CustomFieldValue recebe o valor $Exists ou $NotExist.
  • Ninja-Property-Set atualiza o $CustomField com o $CustomFieldValue.

Casos de uso em potencial

Considere um gerente de TI que supervisiona as implementações de software em uma organização. Eles querem confirmar que o Zoom está instalado na estação de trabalho de cada funcionário. Em vez de navegar manualmente em cada estação de trabalho, eles implementam esse script em toda a rede. Ele verifica a existência do caminho de instalação do Zoom e atualiza um painel centralizado, permitindo que o gerente veja, em um relance, quais máquinas têm o Zoom instalado.

Comparações

Embora existam métodos manuais para verificar a existência de caminhos, como navegar pelas pastas ou usar a opção de propriedades baseada na GUI, o Test-Path do PowerShell é eficiente e dimensionável. Além disso, a integração do teste de caminho com um mecanismo de feedback personalizado, como visto neste script, oferece uma camada adicional de personalização que normalmente não é encontrada em soluções prontas para uso.

Implicações

Embora o script ajude na automação, há uma implicação relacionada à segurança de TI. Se entidades mal-intencionadas acessarem o painel, elas poderão discernir as vulnerabilidades do software com base nas instalações. É fundamental garantir que os resultados desse script sejam mantidos em um ambiente seguro.

Recomendações

  • Sempre teste o script em um ambiente controlado antes da implementação.
  • Atualize regularmente a lista de caminhos a serem verificados, garantindo que ela permaneça relevante.
  • Certifique-se de que os dados gerados pelo script sejam armazenados e transmitidos com segurança.

Considerações finais

O NinjaOne, como uma solução integrada de gerenciamento de TI, pode aproveitar ainda mais os recursos do script. Ao integrar scripts como esses, o NinjaOne pode oferecer percepções mais granulares e em tempo real, permitindo que os profissionais de TI gerenciem e monitorem os sistemas com eficiência. A combinação da versatilidade do PowerShell com a plataforma abrangente da NinjaOne garante operações de TI robustas e otimizadas.

FAQs

O script retornará o valor $NotExist se não encontrar o caminho.

Esse é um espaço reservado para uma função hipotética que atualiza propriedades. Em um aplicativo do mundo real, você o substituiria por uma função real compatível com sua ferramenta de monitoramento.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like

Como habilitar ou desabilitar componentes IPv6 no Windows usando o PowerShell

Como verificar se um caminho existe usando o PowerShell

Como bloquear automaticamente o Windows após a inatividade usando o PowerShell

Como aumentar de forma eficiente o tamanho do arquivo de registro de eventos com o PowerShell

Como usar o PowerShell para enviar notificações de mensagens aos usuários do Windows

Como usar o PowerShell para localizar administradores locais

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).