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

Powershell script not running when using TaskScheduler

$
0
0

Hello,

I cannot get a simple powerhsell script to execute using the task scheduler.

I have the following parameters:

powershell.exe  -ExecutionPolicy ByPass -WindowStyle Hidden -File script.ps1

I would like the script to run for any user that is logged on to the computer. The account that I am using to test execution with has domain admin level privileges. 

The script runs fine if I execute the exact same action command manually.

The script also works if I am logged on with the domain admin account that I defined as the user to execute script.

However, if a domain user is logged on, the task scheduler does not run execute the powershell script.

Any suggestions?

Thanks!


Exchange script issues

$
0
0

Good morning folks.

I am "newish" to Powershell scripting so I am hoping someone can assist me.

Basically, I am using EMS to pull the last 30 days of emails to a specific address from my mail server each month.

Here is what I have so far for dates:

$startDate=Get-Date; 
$endDate=Get-Date; 

$startDateFormatted=$startDate.AddDays(-1).ToShortDateString(); 
$endDateFormatted=$endDate.AddDays(-30).ToShortDateString(); 

From my understanding, This should use today as the start, and 30 days ago as the end.

When I run the command in a normal Powershell, it displays the date 30 days ago so I am assuming it is correct.

When I run it in EMS, it ends up only pulling like 14 days of information. I then changed the number to endDateFormatted=$endDate.AddDays(-60)and it pulled the same 14 days of information. 

Is there something I am missing? Let me know if you need me to include the other half of the script of what information I am pulling.

ANY help is MUCH appreciated. 

PoshRSJob module: Stagger script block execution across RSJobs

$
0
0

I have a situation where I use PS to execute an in-house developed executable X number of times once a day for general maintenance. Doing the work in parallel gets it done faster and PoshRSJob is an excellent module to use for this purpose. However, the executable cannot be started simultaneously and needs about 3 seconds of delay between the start of each execution.

For example:

  • the executable is "foo.exe"
  • it accepts a single string parameter argument called "bar" appended with an incremented integer
  • it is executed using the call operator "&"
  • it is pipelined to Out-Null so that PS waits for it to complete and PoshRSJob's throttling capabilities are used

The limitation:

  • "foo.exe" is coded so that it must briefly have exclusive access to a single, specific external file when it starts
  • "foo.exe" completes exclusive access to the external file in 3 seconds or less and continues on

The issue caused by the limitation:

  • "foo.exe" executed in parallel collides with another thread of "foo.exe" that already has access to the external file
  • "foo.exe" does not handle said error gracefully and just dies
  • "foo.exe" cannot be updated to handle this gracefully in a timely fashion at this time

One way I can think of to overcome this is to use a mutex within in the script block in a round-about way:

  • create a mutex
  • request ownership of the mutex
  • sleep for 3 seconds within the context of the mutex
  • release the mutex
  • execute "foo.exe"

This appears to work, but this seems less than ideal. Is there a better way to accomplish staggering the execution of "foo.exe" across the RSJobs given the limitations listed (not simultaneously, 3 seconds between each execution)?

Import-Module -Name PoshRSJob;

$sb = {

    $cmd = "foo.exe";
    $param = "bar_$($_)";

    $mtx = [System.Threading.Mutex]::new($false, "foo_mutex");

    [void]$mtx.WaitOne();


    Try {
        Start-Sleep -Seconds 3;
    } Catch {
        Write-Warning $_;
    }


    [void]$mtx.ReleaseMutex();

    & $cmd $param | Out-Null;
}

(1..100) | Start-RSJob -Name {"Job_$($_)"} -ScriptBlock $sb -Throttle 5 -Verbose | Wait-RSJob -ShowProgress | Receive-RSJob;

Get-RSJob | Stop-RSJob;
Get-RSJob | Remove-RSJob;

BitsTransfer with credentials

$
0
0

So I am trying to learn powershell, and I learned about BitsTransfer which works great without credentials, but can't seem to get it to work with credentials. Any help is appreciated.

Here is my code:

Import-Module BitsTransfer

$FileArray = @("File1.zip", File2.zip) #Future use
$username = "MyUserName"
$password = "MyPassword"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol.toString() + ', ' + [Net.SecurityProtocolType]::Tls12

$url = "https://mywebsite.com/Usr/" + $file1.zip
$output = "$PSScriptRoot\20meg.test"

Start-BitsTransfer -Credential '$username','$password' -Source $url -Destination $output
    
$start_time = Get-Date
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

Azure Powershell Task V4 - Wrong Location

$
0
0
After a fair bit of troubleshooting my Release I've discovered that Azure Powershell V4 doesn't run from the right location. It looks as the the agent is running from:
`D:\a\_tasks\AzurePowerShell_72a1931b-effb-4d2e-8fd8-f8472a07cb62\4.0.13`

After executing:
`D:\a\_tasks\AzurePowerShell_72a1931b-effb-4d2e-8fd8-f8472a07cb62\4.0.13\azurepowershell.ps1`

I had to put `Set-Location $(System.DefaultWorkingDirectory)` at the start of my scripts for them to run. Apart from this V4 module reporting conflicts and errors with the agent (see examples below), my scripts ran successfully after setting the correct location.

> 2019-07-10T04:00:36.4724639Z VERBOSE: Importing function 'CmdletHasMember'.
2019-07-10T04:00:36.4737609Z VERBOSE: Importing function 'Disconnect-AzureAndClearContext'.
2019-07-10T04:00:36.4746329Z VERBOSE: Importing function 'Initialize-AzModule'.
2019-07-10T04:00:36.4754653Z VERBOSE: Importing function 'Initialize-Azure'.
2019-07-10T04:00:36.4763674Z VERBOSE: Importing function 'Initialize-AzureRMModule'.
2019-07-10T04:00:36.4772155Z VERBOSE: Importing function 'Remove-EndpointSecrets'.
2019-07-10T04:00:36.4856685Z VERBOSE: Trying to disconnect from Azure and clear context at process scope
2019-07-10T04:00:36.4903317Z VERBOSE: Cannot verify the Microsoft .NET Framework version 4.7.2 because it is not included in the list of permitted 
2019-07-10T04:00:36.4904316Z versions.
2019-07-10T04:00:36.4927149Z VERBOSE: Populating RepositorySourceLocation property for module Az.Accounts.
2019-07-10T04:00:36.4942954Z VERBOSE: Loading module from path 'C:\Modules\az_1.6.0\Az.Accounts\1.5.0\Az.Accounts.psm1'.

> 2019-07-10T04:00:25.9013574Z ##[warning]Both Az and AzureRM modules were detected on this machine. Az and AzureRM modules cannot be imported in the same session or used in the same script or runbook. If you are running PowerShell in an environment you control you can use the 'Uninstall-AzureRm' cmdlet to remove all AzureRm modules from your machine. If you are running in Azure Automation, take care that none of your runbooks import both Az and AzureRM modules. 

Active Directory Account Expiration Notification to Managers

$
0
0

Active Directory Account Expiration Notification to Managers

Hello script gurus - I wanted to send an automatic email notification to managers pertaining to their contractors that has an end date on their AD accounts. The script that I found had most of the features I'm looking for. However need assistance on how to add the following into the script.

- Add additional message into the body of the email.
- Exclude the "past" expired accounts from the report.

When the report runs it sends the email to managers just fine however, we've noticed that it is including the ones that are already expired. We want to only send the ones that are expiring within 30 days from this date forward.  


Here's the script I found referenced in this forum:
https://social.technet.microsoft.com/Forums/windows/en-US/9d080c24-b2a2-4d9b-b50b-ca7fb9d95a91/account-expiration-email-notification?forum=winserverpowershell&prof=required 

Thank you for your time and appreciate any assistance!

Cheers.

Get-ADUser -Filter * -Properties directReports,EmailAddress | ForEach {

    $body = @()

    If ($_.directReports) {

        $managerEmailAddress = $_.EmailAddress

        $_.directReports | ForEach {

            $userDetails = Get-ADUser $_ -Properties AccountExpirationDate

            If ( $userDetails.AccountExpirationDate ) {

                If ( $userDetails.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {

                    $sendEmail = $true

                    $props = [ordered]@{
                        Username=$userDetails.SamAccountName
                        'Account Expiration Date'=$userDetails.AccountExpirationDate
                    }

                    $body += New-Object PsObject -Property $props

                }
            }

        }

    }

    If ($sendEmail) {

        $body = $body | Out-String

        Send-MailMessage -From 'email@domain.com' -To $managerEmailAddress -Subject 'Account Expiration Report' -Body $body -SmtpServer 'mail.domain.com'

    }

    $sendEmail = $false

}

# Generic check for users with no manager
$bodyNM = @()
Get-ADUser -Filter * -Properties AccountExpirationDate,Manager | ForEach {

    If ( !$_.Manager ) {

        If ( $_.AccountExpirationDate) {

            If ($_.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {

                $sendEmailNM = $true

                $propsNM = [ordered]@{
                    Username=$_.SamAccountName
                    'Account Expiration Date'=$_.AccountExpirationDate
                }

                $bodyNM += New-Object PsObject -Property $propsNM       

            }

        }

    }

}

If ($sendEmailNM) {

    $bodyNM = $bodyNM | Out-String
    Send-MailMessage -From 'email@domain.com' -To 'helpdesk@domain.com' -Subject 'Account Expiration Report' -Body $bodyNM -SmtpServer 'mail.domain.com'

}

                            

Cheers, DB

Power Shell to nest multiple GG and DLG groups

$
0
0

Dear Experts

I am trying to find if there is a quick way to nest multiple AD groups( Global Group:GG) within their corresponding Domain Local Groups( DLG)

I would like to feed the data using CSV with columns GG & DLG group names. so GG1 should be nested within DLG1 and so on.

Please advise.

Thanks

Shyam

Powershell stopped working

$
0
0
a script pops up and keeps saying powershell stopped working and have to close the app I am on. Please what can I do to fix this?

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.


PowerShell script to Auto Logoff Admin Users if login > 2 days and session is inactive

$
0
0

Hi All

 I was wondering if anyone could help me with this script. What i am trying to do its log off all inactive user login  more-than 2 days. If anyone has any insight it would be greatly appreciated.

 Thanks

Aditya Dugyala

.csv defaulting to unicode text when saving.

$
0
0
I get a csv file where I need to strip out the header. I have scripted the stripping out of the header successfully, but when it is done it moves all the data to column A because it is defaulting to unicode text when it saves. I am not having any success opening the csv, stripping out the header, and then saving it as a CSV in my scripting. Any ideas?

get-date command in powershell

$
0
0

I am trying to create a powershell script that would send email notification advising groups of people servers will be rebooted.

I have the script working with the (Get-date).AddDays(1)  command but it also adds the local time. I just want it to add the it to show the date + 1 day date with  no time. How do you make this  work?

A specified logon session does not exist. It may already have been terminated

$
0
0

Hello, everyone! I recently meet a strange problem about double hop.

I try to run the following PowerShell command

$credential = Get-Credential

$computerName = "frxp02361Dmbssh"

$psdrive1 = @{
    Name = "PSDrive1"
    PSProvider = "FileSystem"
    Root = "\\mbssh01\Tool"
    Credential = $credential
}

$psdrive2 = @{
    Name = "PSDrive2"
    PSProvider = "FileSystem"
    Root = "\\dyn\AX"
    Credential = $credential
}

$psdrive3 = @{
    Name = "PSDrive3"
    PSProvider = "FileSystem"
    Root = "\\scmlabe3\SCM"
    Credential = $credential
}

$psdrive4 = @{
    Name = "PSDrive4"
    PSProvider = "FileSystem"
    Root = "\\codeflow\public"
    Credential = $credential
}

Invoke-Command -ComputerName $computerName -ScriptBlock {
     New-PSDrive @using:psdrive1
     New-PSDrive @using:psdrive2
     New-PSDrive @using:psdrive3
     New-PSDrive @using:psdrive4
}

Finally, I successfully create new PSDrives of "\\mbssh01\Tool", "\\scmlabe3\SCM", "\\codeflow\public"EXCEPT FOR "\\dyn\AX"

I received the following error:

Name           Used (GB)     Free (GB) Provider      Root                                CurrentLocatio PSComputerNam
                                                                                                      n e
----           ---------     --------- --------      ----                                -------------- -------------
PSDrive1                                             \\mbssh01\Tool                                     frxp02361D...
A specified logon session does not exist. It may already have been terminated+ CategoryInfo          : InvalidOperation: (PSDrive2:PSDriveInfo) [New-PSDrive], Win32Exception+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand+ PSComputerName        : frxp02361Dmbssh

PSDrive3                                             \\scmlabe3\SCM                                     frxp02361D...
PSDrive4                                             \\codeflow\public                                  frxp02361D...

We can see the command "New-PSDrive @using:psdrive2" failed.

But the other three commands all succeed.

I have tested that I can access the folder "\\dyn\AX" in File Explorer when I login into the remote computer.

Can anyone help me? I will be very grateful!




How to search a pid with service name and then task kill it

$
0
0

the situation is that my zeromq server can stop properly in development machine in debug directory

since we use pub and sub and it can not send termination request to itself,

we have to wait for heart beat period to end the thread itself

i still afraid that heart beat is not fast enough to stop the thread

as the error of stop is timeout

if can not stop normally, i may use this final method

in cmd

i do as 

sc queryex service_name

taskkill /f /pid 11111

how to do these in powershell script

if the algorithm is

check whether stop a service has error

and then check whether the service still exist in task manager

then search service name for pid

and then taskkill it with the pid returned

my stop in service

---v-----!





Moving user accounts into an OU the contains the same first name, last name and display name. Duplication error

$
0
0

Hey guys,

I'm working on a project for automating our termination process. HR has mandated that user accounts do not get deleted, instead, they'll get their groups stripped, managers removed and the account gets moved into a termination OU. The problem is that our organization is large enough that we have multiple users across the enterprise with the same first and last name but have different SamAccountNames and different location information. How do we go about finding if a user exists in an OU that has the same first and last name as a user we're trying to move? If one exists, rename it so we don't get the below error.

Here'e the error:

Move-ADObject : An attempt was made to add an object to the directory with a name that is already in use+ ... ial $creds | Move-ADObject -TargetPath $fullTermOU -Credential $creds+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (CN=<lname>\, <fname>.......,DC=org:ADUser) [Move-ADObject], ADException+ FullyQualifiedErrorId : An attempt was made to add an object to the directory with a name that is already in use,Microsoft.ActiveDirectory.Management.Commands.MoveADObject

Here's the line of code:

Get-ADUser $SamAccountName -Credential $creds | Move-ADObject -TargetPath $fullTermOU -Credential $creds


Script no longer works - You cannot call a method on a null-valued expression.

$
0
0

I ran this script a few months ago, and now I get an "You cannot call a method on a null-valued expression." error in my stderr.csv file, and nothing in my stdout.csv file. I would appreciate guidance on this. The service I am after has been replaced with the generic "ServiceName" Thanks.

$strMachineName = import-csv -LiteralPath C:\Intel\AllServers_Date.csv
foreach ($line in $strMachineName)
{
    try {
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $line.computer)
        $regkey = $reg.OpenSubkey("System\\CurrentControlSet\\Services\\ServiceName")
        $serialkey = $regkey.GetValue("ImagePath")

        ('"{0}","{1}"' -f $line.computer, $serialkey) | out-file C:\stdout.csv -append -encoding ascii
    } catch {
        ('"{0}","{1}"' -f $line.computer, $_) | out-file C:\stderr.csv -append -encoding ascii
    }
}


Way to find out creation time for an Azure VM?

$
0
0

Using the new Az.Resources, I would like to be able to query a specific VM to find out exactly how long the VM took to be created. I've tried using Get-AzLog on a specific VM by using its ResourceID, and while I get back a ton of data, I'm not seeing anything useful. Looking at get-member, I see a lot of properties that look promising, but after trying many different things I still can't figure it out. 

Below is the command I'm using. Perhaps there's another way entirely to get this info. I can use the portal to find it, but I'd like to be able to find it using PowerShell. Thanks for your help!

Get-AzLog -ResourceId "/subscriptions/xxxxxx-xxxxxx-xxxxxx-xxxxxx/resourceGroups/UserTesting/providers/Microsoft.Compute/virtualMachines/TestMachine"


Write Output of a function in powershell window

$
0
0

I have a GUI and it calls a function depending on the button pressed. I would like for the output of the function to show in the powershell command window when I run the GUI. The code below contains 5 buttons, when I run the powershell script and click on any of the 5 buttons, nothing happens and it just hangs, until i close out of it.

# This is code for the GUI ▼
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '406,414'
$Form.text                       = "Post DC Patching Checker"
$Form.TopMost                    = $false

$Check_NetLogon                  = New-Object system.Windows.Forms.Button
$Check_NetLogon.text             = "Check Netlogon"
$Check_NetLogon.width            = 340
$Check_NetLogon.height           = 50
$Check_NetLogon.location         = New-Object System.Drawing.Point(15,17)
$Check_NetLogon.Font             = 'Microsoft Sans Serif,10'

$Ping                            = New-Object system.Windows.Forms.Button
$Ping.text                       = "Ping Servers / Workstations"
$Ping.width                      = 340
$Ping.height                     = 50
$Ping.location                   = New-Object System.Drawing.Point(16,97)
$Ping.Font                       = 'Microsoft Sans Serif,10'

$ShowReplication                 = New-Object system.Windows.Forms.Button
$ShowReplication.text            = "Show Replication"
$ShowReplication.width           = 340
$ShowReplication.height          = 50
$ShowReplication.location        = New-Object System.Drawing.Point(16,183)
$ShowReplication.Font            = 'Microsoft Sans Serif,10'

$DiskSpace                       = New-Object system.Windows.Forms.Button
$DiskSpace.text                  = "Disk Space"
$DiskSpace.width                 = 340
$DiskSpace.height                = 50
$DiskSpace.location              = New-Object System.Drawing.Point(15,267)
$DiskSpace.Font                  = 'Microsoft Sans Serif,10'

$CheckDNSsuffix                  = New-Object system.Windows.Forms.Button
$CheckDNSsuffix.text             = "Check IP Configuration"
$CheckDNSsuffix.width            = 340
$CheckDNSsuffix.height           = 50
$CheckDNSsuffix.location         = New-Object System.Drawing.Point(17,350)
$CheckDNSsuffix.Font             = 'Microsoft Sans Serif,10'

$Form.controls.AddRange(@($Check_NetLogon,$Ping,$ShowReplication,$DiskSpace,$CheckDNSsuffix))

$Check_NetLogon.Add_Click({ CheckNetLogon })
$Ping.Add_Click({ PingServersAndWorkstations })
$ShowReplication.Add_Click({ ShowReplicationOnServers })
$DiskSpace.Add_Click({ ShowDiskSpace })
$CheckDNSsuffix.Add_Click({ ShowIPconfig })
# This is code for the GUI ▲


# Check the netlogon service ▼
function CheckNetLogon { 
    $netLogon =Get-Service -DisplayName netlogon 
        if ($netLogon.Status -eq "Running"){
        $netLogon.DisplayName + 'Service is running already'}
    }
# Check the netlogon service ▲


# Ping's several workstations and servers ▼
function PingServersAndWorkstations {
        ping Test1
        ping Test2

    }
# Ping's several workstations and servers ▲


# Shows replication ▼
function ShowReplicationOnServers {
        repadmin /showrepl
    } 
# Shows replication ▲


# Shows disk space ▼
function ShowDiskSpace {
        Get-WmiObject -Class Win32_logicaldisk  | 
        Select-Object -Property DeviceID, DriveType, VolumeName, 
        @{L='FreeSpaceGB';E={"{0:N2}" -f ($_.FreeSpace /1GB)}}
    }
# Shows replication ▲



# Shows IP config ▼
function ShowIPconfig {
        ipconfig
   }
# Shows IP config ▲

Write-Output $ping

[void]$Form.ShowDialog()

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?

Change Time execute program then change time back

$
0
0

I have an application that I need to change system time and date.

Then execute the program, once executed successfully I need to change the system time and date back to another state.

Can I do this in powershell, if so how.

Thanks

Viewing all 21975 articles
Browse latest View live


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