Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

"untrusted publisher" even though .ps1 script is signed by valid MS certs

$
0
0

Hello,

I just installed a fresh Windows 2012 R2 server and wanted to install the OpenSSH-Win64 server available here: https://github.com/PowerShell/Win32-OpenSSH/releases

Can somebody clarify why this warning shows up even though the .\install-sshd script is signed and timestamped by valid Microsoft-trusted entities? Why doesn't Microsoft Windows trust it??

Thanks,

Chris.


Powershell Script Automation

$
0
0

I have a script that connects to an SFTP location and synchronises a remote and Local location.  This works like a dream when i run it manually 100%.

I need to run this script every 15 mins and as such I have created a Task Scheduler Job. 

When i run the task scheduler job once created it runs but nothing happens.  

I can seem to get this job to run,  the credentials i am using are the same i created the script in and when i run manually it works it is only when i try to run the script using task scheduler it does nothing.  I am running out of ideas. 

Any assistance would be greatly appreciated.   

indexing two arrays in Powershell

$
0
0

Hi All,

I try to index two arrays by matching values;

I have Inventory of computer names with AD last logon date, I want to update lastlogon date column with new arrays lastlogon date column

I tried to use below script, I don't get any error but its not updating Inventory array.

Any Idea...

ForEach($newad in $newads)
{
    ForEach($Inventory in $Inventorys)
      {           
        If($newad.name -eq $Inventory.All_Workstations)
          {
            $Inventory.AD_lastlogondate = $newad.lastlogondate
          }
      }
  }

$Inventory
All_WorkstationsAD_lastlogondate
Computer105/06/2019
Computer206/06/2019
Computer307/06/2019
Computer408/06/2019
Computer509/06/2019
Computer610/06/2019
Computer711/06/2019


$newad
Namelastlogondate
Computer109/07/2019
Computer209/07/2019
Computer309/07/2019
Computer409/07/2019
Computer509/07/2019


How to export AD user and AD groups into Excel in matrix format

$
0
0

Hi 

Could anyone please tell me how to export AD users and AD group into Excel file. Something like  usernames in rows and Groups in the column. I am looking for a excel which shows everything in one page.

Thank you in advance


Shekar-Technet

Need to run with different user

$
0
0

Hello,

I want to run powershell script with different user account. And i need to store/save those account details as i need to run every time with that account.

Can you please suggest.

Thank You,

Avis

Installing webserver on Windows 10 Build 1803 - Powershell Script

$
0
0

Hi,

I am building a developers windows 10 machine who use .NET, Visual C++ and other softwares. They need to have IIS installed on Windows 10 machine. We have a ps script that runs to install these features on Windows Server 2016. I am trying to run this script on the Windows 10 machine. It gives me an error 

Add-WindowsFeature : The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, ...................

So, I went and tried and did a "Import-module servermanager"

and it is not able to to load the servermanager since no valid module file was found in any module directory. How can I go about getting this installed. Here is the script shown below that I am trying to run on a Windows 10 machine.




AA2913

Remove Terminated Users Mobile Devices from O365

$
0
0

Hey all,

So i am new to using power shell and trying to make part of our termination process less manual. Right now I have a powershell script that sets a users out of office from information pulled from a CSV. I am trying to take this one step further by also removing any mobile device associated with their account. The issue I am running into is how to call the identity of the associated devices per user and then pump that data back into the script all at once. I just cant seem to get the syntax or commands rights.

Ideally it would be something like this;

User1@company.com

Device1

Device2

Script to set user1@company.com OOO > get list of mobile devices > returns Device1 and Device2 > Remove Device1 and Device2 > goes on to next user and repeats process.

Azure AZ modules not working while nested in functions

$
0
0

Hello,

I have written some complex PowerShell scripts for reuse.  I am cleaning them up and compartmentalizing into functions for readability, etc.

I am having trouble with AZ functions not working inside of nested functions.  Maybe this is by design and a normal feature of PowerShell but if so it's not one that I understand yet.

The module works fine.

If I call the module from a function it works fine

If I call the function with the module from another function it just doesn't work.  It doesn't do anything.  There's no error to catch, the whole response object is just the fully qualified name of the method.

Get-AzProviderFeature is the module function I'm calling.

It works fine.  It works fine inside of a function. If I call that function from another function then the whole result is

Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSProviderFeature

I'm sure this is a 101 newbie nuance thing and not a problem with Azure modules but I'm still stuck.

I'm wondering if the AzContext or AzLogin isn't still in scope but I'm not receiving any errors that would indicate that.


Foreach loops output in Different files.

$
0
0

Hello Team,

As a project requirement, i need the output of a foreach loop to be saved in a different file. (i.e). If a loop runs 100 times the output of the each instance of loop should be saved in a different file, So that i may get 100 output files.

I do not want to use "append" option, Since this dumps everything into a single file.

Kind Regards

Sreeram.R


Shriram

import-module activedirectory fails

$
0
0

Getting below eror on 2008 DC: Non R2(RSAT is installed,account having domain admin permission)

Import-Module : The specified module 'ActiveDirectory' was not loaded because no valid module file was found in any mod

ule directory.

At line:1 char:14

+ Import-module <<<<  ActiveDirectory

    + CategoryInfo         : ResourceUnavailable: (ActiveDirectory:String) [Import-Module], FileNotFoundException

    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

________________________________

Installed the below commoponent and ADWS service is running fine.

http://www.microsoft.com/en-us/download/details.aspx?id=2852

Find also below output for powershell version.

PS C:\Windows\system32> get-host

Name            : ConsoleHost

Version          : 2.0

InstanceId       : 4e859c96-b465-46ff-9714-815a76084336

UI              : System.Management.Automation.Internal.Host.InternalHostUserInterface

CurrentCulture   : en-GB

CurrentUICulture : en-US

PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy

IsRunspacePushed : False

Runspace         : System.Management.Automation.Runspaces.LocalRunspace


AliahMurfy

Insert a command for pop up message

$
0
0

Hello All,

Seeking help from the community to include a pop up message when techs execute the script on local machine.  The script runs few actions in Control Panel - Configuration Manager.  Now the script does a job but it is not displaying a message when they run the script.  I was able to Google and get the command details but not sure where to insert the command within the script.

The command is

[System.Windows.MessageBox]::Show('Selected cycle will run and might take few minutes to finish')

The script is 

function Start-CMClientAction {
    <#
.SYNOPSIS
    Invokes CM Client actions on local or remote machines

.DESCRIPTION
    This script will allow you to invoke a set of CM Client actions on a machine (with optional credentials), providing a list of the actions and an optional delay betweens actions. 
    The function will attempt for a default of 5 minutes to invoke the action, with a 10 second delay inbetween attempts. This is to account for invoke-wmimethod failures.

.PARAMETER Schedule
Define the schedules to run on the machine - 'HardwareInv', 'FullHardwareInv', 'SoftwareInv', 'UpdateScan', 'UpdateEval', 'MachinePol', 'AppEval', 'DDR'

.PARAMETER Delay
Specify the delay in seconds between each schedule when more than one is ran - 0-30 seconds

.PARAMETER ComputerName
    Specifies the computers to run this against
    
.PARAMETER Timeout
    Specifies the timeout in minutes after which any individual computer will stop attempting the schedules. Default is 5 minutes.

.PARAMETER Credential
Optional PSCredential

.EXAMPLE
# Start a machine policy eval and a hardware inventory cycle
Start-CMClientAction -Schedule MachinePol,HardwareInv

.NOTES
    FileName:    Start-CMClientAction.ps1
    Author:      Cody Mathis
    Contact:     @CodyMathis123
    Created:     11-29-2018
    Updated:     03-09-2019
#>
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [Alias('Computer', 'HostName', 'ServerName', 'IPAddress')]
        [string[]]$ComputerName = $env:COMPUTERNAME,
        [parameter(Mandatory = $true)]
        [ValidateSet('HardwareInv', 'FullHardwareInv', 'SoftwareInv', 'UpdateScan', 'UpdateEval', 'MachinePol', 'AppEval', 'DDR')]
        [string[]]$Schedule,
        [parameter(Mandatory = $false)]
        [ValidateRange(0, 30)]
        [int]$Delay = 5,
        [parameter(Mandatory = $false)]
        [int]$Timeout = 5,
        [parameter(Mandatory = $false)]
        [pscredential]$Credential
    )
    begin {
        $TimeSpan = New-TimeSpan -Minutes $Timeout
    }
    process {
        foreach ($Computer in $ComputerName) {
            foreach ($Option in $Schedule) {
                $Action = switch -Regex ($Option) {
                    '^HardwareInv$|^FullHardwareInv$' {
                        '{00000000-0000-0000-0000-000000000001}'
                    }
                    '^SoftwareInv$' {
                        '{00000000-0000-0000-0000-000000000002}'
                    }
                    '^UpdateScan$' {
                        '{00000000-0000-0000-0000-000000000113}'
                    }
                    '^UpdateEval$' {
                        '{00000000-0000-0000-0000-000000000108}'
                    }
                    '^MachinePol$' {
                        '{00000000-0000-0000-0000-000000000021}'
                    }
                    '^AppEval$' {
                        '{00000000-0000-0000-0000-000000000121}'
                    }
                    '^DDR$' {
                        '{00000000-0000-0000-0000-000000000003}'
                    }
                }

                $StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
                do {
                    try {
                        Remove-Variable MustExit -ErrorAction SilentlyContinue
                        Remove-Variable Invocation -ErrorAction SilentlyContinue
                        if ($Option -eq 'FullHardwareInv') {
                            $getWMIObjectSplat = @{
                                ComputerName = $Computer
                                Namespace    = 'root\ccm\invagt'
                                Class        = 'InventoryActionStatus'
                                Filter       = "InventoryActionID ='$Action'"
                                ErrorAction  = 'Stop'
                            }
                            if ($PSBoundParameters.ContainsKey('Credential')) {
                                $getWMIObjectSplat.Add('Credential', $Credential)
                            }
                            Write-Verbose "Attempting to delete Hardware Inventory history for $Computer as a FullHardwareInv was requested"
                            $HWInv = Get-WMIObject @getWMIObjectSplat
                            if ($null -ne $HWInv) {
                                $HWInv.Delete()
                                Write-Verbose "Hardware Inventory history deleted for $Computer"
                            }
                            else {
                                Write-Verbose "No Hardware Inventory history to delete for $Computer"
                            }
                        }
                        $invokeWmiMethodSplat = @{
                            ComputerName = $Computer
                            Name         = 'TriggerSchedule'
                            Namespace    = 'root\ccm'
                            Class        = 'sms_client'
                            ArgumentList = $Action
                            ErrorAction  = 'Stop'
                        }
                        if ($PSBoundParameters.ContainsKey('Credential')) {
                            $invokeWmiMethodSplat.Add('Credential', $Credential)
                        }
                        Write-Verbose "Triggering a $Option Cycle on $Computer via the 'TriggerSchedule' WMI method"
                        $Invocation = Invoke-WmiMethod @invokeWmiMethodSplat
                    }
                    catch [System.UnauthorizedAccessException] {
                        Write-Error -Message "Access denied to $Computer" -Category AuthenticationError -Exception $_.Exception
                        $MustExit = $true
                    }
                    catch {
                        Write-Warning "Failed to invoke the $Option cycle via WMI. Will retry every 10 seconds until [StopWatch $($StopWatch.Elapsed) -ge $Timeout minutes] Error: $($_.Exception.Message)"
                        Start-Sleep -Seconds 10
                    }
                }
                until ($Invocation -or $StopWatch.Elapsed -ge $TimeSpan -or $MustExit)
                if ($Invocation) {
                    Write-Verbose "Successfully invoked the $Option Cycle on $Computer via the 'TriggerSchedule' WMI method"
                    Start-Sleep -Seconds $Delay
                }
                elseif ($StopWatch.Elapsed -ge $TimeSpan) {
                    Write-Error "Failed to invoke $Option cycle via WMI after $Timeout minutes of retrrying."
                }
                $StopWatch.Reset()    
            }
        }
    }
    end {
        Write-Verbose "Following actions invoked - $Schedule"
    }
}

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

$
0
0

Hi All, i am getting the below errors when i am running my script. Can you please help me its urgent. 

Code- 
$diskD = Get-WmiObject Win32_LogicalDisk -ComputerName $destinationIP -Filter "DeviceID='D:'"
$disk =  Get-WmiObject Win32_LogicalDisk -ComputerName $localhost -Filter "DeviceID='C:'"

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:16 char:10
+ $diskD = Get-WmiObject Win32_LogicalDisk -ComputerName $destinationIP ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

New-Item : The network path was not found
At line:51 char:5
+     New-Item -ItemType Directory -Force -Path $TestFolderPath
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\​192.168.166.106\\d$\BackUp_Logs:String) [New-Item], IOException
    + FullyQualifiedErrorId : CreateIntermediateDirectoriesIOError,Microsoft.PowerShell.Commands.NewItemCommand

 
New-Item : The UNC path should be of the form \\server\share.
At line:51 char:5
+     New-Item -ItemType Directory -Force -Path $TestFolderPath
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (\\​192.168.166.106\\d$:String) [New-Item], ArgumentException
    + FullyQualifiedErrorId : CreateDirectoryArgumentError,Microsoft.PowerShell.Commands.NewItemCommand

If statement not working, as expected

$
0
0

Sorry, know just enough to make me dangerous.  Trying to script starting and stopping services on Production and TEST servers, but my IF statement is not working and can't figure out what I'm doing wrong.  When I run it, it lists all four servers.

Thanks for your help.  If there's a better way, I'm open to suggestions.

$hashTable=@{"SERVER01"="Service1,service2""SERVERL1"="service2""SERVERT1"="service3""SERVERT2"="service3"
  }

Write-Host 'Select the environment and action:

  1. Start Production Services
  2. Stop Production Services
  3. Start TEST Services
  4. Stop TEST Services
  q. Quit'


While (($Selection = Read-Host -Prompt 'Please select an option') -notin 1,2,3,4,'q') 
{ 
    Write-Warning "$Selection is not a valid option" 
}

Switch ($Selection) {
    1 { $action = "Start-Service" }
    2 { $action = "Stop-Service -Force" }
    3 { $action = "Start-Service" }
    4 { $action = "Stop-Service -Force" }

}

foreach($key in $hashTable.keys)
  {
    $Value = $hashTable[$key]
    $testServer = $Key.Substring($Key.Length - 2,1)
    
    If ($Selection -eq 3 -or 4 -and $testServer -eq "T")
    {
    Write-Host "TEST "
    Write-Host "Get-Service -ComputerName " $key " -Name " $Value " | " $action
    } Else
    {
    Write-Host "Production"
    Write-Host "Get-Service -ComputerName " $key " -Name " $Value " | " $action
    }

  }

How to get the list of Azure AD groups that user belongs to

$
0
0

Hi All,

I want to get list of Azure AD groups that user belongs to. how to get this with powershell scripting.

Thank you.

Join Nondomain server to domain issues

$
0
0

I have a vm that has a host name and IP, pingable by ip but not dns. I run this command to try and join it from my work station as domain admin:

Add-Computer -DomainName server02 -DomainCredential domain\username

I get this error output:

add-computer : Computer name server02  cannot be resolved with the exception: One or more errors occurred

How can I join a new vm that has a hostname and IP to our domain that is in a workgroup please?


Get-RecipientPermission doesn't show all "send-as" permissions

$
0
0

I wan't to get all the "send-as" permissions for all mailboxes. But when using the Get-RecipientPermission Command i only get some. When checking on the exchange online webinterface the send as  permissions are set correctly. 

Example:

For mailbox "xy" I enter: 

Get-RecipientPermission -ResultSize Unlimited -Identity "xy"

I Expected: 2 Accounts + NT AUTHORITY\SELF

I Got: only the default NT AUTHORITY\SELF

I don't see how i could use the command wrongly but maybe I still am. Is there a possibility to get more insight into whats happening? Is this an Exchange online problem or a powershell problem?

Thanks very much in advance

iperf like network test using Powershell or other 'native' windows functions

$
0
0

Hi,

I would really like to test a network connection between 2 servers in a 'raw TCP throughput style' i.e. no other bottlenecks like file I/O being part of the measurement.

The internets recommend IPERF strongly and this looks ideal, unfortunately the environment I need to test is very strict on ANY 'foreign' software being installed, even sysadmin style tools.

I imagined Powershell or by extension .NET would be ideal for this, setting up a 'listener' on one machine, then a 'client' on another and trying to max out the link.

Is this possible in a simple fashion, or am I completely mad thinking this can be done with local tools only?

Thanks!

issue to display function result with custom object

$
0
0

Hi,

I'm newbie to do script and I don't know where is my issue.

Piece of my script :

#Roles FSMO
function FSMO {
    AfficheTitre ("ROLES FSMO")
    $result=@()
    #maitre de domaine
    $domainMaster=$forest.domainnamingmaster
    #maitre de schema
    $schemaMaster=$forest.schemamaster

    #Récupération des rôles FSMO de chaque domaines
    $alldomains | foreach { 
        $domaine=$_
        #maitre d'infrastructure
        $infraMaster=(Get-ADDomain -Identity $domaine).infrastructuremaster
        #maitre RID
        $RIDMaster=(Get-ADDomain -Identity $domaine).RIDMaster
        #emulateur PDC
        $PDC=(Get-ADDomain -Identity $domaine).PDCEmulator
        $obj=[PSCustomObject]@{
            Domaine=$domaine
            MaitreDeDomaine=$domainMaster
            MaitreDeSchema=$schemaMaster           
            maitreInfrastructure=$infraMaster
            maitreRID=$RIDMaster
            emulateurPDC=$PDC          
        }    
        $result+=$obj
    }
    return $result
}

#Permet d'afficher un titre encadré
function AfficheTitre ($titre)
{
    $nbchar=$titre.length
    $charhaut="#"
    $charbas="#"
    $nbsymbole=100
    $debutEcriture=[math]::truncate(($nbsymbole-$nbchar)/2)-1
    $return+=write-host ""
    $return+=write-host $($charhaut*$nbsymbole)
    $return+=write-host $($charhaut*$nbsymbole)
    $return+=write-host $(" " * $debutEcriture) $titre $(" " * $debutEcriture)
    $return+=write-host $($charbas*$nbsymbole)
    $return+=write-host $($charbas*$nbsymbole)
    $return+=write-host ""
    return($return)

}

#Récupération des niveaux fonctionnels
function NiveauFonctionnel
{
    AfficheTitre("NIVEAU FONCTIONNEL")
    $result=@()
    #niveau fonctionnel forêt
    $ffl=$forest.forestmode
    #niveau fonctionnel domaine
    $alldomains | foreach {
        #nom du domaine
        $domaine=$_
        #niveau fonctionnel du domaine
        $dfl=(Get-ADDomain -Identity $domaine).domainmode
        $obj=[PSCustomObject]@{
            Domaine=$domaine
            NiveauFonctionnelForet=$ffl
            NiveauFonctionnelDomaine=$dfl          
        }    
        $result+=$obj
    }
    return $result
}

function main 
{
    $forest=get-adforest
    $domain=get-addomain
    $alldomains=$forest.domains
    $allDCs = $forest.Domains | foreach { Get-ADDomainController -Filter * -Server $_ } 
    NiveauFonctionnel
    FSMO



}

main

My issue is FSMO doesn't display what I want.

If I comment on main function "NiveauFonctionnel" FSMO displays result I want.

I have this issue with all my powershell function where I created custom object.

Can you explain me what I do wront pls.


Merci de marquer comme reponses les interventions qui vous ont ete utile.


PoshRSJob not passing $computer

$
0
0

I have a script to check services from a list of computers:

$winrmlist =  import-csv .\computers.csv | select-object -expandproperty computer

 Foreach ($computer in $winrmlist) {
          $winrmsvc=get-service -Computername $computer -name winrm
          $rpcsvc=get-service -computername $computer -name rpcss
          $remotereg=get-service -Computername $computer -name RemoteRegistry

               if ($Winrmsvc.status -eq "stopped") {
                  write-host $computer $winrmsvc $winrmsvc.status -foregroundcolor red} else {
                   write-host $computer $winrmsvc $winrmsvc.status -foregroundcolor green}

               if ($rpcsvc.status -eq "Stopped") {
                   write-host $computer $rpcsvc $rpcsvc.status -foregroundcolor red} else {
                   write-host $computer $rpcsvc $rpcsvc.status -foregroundcolor green}                  

               if ($remotereg.status -eq "Stopped") {
                   write-host $computer $remotereg $remotereg.status -foregroundcolor red} else {
                   write-host $computer $remotereg $remotereg.status -foregroundcolor green} 

 }

works fine for what I need but, could use some error catching.

Anyhow, I downloaded PoshRSJob and, am just trying to understand how I could get it to work with this script.

I tried a number of iterations of 

$winrmlist =  import-csv .\computers.csv | select-object -expandproperty computer

$winrmlist | forEach-object {Start-rsjob -name {$_.computer} -Scriptblock {
Param($object)
$winrmsvc=get-service -Computername $object -name winrm
          $rpcsvc=get-service -computername $object -name rpcss
          $remotereg=get-service -Computername $object -name RemoteRegistry

I also tried:

$winrmlist | forEach-object {Start-rsjob -name {$_.computer} -Scriptblock {
Param($object)
$winrmsvc=get-service -Computername $_ -name winrm
          $rpcsvc=get-service -computername $_ -name rpcss
          $remotereg=get-service -Computername $_-name RemoteRegistry

I cant seem to get it to pass the $computer

Can someone point me in the right direction?

Thank you!

Steve


--------- SteveP

REG UNLOAD Access Denied in CMD

$
0
0

Greetings,

I'm trying to write a simple batch file to load a hive from another hard drive, create a key, create a subkey, and then unload the hive. It all works well until I try to unload the hive. It says access denied. Here is what I have

REG LOAD HKLM\MINWIN E:\Windows\System32\config\system
REG ADD HKLM\MINWIN\xxxxxxxx\xxxxxxx\xxxxxx /f
REG ADD HKLM\MINWIN\xxxxxxxx\xxxxxxx\xxxxxx /f /v xxxxxxxxxxxxxxxx /t REG_DWORD /d 0
REG UNLOAD HKLM\MINWIN

Also, I am running these commands in cmd (ran as administrator) using windows 7.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>