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

Windows Updates PowerShell Script

$
0
0

Hi All 

I have this Windows update Powershell script below which works pretty much fine. I would like to add a csv file that will contain multiple Serves and do the updates on them. The issue is getting the script to get the machines name from the CSV file and and update it based on the CSV file. Can anyone assist on this matter.

$UpdateSession = New-Object -Com Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
 
Write-Host("Searching for applicable updates...") -Fore Green
 
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")
 
Write-Host("")
Write-Host("List of applicable items on the machine:") -Fore Green
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    Write-Host( ($X + 1).ToString() + "> " + $Update.Title)
}
 
If ($SearchResult.Updates.Count -eq 0) {
    Write-Host("There are no applicable updates.")
    Exit
}
 
#Write-Host("")
#Write-Host("Creating collection of updates to download:") -Fore Green
 
$UpdatesToDownload = New-Object -Com Microsoft.Update.UpdateColl
 
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    #Write-Host( ($X + 1).ToString() + "> Adding: " + $Update.Title)
    $Null = $UpdatesToDownload.Add($Update)
}
 
Write-Host("")
Write-Host("Downloading Updates...")  -Fore Green
 
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Null = $Downloader.Download()
 
#Write-Host("")
#Write-Host("List of Downloaded Updates...") -Fore Green
 
$UpdatesToInstall = New-Object -Com Microsoft.Update.UpdateColl
 
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++){
    $Update = $SearchResult.Updates.Item($X)
    If ($Update.IsDownloaded) {
        #Write-Host( ($X + 1).ToString() + "> " + $Update.Title)
        $Null = $UpdatesToInstall.Add($Update)        
    }
}
 
$Install = [System.String]$Args[0]
$Reboot  = [System.String]$Args[1]
 
If (!$Install){
    $Install = Read-Host("Would you like to install these updates now? (Y/N)")
}
 
If ($Install.ToUpper() -eq "Y" -or $Install.ToUpper() -eq "YES"){
    Write-Host("")
    Write-Host("Installing Updates...") -Fore Green
 
    $Installer = $UpdateSession.CreateUpdateInstaller()
    $Installer.Updates = $UpdatesToInstall
 
    $InstallationResult = $Installer.Install()
 
    Write-Host("")
    Write-Host("List of Updates Installed with Results:") -Fore Green
 
    For ($X = 0; $X -lt $UpdatesToInstall.Count; $X++){
        Write-Host($UpdatesToInstall.Item($X).Title + ": " + $InstallationResult.GetUpdateResult($X).ResultCode)
    }
 
    Write-Host("")
    Write-Host("Installation Result: " + $InstallationResult.ResultCode)
    Write-Host("    Reboot Required: " + $InstallationResult.RebootRequired)
 
    If ($InstallationResult.RebootRequire -eq $True){
        If (!$Reboot){
            $Reboot = Read-Host("Would you like to install these updates now? (Y/N)")
        }
 
        If ($Reboot.ToUpper() -eq "Y" -or $Reboot.ToUpper() -eq "YES"){
            Write-Host("")
            Write-Host("Rebooting...") -Fore Green
            (Get-WMIObject -Class Win32_OperatingSystem).Reboot()
        }
    }
}


PowerShell - StopService with variable

$
0
0

Hi people mi need help

I am try create a script of stop services with variable values,  as down my script:

Clear-Host

$serviceList=gcservicos.txt

foreach ($servicein$serviceList)

{

$service=$service-split(',')

$first=$service[0]

$second=$service[1]

$third=$service[2]

echo$first

Get-Service-InputObject$first|Start-Service

echo$second

Get-Service-InputObject$second|Start-Service

echo$third

Get-Service-InputObject$third|Start-Service

I get an error over the service ends successfully

 et-Service : Cannot bind parameter 'InputObject'. Cannot convert value "" to type "System.ServiceProcess.ServiceController". 

Error: "Invalid value  for parameter name."

At line:10 char:26

+ Get-Service -InputObject $first | Start-Service

+                          ~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Get-Service], ParameterBindingException

    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetServiceCommand

 

Get-Service : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Provide an argument that is 

not null or empty, and then try the command again.

At line:12 char:26

+ Get-Service -InputObject $second | Start-Service

+                          ~~~~~~~

    + CategoryInfo          : InvalidData: (:) [Get-Service], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetServiceCommand

 

Get-Service : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Provide an argument that is 

not null or empty, and then try the command again.

At line:14 char:26

+ Get-Service -InputObject $third | Start-Service

+                          ~~~~~~

    + CategoryInfo          : InvalidData: (:) [Get-Service], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetServiceCommand 

move-item asks for path[0]

$
0
0

I have the following script that Im trying to use based on a posting from June Blender in 2013.

$archivedate = (Get-Date).AddDays(-61)
$files = get-childitem -recurse E:\ftp-folder\UFSI-VA-WAVE-back |
 where-object {$_.lastWriteTime -lt $ArchiveDate}
foreach ($file in $files)
{
 $newName = $file.fullname -Replace 'E:\\ftp-folder','F:\\archive'
 move-item -Destination $newname
}

when I run it, powershell gives me this:

cmdlet Move-Item at command pipeline position 1
Supply values for the following parameters:
Path[0]: PS C:\Scripts>
PS C:\Scripts> .\move-back61.ps1

cmdlet Move-Item at command pipeline position 1
Supply values for the following parameters:
Path[0]:

why doesn't it find the path of the current $file?

Thanks!

Steve

Change Default PSSession Configuration

$
0
0

Hi,

I'm not sure if this is at all possible & I can't find any documentation that suggests it is, so I'm hoping someone here might be able to answer the questions.

I've created a PowerShell toolkit that I want to install on production servers, this toolkit contains a series of diagnostic utilities to do things like take memory dumps and upload them to a shared storage location.

I can register a restricted PS-Session configuration, using Register-PSSessionConfiguration, which includes a custom script that restricts the cmdlets available, but loads the utilities. This all works perfectly and we're very happy with the solution.

The issue I have is that a user can enter this restricted environment by using:

Enter-PsSession REMOTEHOST -ConfigurationName "MyConfiguration"

But they can also access an unrestricted remote shell by just using:

Enter-PsSession REMOTEHOST

Is there any way to configure the default PSSessionConfiguration to use my restricted environment script?

Many thanks,

Howard


Howard van Rooijen co-founder | @endjin

Runspace error

Powershell script not recognising Functions

$
0
0

I've written the following PS script to delete logfiles from specific server paths. I'm a novice to PS but I'm getting some errors with a few of the functions that I have written in this script:

#* FileName: FileCleaner.ps1
#Clear the screen
Clear

#Read XML Config File to get settings
[xml]$configfile = Get-Content "C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell Script\FileCleaner.config.xml"

#Declare and set variables from Config values
$hostServer = $configfile.Settings.HostServer
$dirs = @($configfile.Settings.DirectoryName.Split(",").Trim())
$scanSubDirectories = $configfile.Settings.ScanSubDirectories
$deleteAllFiles = $configfile.Settings.deleteAllFiles
$fileTypesToDelete = @($configfile.Settings.FileTypesToDelete.Split(";").Trim())
$liveSiteLogs = $configfile.Settings.LiveSiteLogs
$fileExclusions = @($configfile.Settings.FileExclusions.Split(";").Trim())
$retentionPeriod = $configfile.Settings.RetentionPeriod
$AICLogs = $configfile.Settings.AICLogs
$AICLogsRententionPeriod = $configfile.Settings.AICLogsRententionPeriod
$fileCleanerLogs = $configfile.Settings.FileCleanerLogs
$fileCleanerLogsRententionPeriod = $configfile.Settings.FileCleanerLogsRententionPeriod

#Setup FileCleaner output success logfiles
$successLogfile = $configfile.Settings.SuccessOutputLogfile
$dirName  = [io.path]::GetDirectoryName($successLogfile)
$filename = [io.path]::GetFileNameWithoutExtension($successLogfile)
$ext = [io.path]::GetExtension($successLogfile)
$successLogfile = "$dirName\$filename$(get-date -Format yyyy-MM-dd)$ext"

#Setup FileCleaner output error logfiles
$errorLogfile = $configfile.Settings.ErrorOutputLogfile
$dirName  = [io.path]::GetDirectoryName($errorLogfile)
$filename = [io.path]::GetFileNameWithoutExtension($errorLogfile)
$ext = [io.path]::GetExtension($errorLogfile)
$errorLogfile = "$dirName\$filename$(get-date -Format yyyy-MM-dd)$ext"

#Setup Retention Period
$LastWrite = (Get-Date).AddDays(-$retentionPeriod)#.ToString("d")
$AICLastWrite = (Get-Date).AddDays(-$AICLogsRententionPeriod)#.ToString("d")
$fileCleanerLastWrite = (Get-Date).AddDays(-$fileCleanerLogsRententionPeriod)

#EMAIL SETTINGS
$smtpServer = $configfile.Settings.SMTPServer
$emailFrom = $configfile.Settings.EmailFrom
$emailTo = $configfile.Settings.EmailTo
$emailSubject = $configfile.Settings.EmailSubject
#Update the email subject to display the Host Server value
$emailSubject -replace "HostServer", $hostServer

$countUnaccessibleUNCPaths = 0

#Check Logfiles exists, if not create them
if(!(Test-Path -Path $successLogfile))
{
    New-Item -Path $successLogfile –itemtype file
}

if(!(Test-Path -Path $errorLogfile))
{
    New-Item -Path $errorLogfile  –itemtype file
}

foreach ($dir in $dirs)
{
#needs a check to determine if server/the UNC Path is accessible. If it fails to connect, it needs to move on to the next UNC share but a flag needs to
#be generate to alert us to investigate why the UNC share was not accessible during the job run.
If(Test-Path -Path $dir)
{
    #write to output logfile Directory info
    $Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $dir"
    $Msg | out-file $successLogfile

    If ($scanSubDirectories -eq "True")
    {
        If ($deleteAllFiles -eq "True")
        {
            #ScanSubDirectories and delete all files older than the $retentionPeriod, include Sub-Directories / also forces the deletion of any hidden files
            $logFiles = Get-ChildItem -Path $dir -Force -Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$LastWrite" }
            DeleteLogFiles($logFiles)
            #foreach($logFile in $logFiles)
            #{
            #    if($logFile -ne $null)
            #    {
            #        $Msg = Write-Output "$("Deleting File $logFile")"
            #        $Msg | out-file $successLogfile -append
            #        Remove-Item $logFile.FullName -Force
            #    }
            #}
        }
        Else
        {
            #"ScanSubDirectories but only delete specified file types."
            $logFiles = Get-Childitem $dir -Include $fileTypesToDelete[0],$fileTypesToDelete[1],$fileTypesToDelete[2], $liveSiteLogs -Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where {$_.LastWriteTime -le "$LastWrite"}
            DeleteLogFiles($logFiles)
            #foreach($logFile in $logFiles)
            #{
            #    if($logFile -ne $null)
            #    {
            #        $Msg = Write-Output "$("Deleting File $logFile")"
            #        $Msg | out-file $successLogfile -append
            #        Remove-Item $logFile.FullName -Force
            #    }
            #}
        }
    }
    Else
    {
        #Only delete files in top level Directory
        If ($deleteAllFiles -eq "True")
        {
            $logFiles = Get-ChildItem -Path $dir -Force -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$LastWrite" }
            DeleteLogFiles($logFiles)
            #foreach($logFile in $logFiles)
            #{
            #    if($logFile -ne $null)
            #    {
            #        $Msg = Write-Output "$("Deleting File $logFile")"
            #        $Msg | out-file $successLogfile -append
            #        Remove-Item $logFile.FullName -Force
            #    }
            #}
        }
        Else
        {
            $logFiles = Get-Childitem $dir -Include $fileTypesToDelete[0],$fileTypesToDelete[1],$fileTypesToDelete[2], $liveSiteLogs -Exclude $fileExclusions[0],$fileExclusions[1] | Where {$_.LastWriteTime -le "$LastWrite"}
            DeleteLogFiles($logFiles)
            #foreach($logFile in $logFiles)
            #{
            #    if($logFile -ne $null)
            #    {
            #        $Msg = Write-Output "$("Deleting File $logFile")"
            #        $Msg | out-file $successLogfile -append
            #        Remove-Item $logFile.FullName -Force
            #    }
            #}
        }
    }
}
Else
{
    $countUnaccessibleUNCPaths++
    #server/the UNC Path is unaccessible
    $Msg = Write-Output  "$(Get-Date -UFormat "%D / %T") Unable to access $dir."
    $Msg | out-file $errorLogfile -append
}
# Call the function to Delete the AIC XML Logfiles
DeleteAICXMLLogs $dir
}
#If any of the directories were unaccessible send an email to alert the team
if($countUnaccessibleUNCPaths.count -gt 0)
{
# Call the function to send the email
SendEmail $emailSubject $emailFrom $emailTo
}

#Only keep 2 weeks worth of the FileCleaner App logs for reference purposes
If(Test-Path -Path $fileCleanerLogs)
{
#write to output logfile Directory info
$Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $fileCleanerLogs"
$Msg | out-file $successLogfile

$fileCleanerLogs = Get-Childitem $fileCleanerLogs -Recurse | Where {$_.LastWriteTime -le "$fileCleanerLastWrite"}
DeleteLogFiles($fileCleanerLogs)
#foreach($fileCleanerLog in $fileCleanerLogs)
#{
#    if($fileCleanerLog -ne $null)
#    {
#        $Msg = Write-Output "$("Deleting File $fileCleanerLog")"
#        $Msg | out-file $successLogfile -append
#        Remove-Item $fileCleanerLog.FullName -Force
#    }
#}
}

Function DeleteLogFiles($logFiles)
{
    foreach($logFile in $logFiles)
    {
        if($logFile -ne $null)
        {
        $Msg = Write-Output "$("Deleting File $logFile")"
        $Msg | out-file $successLogfile -append
        Remove-Item $logFile.FullName -Force
        }
    }
}

Function DeleteAICXMLLogs($dir)
{
    #Split the UNC path $dir to retrieve the server value
    $parentpath = "\\" + [string]::join("\",$dir.Split("\")[2])
    #test access to the \\server\D$\DebugXML path
    If(Test-Path -Path $parentpath$AICLogs)
    {
        $Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $parentpath$AICLogs"
        $Msg | out-file $successLogfile

        #Concantenate server value to $AICLogs to delete all xml logs in \\server\D$\DebugXML with a retention period of 30Days
        $XMLlogFiles = Get-ChildItem -Path $parentpath$AICLogs -Force -Include $fileTypesToDelete[3]-Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$AICLastWrite" }
        #get each file and add the filename to be deleted to the successLogfile before deleting the file
        DeleteLogFiles($XMLlogFiles)
    #foreach($XMLlogFile in $XMLlogFiles)
    #{
    #    if($XMLlogFile -ne $null)
    #    {
    #        $Msg = Write-Output "$("Deleting File $XMLlogFile")"
    #        $Msg | out-file $successLogfile -append
    #        Remove-Item $XMLlogFile.FullName -Force
    #    }
    #}
}
Else
{
    $Msg = Write-Output "$("$parentpath$AICLogs does not exist.")"
    $Msg | out-file $successLogfile -append
}
}

Function SendEmail($emailSubject, $emailFrom, $emailTo)
{
    $MailMessage = New-Object System.Net.Mail.MailMessage
    $SMTPClient = New-Object System.Net.Mail.smtpClient
    $SMTPClient.host = $smtpServer
    $Recipient = New-Object System.Net.Mail.MailAddress($emailTo, "Recipient")
    $Sender = New-Object System.Net.Mail.MailAddress($emailFrom, "Sender")

    $MailMessage.Sender = $Sender
    $MailMessage.From = $Sender
    $MailMessage.Subject = $emailSubject
    $MailMessage.Body = @"
    This email was generated because the FileCleaner script was unable to access some UNC Paths, please refer to $errorLogfile for more information.

Please inform the Team if you plan to resolve this.

This is an automated email please do not respond.
"@
    $SMTPClient.Send($MailMessage)
}

when debugging I'm getting these errors:

DeleteAICXMLLogs : The term 'DeleteAICXMLLogs' 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. At C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell Script\FileCleaner.ps1:158 char:5 + DeleteAICXMLLogs $dir + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (DeleteAICXMLLogs:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

SendEmail : The term 'SendEmail' 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. At C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell Script\FileCleaner.ps1:164 char:5 + SendEmail $emailSubject $emailFrom $emailTo + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (SendEmail:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

DeleteLogFiles : The term 'DeleteLogFiles' 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. At C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell Script\FileCleaner.ps1:175 char:5 + DeleteLogFiles($fileCleanerLogs) + ~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (DeleteLogFiles:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

I don't see anything wrong with how I'm declaring the functions and calling them, any ideas why this script is failing?


Delete bulk contacts via powershell?

$
0
0

Hello,

I would like to know if it is possible to delete contacts in bulk via a cmdlet?

I know that there is a delete all contacts cmdlet. Not looking for that one.

Thank you.

Return List of Systems Pending Reboot (Powershell)

$
0
0

This script returns a list of all systems needing a reboot from Windows Patches when run on a WSUS server:


[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null

if (!$wsus) {
        $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer();
This script returns a list of all systems needing a reboot from Windows Patches when run on a WSUS server:


}

$computerScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetScope;
$computerScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot;

$updateScope = new-object Microsoft.UpdateServices.Administration.UpdateScope;
$updateScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot;

$computers = $wsus.GetComputerTargets($computerScope);

$computers | foreach-object {
                $_.FullDomainName | write-host;
     }



But how do you edit it to generate the list for a specific WSUS container? I tried the following:


[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null

if (!$wsus) {
        $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer();
}

$computerScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetGroupId::SpecificWSUSContainer;
$computerScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot;

$updateScope = new-object Microsoft.UpdateServices.Administration.UpdateScope;
$updateScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot;

$computers = $wsus.GetComputerTargetGroup($computerScope);

$computers | foreach-object {
                $_.FullDomainName | write-host;
     }



But this does not work. Any ideas?


How to list the Cert Issuer for all servers in a Domain

$
0
0

Hello,

The objective is to list the Server name and Cert Issuer for any Cert found in the LocalMachine\My store on all servers in a Domain.

Once I'd get to a server, probably by PS remoting, I'd issue the following:

dir cert:\localmachine\my -recurse | ? Issuer -like '*'

However, the output is Thumbprint and Subject, but I really need to see the Issuer, or what is displayed in the Certificates MMC under the 'Issued By' column.  What I need in my output is the following:

ComputerName       Issuer

Srv1                       Acme Cert Auth

Srv2                       Host1.Acme.Com

Any suggestions would be appreciated.


Thanks for your help! SdeDot

Install software remotely via Powershell

$
0
0

I'm trying to remotely install an application (Office 2010 Pro to be exact) and it works when I run it locally, but fails when i try it remotely. I have this syntax which I see commonly online as the preferred method to remote install, but it's not working. There are no errors when I run the script... the install just never starts. Again no issues when running locally.

Any help or troubleshooting recommendations would be much appreciated. I have to get this installed on hundreds of computers.

Current Code:

$InstallString = '"\\servershare\Office 2010\setup.exe" /adminfile Updates/OfficeSetup.MSP /config ProPlus.WW/config.xml"'
([WMICLASS]"\\computer1\ROOT\CIMV2:Win32_Process").Create($InstallString)


Please mark my post as helpful or the answer or better yet.... both! :) Thanks!

How to add hash table values to SQL Table using Powershell

$
0
0

Hi,

I have sharepoint list with four(column1, column2, column3,column4)columns.I am reading the list column values and adding to hashtable. Now I want to add values from hastable to SQL table with four(column1, column2, colum3,column4)columns using powershell.

I have written the following script for single column but I would like to know how to add values for multiple columns.



            if(($key -eq "Column1") )
            {

               $SqlQuery = "INSERT INTO [TableName] ([Column1]) VALUES ('" + $HashTable.Item($key) +"')"
               #Set new object to connect to sql database
               $connection = new-object system.data.sqlclient.sqlconnection
               $Connection.ConnectionString ="server=SQLServerName;database=SQLDBName;Integrated Security = True;"
          $connection #List connection information 
               $connection.open() #Open Connection
             $Cmd = New-Object System.Data.SqlClient.SqlCommand
             $Cmd.CommandText = $SqlQuery
               $Cmd.Connection = $connection
              $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
              $SqlAdapter.SelectCommand = $SqlCmd
              $DataSet = New-Object System.Data.DataSet
              $SqlAdapter.Fill($DataSet)
              $DataSet.Tables[0]
              $connection.Close()

Can anybody please help me out to accomplish the task? Any help would be greatly appreciated.

Thank you advance.

                                        

AA.

Change Calendar default sharing policy

$
0
0

Hi Guys,

The Office365 and Exchange Online support person refer me to this forum. Could any one please help?

Here is the story:

We are using Exchange Online and Office365.

My boss ask me to force all users to share their detailed calendar to other, not just "free and busy".

I know we can do it manually one by one, but considering lots of users aren't skilled computer cooperate, so I want it to be done automatically by using script.

I found a quite useful link: http://community.office365.com/en-us/f/158/t/54401.aspx

The powershell script mentioned on the above thread was running successfully, however, when I back to check the calendar of Outlook2013, nothing has been changed after running the script. Some users have their calender displayed as free or busy.

Please notice our domain is XXX.local and our primary email address is @XXX.co. I am not sure which one to be used in the script.

Here is the details of my script:

PS C:\Users\Administrator.XXX> Set-SharingPolicy -Identity "Default Sharing Policy" -Domains 'XXX.co:CalendarSharingFree
BusyReviewer', 'Anonymous:CalendarSharingFreeBusyReviewer', '*:CalendarSharingFreeBusySimple'
Creating a new session for implicit remoting of "Set-SharingPolicy" command...

PS C:\Users\Administrator.XXX> Get-SharingPolicy |fl


RunspaceId : 07e0f104-d386-4676-843d-XXXXXXXXXX
Domains : {XXX.co:CalendarSharingFreeBusyReviewer, Anonymous:CalendarSharingFreeBusyReviewer,
*:CalendarSharingFreeBusySimple}
Enabled : True
Default : True
AdminDisplayName :
ExchangeVersion : 0.10 (14.0.100.0)
Name : Default Sharing Policy
DistinguishedName : CN=Default Sharing Policy,CN=Federation,CN=Configuration,CN=xxxapps.onmicrosoft.com,CN=Configuratio
nUnits,DC=APCPR01A001,DC=prod,DC=outlook,DC=com
Identity : Default Sharing Policy
Guid : 807d8414-3e10-47f3-bddf-xxxxxxxxxxxx
ObjectCategory : APCPR01A001.prod.outlook.com/Configuration/Schema/ms-Exch-Sharing-Policy
ObjectClass : {top, msExchSharingPolicy}
WhenChanged : 25/03/2015 9:36:25 a.m.
WhenCreated : 12/06/2013 11:49:42 a.m.
WhenChangedUTC : 24/03/2015 8:36:25 p.m.
WhenCreatedUTC : 11/06/2013 11:49:42 p.m.
OrganizationId : APCPR01A001.prod.outlook.com/Microsoft Exchange Hosted Organizations/xxxapps.onmicrosoft.com -
APCPR01A001.prod.outlook.com/ConfigurationUnits/xxxapps.onmicrosoft.com/Configuration
Id : Default Sharing Policy
OriginatingServer : xxxxxxxxxxxxxx.APCPR01A001.prod.outlook.com
IsValid : True
ObjectState : Changed

 

Could anyone please advise if I make a mistake?

Thank you very much in advance.

Cheers,

Vincent

WSUS and Windows Update

$
0
0
In a workgroup environment, no domain, no group policy, cannot configure registry key on the client.

From my management machine I want to run a powershell script to download patches from a specific patch group in wsus onto this new machine and install the patches.

How can I achieve this with Powershell?
How do I approve patches using powershell.

Help with Functions.

$
0
0

I have a code that works:

$IngInterfaceIndex = (Get-WmiObject win32_networkadapter -Filter "netconnectionstatus = 2").InterfaceIndex
Write-Host 'InterfaceIndex is ' $IngInterfaceIndex

If (( $strHostName -match "666") -OR ( $strHostName -match "SFM"))
{
 "Location is 666 and San Fran"
 Set-DnsClientServerAddress -InterfaceIndex $IngInterfaceIndex -ServerAddresses ("1.1.1.1","2.2.2.2")
}

I would like to start using functions, so i tried this:

The idea is to use the function to get the InterfaceIndex.

However i am getting an error:

Set-DnsClientServerAddress : Cannot process argument transformation on parameter 'InterfaceIndex'. Canno
value "InterfaceIndex" to type "System.UInt32[]". Error: "Cannot convert value "InterfaceIndex" to type "System.UInt32". Error: "Input string was not in a correct format.""

When i call the function first time i am getting the correct value. However when i try to use it inside Set-DnsClientServerAddressi get an error.

What am i missing?

Function InterfaceIndex
{
 $IngInterfaceIndex = (Get-WmiObject win32_networkadapter -Filter "netconnectionstatus = 2").InterfaceIndex
 Write-Host 'InterfaceIndex is ' $IngInterfaceIndex
}

If (( $strHostName -match "666") -OR ( $strHostName -match "SFM"))
{
 InterfaceIndex
 "Location is 666 and San Fran"
 Set-DnsClientServerAddress -InterfaceIndex InterfaceIndex -ServerAddresses ("1.1.1.1","2.2.2.2")
}

Thanks for the help.

Connecting exchange server from remote machine failed with error

$
0
0

hi,

Try  to connect exchange server from remote machine.

$session = new-pssession -connectionURI "http://XXXXXXX/powershell?serializationLevel=Full" -ConfigurationName "http://schemas.microsoft.com/powershell/Microsoft.Exchange" -Credential $user

Import-PSSession $Session

failed with access denied error 


then   i checked the remote machine , to know how trusted hosts configured .

machine confgured with 'trustedhosts *'


then i reset trusted host settings to null value.. its works fine

my question is ,what is the difference between 

Set-Item wsman:\localhost\client\trustedhosts *

and

Set-Item wsman:\localhost\client\trustedhosts null

thank you

sumith


Count Sessions in a Powershell output

$
0
0

Hello,

currently I'm working on a PowerShell Script to Count Sessions by Application.

Therefor I use this script: 

Get-XASession | where-object {$_.BrowserName -ne "" } | Select BrowserName | Group BrowserName | where {$_.Count -gt 0}

This generates a output like:

Count   Name        Group
-----   ----        -----
   84   Notepad     {@{BrowserName=Notepad}
    4   Wordpad     {@{BrowserName=Wordpad}, @{BrowserName=Notepad}, @{BrowserName=Paint}
   23   Paint       {@{BrowserName=Paint}, @{BrowserName=Wordpad}

How can I summerize all counts in PowerShell?

Greetings

Uemit

get-process and UserName

$
0
0
Hi,
I'm trying to list all/some process and need to include the username since the script has to run in a terminal server environment. It works using WMI (Get-WmiObjectWin32_Processand GetOwner()) but get-process provides some more attributes I need to export to  a logfile.

Accoring to MSDN there is a property called UserName in the StartInfo object, but the value is always empty, when executing this script:

get-process

outlook | select-object id, path, @{Name="UserName";Expression = {$_.StartInfo.UserName}}

What's wrong? I am fairly new to PS, so is this the correct way of reading that property?


Thanks, regards

Acces Denied when running set-aduser and delegated rights

$
0
0

Hi,

when a user with delegated rights run a script to change an specific field he gets the message access denied.

If he changes the value over the ADUC snapin, he can change the field where he has the rights.  

if ($objext2txtbox.text -ne "") {set-aduser -Identity $user.DistinguishedName[0] -Replace @{employeeNumber=@($objext2txtbox.text)}} else {$user.employeeNumber.clear()}

Above the codesnip where the change will be set. If the complete code is required i can post that one too.

Best regards

Malte

How do I remove multiple XML elements?

$
0
0

Hi guys,

I am writing a script that  amends an XML file. I'm still troubleshooting some of the finer points, but to save time, I was thinking I add something to my code the removes the new xml I have added, every time I run the code again.

<employees><newXML><newTextNode>temp</newTextNode></newXML><newXML><newTextNode>temp</newTextNode></newXML><newXML><newTextNode>temp</newTextNode></newXML><newXML><newTextNode>temp</newTextNode></newXML><newXML><newTextNode>temp</newTextNode></newXML></employees>


The above is an example of what my script does to the employees.xml. It creates newXML nodes with a text node within them. 

Every time I run my script it just adds more and more nodes to the list. Not what I really want. So is there anyway to get rid of all these newXML nodes?

I've tried this:

try{
    $node = $xdoc."employees"

    $i=0

    foreach($item in $node)
    {
        $i= $i+1
        $node.ParentNode.RemoveChild($node[$i])
    }
}
catch{ write-host "The employees node is empty" }

When I run this, it always goes straight to my catch. Any thoughts?

How to change size for pop-up history window

$
0
0

Hello!

I work with PoSH and like use shortcut F7 for access to history powershell commands. But it is very small for my purposes.

Powershell popup history window

Are there way to change size (increase) this window?


Truly, Valery Tyurin

Viewing all 21975 articles
Browse latest View live


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