Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

[PowerShell] Exchange script not running as a Scheduled Task

$
0
0

I have a handful of Exchange scripts that run automatically as scheduled tasks using an Active Directory service account that is a member of the Organization Management group (a default Exchange group).  I am trying to migrate these scheduled tasks (via export/import) and copied my PowerShell scripts to the same drive and folder on another server, but they do not seem to work correctly on the new server.

When I run the scheduled tasks on the new server either manually or if they run themselves on schedule, the powershell.exe processes just takes up around 56 MB of RAM but 0% CPU utilization and sits there in that state.  After a few minutes, the RAM usage slowly starts to drop until it's a little under 2 MB of RAM.  Eventually, the scheduled tasks time out after the two hour maximum task runtime I have configured and the Task Scheduler shows the following error:  "The last run of the task was terminated by the user (0x41306)".

Here is an example of one of my scheduled tasks that I am having trouble with on the new server:

  • Run as:  DOMAIN\ExchangeTask
  • Run whether user is logged in or not
  • Command:  %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
  • Arguments:  -command ". 'D:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; D:\Scripts\Generate-ExchangeMailboxDetailReport.ps1"
  • Start in:  D:\Scripts
  • Start the task only if the computer is on AC power:  Disabled

Both servers are Windows Server 2008 R2 Standard SP1.  Both are running PowerShell 2.0.  I have already configured the service account the scripts run as with the "Log on as a batch job" security right in Local Security Policy on the server and also rebooted the server.  Additionally, the service account is not restricted by which computers it is permitted to log on to in Active Directory.  I have also tried the "Run with highest privileges" option, but this made no difference.  I checked to make sure that both RemoteExchange.ps1 and Generate-ExchangeMailboxDetailReport.ps1 exist at the paths specified on the new server and they do.  I've also made sure to launch PowerShell as admin and run Set-ExecutionPolicy Bypass beforehand.

If I launch a cmd.exe session as the DOMAIN\ExchangeTask account and then run the following command, the script runs and completes successfully in well under the two hour maximum allotted.  Additionally, the powershell.exe process running as DOMAIN\ExchangeTask quickly ramps up to around 170 MB and uses around 99% CPU the entire time it is executing.

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -command ". 'D:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; D:\Scripts\Generate-ExchangeMailboxDetailReport.ps1"

This seems to tell me that there is nothing wrong with my command and argument strings nor my script, but that something else is going wrong when the Task Scheduler tries to run the task.  But I have no idea what that might be.

Any help that could be provided on this issue would be appreciated.






Desperate to run on liner DOS commands in powershell

$
0
0

I am down to 3 diffident on liners that work perfectly from the dos prompt but in Powershell I  get the below error.

ADSchemaAnalyzer.exe : The term 'ADSchemaAnalyzer.exe' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

The command is

ADSchemaAnalyzer.exe  /targetLDIF "C:\Domain2LAB\INFO\PRODSchema.ldif" /baseServer $baseserver /outputLDIF "C:\Domain2LAB\INFO\LAB.LDIF"

This is the full section of script

###################################################
# Schema START
###################################################
$env:COMPUTERNAME

$baseserver = "$env:COMPUTERNAME.$DNSHostName"
If (Test-Path "C:\Domain2LAB\INFO\PRODSchema.ldif") { #1

# Find ADSchemaAnalyzer.exe and set location start
(Get-ChildItem -Path c:\windows -Filter ADSchemaAnalyzer.exe -Recurse).Directory |Export-Csv $env:temp\scrappath.csv -NoTypeInformation
$changepath = (Import-Csv $env:temp\scrappath.csv).FullName[1]
$changepath
Set-Location "$changepath"
# Find ADSchemaAnalyzer.exe and set location end

ADSchemaAnalyzer.exe  /targetLDIF "C:\Domain2LAB\INFO\PRODSchema.ldif" /baseServer $baseserver /outputLDIF "C:\Domain2LAB\INFO\LAB.LDIF""Wait 15 seconds"
Start-Sleep 15

ldifde -i -f "C:\Domain2LAB\INFO\Test.ldif" -c dc=x $DistinguishedName


} # 1


###################################################
# Schema END
###################################################

Please tell me there is a way to run a a one liner like the one above?

Thanks


Lishron

change content in a file list and copy files including folder structure.

$
0
0

Hi all,

I'm looking to read the contents of a text file, change some content, set variables and use that content (a file list) to copy files to a new folder including the folder structure as below: I had to use New-Item to work around not being able to create the folder structure while using Copy-Item.

$Dst - $env:userprofile + '\desktop\copied-files

Get-Content filename.txt|
    Foreach-Object
{
        ($a = '.' + $_ -replace "/", "\"); ($d = $dst + $_ -replace "/", "\")|
        New-Item -ItemType File -Path $d -Force|
        Copy-Item -Include $a -Destination $d -Force
}

This is failing at the copy-item portion. I can run copy-item $a -dest $d manually afterward and it runs perfectly.

the filename.txt is a list of files using linux based '/' which I am converting to '\'

ie: 'filename.txt'
/logs/jan/31/10am.log
/logs/jan/31/1pm.log
/logs/mar/13/3pm.log

copy to '.\desktop\copied-files\logs\lan\31\10am.log', '.\desktop\copied-files\logs\mar\13\3pm.log', etc.

Copy-Item : Cannot copy item C:\Users\Jomal\desktop\deployment\archive-test\weblogfiles\W3SVC2\u_ex140612.log onto itself. At line:1 char:161 + get-content filename.txt|Foreach-Object {($a = '.' + $_ -replace "/", "\"); ($d = $dst + $_ -replace "/", "\")|New-Item -ItemType File -Path $d -Force|copy-it em <<<< -Include $a -Destination $d -Force} + CategoryInfo : WriteError: (C:\Users\Jomal...\u_ex140612.log:String) [Copy-Item], IOException+ FullyQualifiedErrorId : CopyError,Microsoft.PowerShell.Commands.CopyItemCommand

Please advise,

Jomal


Batch - Move files to new folder, by matching string within filename

$
0
0

Hello... Assume the following test conditions:
In folder C:\images I have several image files named:

100.00001.png
100.00002.png

100.00003.png
200.00001.png
200.00002.png
200.00003.png

The batch should find all files with matching "100" string prefix (before first "." delimiter), and move it to a folder withinC:\images which is named after the search string (i.e.C:\images\100\). What I have so far finds the correct files (I think), but I'm having trouble moving them, I believe a nested for is required but my efforts so far have been failure. What I must do to get this working? 

@echo off

for /f "delims==" %%i in ('dir /b C:\images ^| findstr "100"') do (
echo %%i
rem MD C:\images\%%i
MOVE C:\images\%%i "C:\capture\100\"
)
pause

mailboxes that have not been accessed in 60 days.

$
0
0

Hi All,

Im looking to be able to get a report that lists all the mailboxes that have not been accessed in 60 days and export them to excel. I was using the following command Get-MailboxStatistics -server "YourServerName" | Where {($_.LastLogonTime -lt (get-date).adddays(-90))} | out-file C:\mailboxes.txt However we use commvault brick level backup every weekend which means that administrator account will access each account to back it up.


Ganga

Select-String command

$
0
0

Hi everyone,

I have a script below which displays everything that matches the keyword (such as security update and Office updates etc..).  How do I modify the above so that it only display the product installed (Microsoft Office 2010 or Microsoft Project 2010 etc.... 

If not, how do I exclude certain keyword such as "Security" or "update" etc..?

psinfo -s \\computername | Select-String 'Office','Project','Visio'

Thanks in advance.

move users to a new OU, getting information from .csv file.

$
0
0

I need a way to move users to a new OU, getting information for using via .csv file.

For example, I have some users with there login name need to move them to OU1

another users another files need to move them to OU2

any advice ?


@hmad

Exchange 03/07 Info Script

$
0
0
So I am in charge of moving our users off of Exchange 2003 to 2007. Is there a script that I can run on my Exchange 2003 server that will give me all the users with Mailboxes, if they are Active or Disabled, and also what server they are on?

Batch - Why is file extension removed during renaming of file in for loop iteration?

$
0
0
The batch script below is supposed to find dots in a filename and replace them withspaces. It accomplishes this objective, however it removes the extension, leaving me with a generic file type. Please explain why it includes the extension in the renaming process, and what I can do to remedy this?

@echo off
setlocal enabledelayedexpansion

set "space= "
set "dot=."

for %%i in ("C:\XXX\*.*") do (
   set name=%%~ni
   ren "%%i" "!name:%dot%=%space%!"
)
pause

New-PSDrive to SharePoint Office 365

$
0
0

How can I create a New-PSDrive to an instance of Office 365 over WebDAV?

I know I can do it by using the map network drive in the Windows Shell (then specyfing connect to Web site).

Just passing -Credentials into New-PsDrive does not work, I believe because Office 365 requires passing SAML tokens.

Please help.

Thx,

Adam

How to change sharing Permission of a folder using powershell

$
0
0

Hi Team,

I have a windows server 2008 R2 File Server.

1. I want to create a share folder on this remote File server for number of users

2. I Also want to give SHARE PERMISSION to respect Users on their Respective folders

How do I set SHARE PERMISSION of a remote file server folder ?

I was using SET_ACL but it set the permission for Security TAB.

Thanks

missing exchange PS cmdlets

$
0
0

I created a  file called Micro­soft.PowerShell_profile.ps1 and saved it under %UserProfile%\Documents\WindowsPowerShell\

with the following content

$Session = New-PSSession -ConfigurationName microsoft.exchange -ConnectionUri http://mail/powershel
Import-PSSession $Session

Now every time I start powershell on my pc, I get exchange cmdlets loaded temporary.

Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.0        tmp_zy4rlg52.g42                    {Add-MailboxFolderPermission, Clear-ActiveSyncDevice, Clea..

---------------------------------------------------------------------------

gcm | where { $_.modulename -like "*tmp*"} returns the following list, which does not seem as a complete exchange cmdlet list at all.

Any ideas what could be causing the problem?

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Add-MailboxFolderPermission                        tmp_zy4rlg52.g42
Function        Clear-ActiveSyncDevice                             tmp_zy4rlg52.g42
Function        Clear-MobileDevice                                 tmp_zy4rlg52.g42
Function        Disable-App                                        tmp_zy4rlg52.g42
Function        Disable-InboxRule                                  tmp_zy4rlg52.g42
Function        Enable-App                                         tmp_zy4rlg52.g42
Function        Enable-InboxRule                                   tmp_zy4rlg52.g42
Function        Get-ActiveSyncDevice                               tmp_zy4rlg52.g42
Function        Get-ActiveSyncDeviceStatistics                     tmp_zy4rlg52.g42
Function        Get-App                                            tmp_zy4rlg52.g42
Function        Get-CalendarProcessing                             tmp_zy4rlg52.g42
Function        Get-CASMailbox                                     tmp_zy4rlg52.g42
Function        Get-InboxRule                                      tmp_zy4rlg52.g42
Function        Get-Mailbox                                        tmp_zy4rlg52.g42
Function        Get-MailboxAutoReplyConfiguration                  tmp_zy4rlg52.g42
Function        Get-MailboxCalendarConfiguration                   tmp_zy4rlg52.g42
Function        Get-MailboxCalendarFolder                          tmp_zy4rlg52.g42
Function        Get-MailboxFolder                                  tmp_zy4rlg52.g42
Function        Get-MailboxFolderPermission                        tmp_zy4rlg52.g42
Function        Get-MailboxJunkEmailConfiguration                  tmp_zy4rlg52.g42
Function        Get-MailboxMessageConfiguration                    tmp_zy4rlg52.g42
Function        Get-MailboxRegionalConfiguration                   tmp_zy4rlg52.g42
Function        Get-MailboxSpellingConfiguration                   tmp_zy4rlg52.g42
Function        Get-MailboxStatistics                              tmp_zy4rlg52.g42
Function        Get-MessageCategory                                tmp_zy4rlg52.g42
Function        Get-MessageClassification                          tmp_zy4rlg52.g42
Function        Get-MessageTrackingReport                          tmp_zy4rlg52.g42
Function        Get-MobileDevice                                   tmp_zy4rlg52.g42
Function        Get-MobileDeviceStatistics                         tmp_zy4rlg52.g42
Function        Get-Recipient                                      tmp_zy4rlg52.g42
Function        Get-User                                           tmp_zy4rlg52.g42
Function        Get-UserPhoto                                      tmp_zy4rlg52.g42
Function        New-App                                            tmp_zy4rlg52.g42
Function        New-InboxRule                                      tmp_zy4rlg52.g42
Function        New-MailboxFolder                                  tmp_zy4rlg52.g42
Function        New-MailMessage                                    tmp_zy4rlg52.g42
Function        Remove-ActiveSyncDevice                            tmp_zy4rlg52.g42
Function        Remove-App                                         tmp_zy4rlg52.g42
Function        Remove-InboxRule                                   tmp_zy4rlg52.g42
Function        Remove-MailboxFolderPermission                     tmp_zy4rlg52.g42
Function        Remove-MobileDevice                                tmp_zy4rlg52.g42
Function        Remove-UserPhoto                                   tmp_zy4rlg52.g42
Function        Search-MessageTrackingReport                       tmp_zy4rlg52.g42
Function        Set-CalendarProcessing                             tmp_zy4rlg52.g42
Function        Set-CASMailbox                                     tmp_zy4rlg52.g42
Function        Set-InboxRule                                      tmp_zy4rlg52.g42
Function        Set-Mailbox                                        tmp_zy4rlg52.g42
Function        Set-MailboxAutoReplyConfiguration                  tmp_zy4rlg52.g42
Function        Set-MailboxCalendarConfiguration                   tmp_zy4rlg52.g42
Function        Set-MailboxCalendarFolder                          tmp_zy4rlg52.g42
Function        Set-MailboxFolderPermission                        tmp_zy4rlg52.g42
Function        Set-MailboxJunkEmailConfiguration                  tmp_zy4rlg52.g42
Function        Set-MailboxMessageConfiguration                    tmp_zy4rlg52.g42
Function        Set-MailboxRegionalConfiguration                   tmp_zy4rlg52.g42
Function        Set-MailboxSpellingConfiguration                   tmp_zy4rlg52.g42
Function        Set-MailUser                                       tmp_zy4rlg52.g42
Function        Set-UserPhoto                                      tmp_zy4rlg52.g42

HTA VBS errors in WinPE are blank! Why?

$
0
0

Hi folks,

I have an HTA which has some VBS.

Whenever I get a script error, a blank dialog box appears. Blue top bar, with an X, no text, and a large white box, no text or buttons.

The WinPE version we are using, if I type VER, is 6.1.7600.

Any ideas why this happens... and how to fix it? Would be really handy to know what line my script errors occur on. At the moment I have to put msgbox's in to try to catch where the error lies.

Thanks.

Powershell Script in WinPE "Property cannot be found" problem

$
0
0

Hi Im trying to run the following powershell script in WinPE while doing an SCCM OSD and am getting an error. The script is as follows:

***********

$drive = gwmi Win32_Volume | where {$_.DriveLetter -eq ""}

$drive.DriveLetter = "Z:"

$drive.Put()
***********

The script is supposed to select the volume that has a blank drive letter then sets it to Z:.

When running the second line I get an error "The property 'DriveLetter' cannot be found on this object"


Any ideas??

Scripts are not recognized by my computer

$
0
0

Hi everyone,
I got a script to get the membership of local groups in a server and I'm using as this:

Get-LocalGroupMembership -Computername server1 -Group Administrators

however, when I try to execute it I’m getting the following error:

The term ‘Get-LocalGroupMembership’ is not recognized as the name of a cmdlet, function, script file, or operable progr
am. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Suggestion [3,General]: The command Get-LocalGroupMembership was not found, but does exist in the current location. Wind
ows PowerShell doesn’t load commands from the current location by default. If you trust this command, instead type “.\Get-LocalGroupMembership”. See “get-help about_Command_Precedence” for more details.

Previously I tried to run the script as.\Get-LocalGroupMembership.ps1 but is not generating anything.

Could someone assist me how to correct this?

Thanks in advance,

Gerardo.


Exclude Subfolder from Batch Deletion - VBscript

$
0
0

Hello, a couple days ago I received some great help fixing a VB script that deletes any file older than 90 days and then goes through and deletes an empty directory. The original script runs without any issues, however now I have identified a single subfolder that needs to be excluded from this deletion and I am unable to get the script to function properly. All files and folders get deleted as expected however I can't figure out how to exclude this folder. I'm not the greatest at scripting and this is my first visualbasic script any assistance would be greatly appreciated. Here is the script I am currently using:

DIM objFSO, oShell
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
strPath = strHomeFolder & "\OneDrive - City of Bellevue"
ExdPath = strPath & "\Shared With Everyone"         <------- Folder I want Excluded
Set objFSO = CreateObject("Scripting.FileSystemObject")

Call Search (strPath)
WScript.Echo"Done."

Sub Search(str)
Dim objFolder, objSubFolder, objFile
Set objFolder = objFSO.GetFolder(str)
For Each objFile In objFolder.Files
If objFile.DateLastModified < (Now() - 90) Then
objFile.Delete(True)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Search(objSubFolder.Path)
' Files have been deleted, now see if
' the folder is empty.
If (objSubFolder.Files.Count = 0) Then
objSubFolder.Delete True
ElseIF (objFSO.Folder = ExdPath) Then    <----- Code I'm using to try to exclude the specified folder
   objFolder.Delete False 
End If
Next
End Sub



Kevin Craig A+ | Net+ | Sec+ | MSCA | CCNA

I need a script that will find the computer a user last logged into.

$
0
0

I am still learning scripting, I need a script that will allow me to pull in usernames from a csv file. Find what computer they last logged into and output that to an csv file.

I have looked all over and can't find exactly what I need.

 I found the following script but I need  to add the resuitsize unlimited but can not figure out where to put it we have a large environment. Also I need to be able to grab username from a csv file. Any assistance you can provide is appreciated.

##############################################################################################
##  Find out what computers a user is logged into on your domain by running the script
##  and entering in the requested logon id for the user.
##
##  This script requires the free Quest ActiveRoles Management Shell for Active Directory
##  snapin  http://www.quest.com/powershell/activeroles-server.aspx
##############################################################################################

Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
$ErrorActionPreference = "SilentlyContinue"

# Retrieve Username to search for, error checks to make sure the username
# is not blank and that it exists in Active Directory

Function Get-Username {
$Global:Username = Read-Host "Enter username you want to search for"
if ($Username -eq $null){
Write-Host "Username cannot be blank, please re-enter username!!!!!"
Get-Username}
$UserCheck = Get-QADUser -SamAccountName $Username
if ($UserCheck -eq $null){
Write-Host "Invalid username, please verify this is the logon id for the account"
Get-Username}
}

get-username resultsize unlimited

$computers = Get-QADComputer | where {$_.accountisdisabled -eq $false}
foreach ($comp in $computers)
{
$Computer = $comp.Name
$ping = new-object System.Net.NetworkInformation.Ping
  $Reply = $null
  $Reply = $ping.send($Computer)
  if($Reply.status -like 'Success'){
#Get explorer.exe processes
$proc = gwmi win32_process -computer $Computer -Filter "Name = 'explorer.exe'"
#Search collection of processes for username
ForEach ($p in $proc) {
    $temp = ($p.GetOwner()).User
  if ($temp -eq $Username){
write-host "$Username is logged on $Computer"
}}}}

How to get the drive letter of a Volume Number using CMD

$
0
0

Hi everyone,

Using windows command line tools i want to get the drive letter of a volume (by specifying its volume number, not volume label) and save it to an environment variable. Let me explain the problem:

I have a USB hard disk with two volumes. 0 and 1. My disk is always DISK1

I have a batch file which executes some operations on Volume-1.

We know it is not necessary 'every time same Drive letter will be used for portable devices on different PCs.

But Volume Numbers are files until you re-partitions the disk.

So i want to know which drive letter is assigned to DISK1's Volume Number-2, before executing batch file...

Some thing like this:

SET Lttr=<Command><VolumeNumber>

This can be done if we find it against Volume Label, But i need it using Volume Number.

Is there any method which can do this for me...

Thanks...


ASJoshan

Filter Records using value store in Extension Attribute

$
0
0

Hi, this is a long list of values(Employee ID) in csv file to be deleted from AD.  The employee ID is stored in extensionattribute15 in AD.

The function of the script is to search for AD users where extensionattribute15(store Employee ID) is identical to the values in CSV file.  There is only 1 column in the csv file.  The script below is not working, can you assist?  Any help would be greatly appreciated.  Thanks.

Script start here:

Import-ModuleActiveDirectory 

$users=Import-Csv -PathC:\test\Test.csv           

$today=get-date

foreach ($userin$users) {       

        $UserChkExist=Get-ADUser -Filter"extensionattribute15 -eq '$($user.EmployeeID)'"

             $today=get-date

 If ($UserChkExist-eq$null)

{

   Add-ContentC:\Test\TestFAIL.log"$($user.EmployeeID) not amended on$Today"

}

else{

Get-ADUser-Filter"extensionattribute15 -eq '$($user.EmployeeID)'"|Remove-ADUser

Add-ContentC:\Test\Test.log"$($user.EmployeeID) amended on$Today"

}

}

 

            

  


Fetch shared storage usage info from windows server.

$
0
0
I am trying to retrieve usage related info of shared storage attached to a server by using:
WMIC logicaldisk get size,freespace,caption,drivetype /Format:csv

The output is fine. But here the Drive type for drive-D is showing as 3, though its a Netapp Lun. Please let me know how to get Lun information. Its becomes tough for me to identify a Netapp volume if it is showing Netapp as Drivetype 3.
I do not have powershell installed in all the servers.So i can not use PS.

OUTPUT:
Node,Caption,DriveType,FreeSpace,Size
Hostname,C:,3,1522081792,20973137920
Hostname,D:,3,38534803456,751148986368
Hostname,E:,3,2867924992,52395274240
Hostname,F:,3,44005818368,73364254720
Hostname,R:,5,,
Viewing all 15028 articles
Browse latest View live


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