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

SharePoint Sandbox Solution - Powershell

$
0
0

Hello,

i want to have a list off all my Sandbox Solutions from every webapp and there Site Collections.

How can i realize this, i doesn't find any idea at www.


Thanks Horst MOSS 2007 Farm, MOSS 2010 Farm, TFS 2008, TFS 2010

DSC: How to create mofs from Configuration File and Configuration Data File

$
0
0
I have a configuration data file like data.psd1
@{
    AllNodes = @(
        @{
            NodeName = "*"
            LogPath = "C:\Logs"
        },
        @{
            NodeName = "machine1";
            Roles = @( "SmtpRole", "WebRole" )
        },
        @{
            NodeName = "machine2";
            Roles = @( "SmtpRole" )
        }
    )
}

I have a configuration like FarmConfiguration.ps1
Configuration FarmConfiguration {
    Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
    Import-DscResource -ModuleName 'MyCustomDsc'
    Node $AllNodes.NodeName
    {
        SimpleTcpIpConfiguration SimpleTcpIp
        {
        }
    }
    Node $AllNodes.Where{$_.Roles -contains "WebRole"}.NodeName
    {
        WebConfiguration Web
        {
        }
    }
    Node $AllNodes.Where{$_.Roles -contains "SmtpRole"}.NodeName
    {
        SmtpConfiguration Smtp
        {
        }
    }
}

I know if I add "FarmConfiguration-ConfigurationData ConfigurationData.psd1" to the bottom of my FarmConfiguration.ps1 file then everything works fine.
But this is a big problem I don't want my FarmConfiguration to know about the data file at all, it's check into source control.
I want to be able to creates MOFs based on various different data files how can I do this?  Thanks.

Convert rows to columns without header and delimiters

$
0
0

Hi,

I have a simple txt file like this :

349.67
54
547
34
45
67.67
78
3
349.6


I would like to transpose data like this :

349.67;54;547;34;45;67.67;78;;3;349.6

Is It possible ?

Thank you in advance

F.

Remove ISAPI Filter in IIS

$
0
0

I'm writing a PowerShell script that needs to configure about a million things, one of which is that it needs to remove an existing ISAPI filter from IIS.   The other IIS related tasks I've been able to accomplish using Remove-Item after using the importing the WebAdminstration module.  However, I can't figure-out how to remove an ISAPI filter that is configured at the root of the default web site.  Any tips, please?


How can I Import-Csv a csv file that has multi-line fields

$
0
0

Hello,

I am trying to process a CSV file that has some multi line fields. If for example I were to open the file with notepad, it would look like this:

header 1, header 2, header 3......

header1text, header2text, header3text

header1text, header2text
header2 some more text, header3text

Excel seems to be able to manage this fine if I just open it directly from explorer, but I can't figure out how to make this work using Import-CSV.

Is there any way that I could get this to work correctly? It's not big deal if I just have to script something in excel to process the data, but it would be nice if I could find out how to get things working correctly in powershell. 

Powershell galleries

$
0
0
Hi,

Has anyone managed to get the internet access from Powershell v5 for the Powershell gallery to work, typically with nuget based repositories? If yes, please share how you did.

This is what I see:

"WARNING: Unable to download the list of available providers. Check your internet connection."

Internet access is there from the machine when browsed from Internet explorer

Thanks

Export Outlook Folders.vbs

$
0
0
Sorry all just changing it up a bit. I have a vb script to pull all folders in a users mailbox to a text file however the file is outputted it goes to their desktop. I would like to change that location to the root of their home drive and to also pull the folder size.  
Dim MyFile, Structured, Base

Call ExportFolderNamesSelect()

Public Sub ExportFolderNamesSelect()
  Dim objOutlook
  Set objOutlook = CreateObject("Outlook.Application")

  Dim F, Folders
  Set F = objOutlook.Session.PickFolder

  If Not F Is Nothing Then
    Set Folders = F.Folders

    Dim Result
    Result = MsgBox("Do you want to structure the output?", vbYesNo+vbDefaultButton2+vbApplicationModal, "Output structuring")
    If Result = 6 Then
      Structured = True
    Else
      Structured = False
    End If

    MyFile = GetDesktopFolder() & "\outlookfolders.txt"
    Base = Len(F.FolderPath) - Len(Replace(F.FolderPath, "\", "")) + 1

    WriteToATextFile (StructuredFolderName(F.FolderPath, F.Name) & " " & F.Items.count)

    LoopFolders Folders

    Set F = Nothing
    Set Folders = Nothing
    Set objOutlook = Nothing
  End If
End Sub

Private Function GetDesktopFolder()
  Dim objShell
  Set objShell = CreateObject("WScript.Shell")
  GetDesktopFolder = objShell.SpecialFolders("Desktop")
  Set objShell = Nothing
End Function

Private Sub LoopFolders(Folders)
  Dim F

  For Each F In Folders
    WriteToATextFile (StructuredFolderName(F.FolderPath, F.Name)  & " " & F.Items.count)
    LoopFolders F.Folders
  Next
End Sub

Private Sub WriteToATextFile(OLKfoldername)
  Dim objFSO, objTextFile
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objTextFile = objFSO.OpenTextFile (MyFile, 8, True)
  objTextFile.WriteLine (OLKfoldername)
  objTextFile.Close
  Set objFSO = Nothing
  Set objTextFile = Nothing
End Sub

Private Function StructuredFolderName(OLKfolderpath, OLKfoldername)
  If Structured = False Then
    StructuredFolderName = Mid(OLKfolderpath, 3)
  Else
    Dim i, x, OLKprefix
    i = Len(OLKfolderpath) - Len(Replace(OLKfolderpath, "\", ""))

    For x = Base To i
      OLKprefix = OLKprefix & "-"
    Next

    StructuredFolderName = OLKprefix & OLKfoldername
  End If
End Function

The WS-management service cannot process the request

$
0
0

Hello everyone

I am fighting with "Desired State Configuration" but I must say I am not finding easy. I've got a windows server 2012 and created a .MOF file with no problems. However when I run: 

start-dscconfiguration -wait -verbose -path <some_path>

 

I get the following error:

The WS-Management service cannot process the request.

The service cannot find the resource identified by the resource URI and selectors.

+CategoryInfo :ObjectNotFound: (root/Microsoft/...gurationManager:String) [], CimException

+FullyQualified ErrorId: Hresult 0x80338000

+PCComputerName: beftaki

Please note the client machine is windows 7.  

Any suggestions please?

Thank you




Migrating from IBM Notes to Federated O365

$
0
0

I have TXT/CVS files with lists of Name, email address of over 300 mailin/shared mailfiles and about 100 department calendars. Would it be pro-active to create placeholder shared mailboxes/ calendars into tenant, prior to migration, using powershell?

What would be the powershell commands to create bulk shared mailboxes and calendars into the tenant?

Any assistance would be appreciated.

Get-Eventlog the time of the day

$
0
0

Hi all,

The idea here is to get how many times people logged into a PC in a certain time period. how many before 8, how many between 8-10 ..etc. Eventually it will tell us how many people logged into a PC during a given month entered by the user and tell us the number of logons in range of time.

$TimeCounter = 0

$event = Get-EventLog -LogName System -InstanceId "7001" | Select-Object Timewritten | ForEach-Object { if (( $_.Timewritten.ToShortTimeString() -ge "08:00 AM") -and ($_.Timewritten.ToShortTimeString() -le "10:00 AM")) {$TimeCounter++} }

$TimeCounter
$event.Count
$event

The issue is I can display the time, I can count the events but it does not recognize the time. if I change it to ForEach-Object { if ($_.Timewritten.ToShortTimeString() -le "18:00") {$TimeCounter++} } I get 3 counts but they were empty lines. TIA

Powershell Script to create IIS director runs sucessfully on ISE but when I put it in my PHP code it does not run.

$
0
0

Hello,

I hope someone can help me.  I am trying to learn powershell and I have hit a dead end.  I have 3 items that I am creating.

1.  Welcome.php page

2.  Input.html page

3.  Powershell script IIS.ps1.

If I run the powershell script on the ISE it works fine.  It creates a IIS virtual directory for me and a physical directory.  But when I use php 

<html>
<body>
<?php $psScriptPath = "c:\\IIS.ps1";?>
<?php $query=shell_exec('C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Noninteractive -command ".c:\iis.ps1');?>
</body>
</html>

it does not do anything.  My script is listed below


Set-StrictMode -Version 2.0

$Site="Default Web Site"

Write-Host ""
Write-Host "                                                            " -BackgroundColor DarkCyan
Write-Host "            IIS Setup Script                                " -BackgroundColor DarkCyan
Write-Host "       Create Virtual Directories                           " -BackgroundColor DarkCyan
Write-Host "                                                            " -BackgroundColor DarkCyan
Write-Host ""
 
Import-Module WebAdministration -ErrorAction SilentlyContinue
 
if (dir IIS:\Sites\$Site) {Write-Host "Checking $Site Configuration"}else{
Write-Error "$Site does not exist, exiting"
exit
}
Write-Host ""
 
# Read Existing Values
#$rootpath = Get-ItemProperty ("IIS:\Sites\$Site") -name physicalPath
$rootpath = "C:\inetpub\wwwroot\datix"
echo $rootpath
$pool = Get-ItemProperty ("IIS:\Sites\$Site") -name applicationPool
 
# Create New App
$virdir = "NewApp"
 
if (dir IIS:\Sites\$Site\$virdir -ErrorAction SilentlyContinue)
{
 Write-Host "$Site/$virdir/ Virtual Directory is already configured"}
else
{
 # Create Physical Path if Not Present
 $apppath = Join-Path $rootpath $virdir
 $copypath = "c:\copy\*.*"
 echo $apppath
 if (!(Test-Path $apppath))
 { New-Item -Path $apppath -ItemType Directory 
   echo $apppath
   Copy-Item $copypath $apppath }
 Write-Host "$Site/$virdir/ Virtual Directory is NOT configured, creating..."
 
 # Create new IIS Application
 New-Item IIS:\Sites\$Site\$virdir -physicalPath "$rootpath\$virdir" -type Application | Out-Null
 
 # Set Application Pool
 Set-ItemProperty IIS:\Sites\$Site\$virdir -name applicationPool -value $pool
 
 # Create Images Virtual Directory
 New-Item IIS:\Sites\$Site\$virdir\images -physicalPath "$rootpath\images" -type VirtualDirectory
 
 Write-Host "Created $Site/$virdir/ Virtual Directory"
}


SUMEET

Renaming multiple different version of Windows computer remotely ?

$
0
0

Hi All,

Can anyone please assist me what's the pwoershell command to rename Windows computername remotely or locally ?
I need to rename and standardize Windows 10, 8.1 and 7 computername in the domain.

The script below that I use:

Rename-Computer -ComputerName WKS-W10-01 -NewName TEST01 -DomainCredential Domain\Administrator

Doesn't seems to be working with the error message as follows:

Rename-Computer : Cannot establish the WMI connection to the computer 'WKS-W10-01' with the following error message: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).


/* Server Support Specialist */

Combining Powershell script to display current logged on username and computer model ?

$
0
0

People,

I've got the folowing script below

Get-ADComputer -Properties OperatingSystem, OperatingSystemVersion  -Filter { Enabled -eq $True -and OperatingSystem -like "*Windows 10*"} -SearchBase "OU=Main Office Computers,DC=company,DC=com" |
Where-Object { Test-Connection $_.Name -Count 1 -Quiet } |
Where-Object { $_.DistinguishedName -notlike "*OU=Decommissioned Computers,OU=Main Office Computers,DC=company,DC=com" } |
Select Name, OperatingSystem, OperatingSystemVersion |
Export-Csv C:\temp\Win10.csv -NoTypeInformation -UseCulture

which exports the list / result as VSV with Name, OperatingSystemand OperatingSystemVersion column.

How can I add two more column to the script above from the command line below to get the Computer model and also the currrent logon name ?

Getting The computer model name

     Get-WmiObject -Class Win32_ComputerSystem

Getting The computer logged on username

     Get-WmiObject -Class Win32_ComputerSystem -ComputerName . -Property UserName

Thanks in advance.


/* Server Support Specialist */

Run site collection health checks in SharePoint 2013

$
0
0

I just run the following commands in the powershell to check the sharepoint sitecollection health check up,im getting below error

,Test

Test-SPSite -Identity http://siteurl/sites/OTC[-Rule cd839b0d-9707-4950-8fac-f306cb920f6c]

Repair-SPSite -Identity http://siteurl/sites/OTC [-Rule cd839b0d-9707-4950-8fac-f306cb920f6c]

below error:

Repair-SPSite : A positional parameter cannot be found that accepts argument '[-Rule'.
At line:1 char:1
+ Repair-SPSite -Identity http://siteurl/sites/OTC[-Ru ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Repair-SPSite], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.SharePoint.PowerShell.SPCmdletRepairSite

But without rule Below commands executed suceesfully,

Test-SPSite -Identity http://siteurl/sites/OTC

Anyone having idea,what is that issue?

reference:https://technet.microsoft.com/en-us/library/jj219720.aspx

Swapping Proxy Primary Secondary Email Addresses

$
0
0

Hi,

We have onpremise Windows 2012 R2 AD Domain, AD Connect/Sync, ADFS and O365 Subscription too.

All Users Mailboxes have been migrated to O365 from an Onpremise Exchange 2010 we had earlier. Exchange server no longer exists onpremise.

Each user has multiple SMTP email addresses for e.g. user@xyz.com & user@abc.org.

@xyz.com address is set as primary SMTP.

Since we cannot make change to users object on O365 we have to make the change in onpremise AD.

We need to swap the current primary SMTP address to secondary & the secondary to primary using AD Powershell for multiple users.

Could anyone help with a AD Powershell script that would allow us to do so.



AD query not returning expected result using -eq

$
0
0

Hi folks,

today I ran some AD queries and encountered an issue I don't understand. Actually to me it looks like a bug. In a first query I wanted to retrieve all enabled AD user accounts and in a second one all disabled ones.

get-aduser -filter * -properties cn,enabled | ?{$_.enabled -eq "True"}| select cn,enabled

returns all enabled accounts as expected

however

get-aduser -filter * -properties cn,enabled | ?{$_.enabled -eq "False"}| select cn,enabled

also returns all enabled accounts!

When I run 

get-aduser -filter * -properties cn,enabled | ?{$_.enabled -ne "True"}| select cn,enabled

I get all accounts where enabled property is set to False.

Can someone explain this? Is this expected? Or a bug?

Thanks in advance
Daniel

Question on comparing lists

$
0
0

Working on some drive cleanup and need some extra eyes to help me with the logic.

I have a list that is basically the result of Get-AdUser | Select DistiguishedName - I loop through this list and do invoke get to locate the users TsHomeDirectory:

 $ADList =  Get-ADUser  -filter * | select DistinguishedName

     foreach ($User in $AdList) {  

  $DN = $User.DistinguishedName

  $ADSI = [ADSI]"LDAP://$($DN)"
  $Paths += $ADSI .psbase.invokeget("TerminalServicesHomeDirectory")

}

This gets me all the home directories as expected in a list called $Paths. Now I am trying to compare that list to see if it contains any entry found on another list but cant seem to get it working. The other list would be an imported CSV like this:

DirectoriesToDelete 

jimnasium14

jimnasium15

etc. etc etc.

I'm trying to get output of any home directory that ISNT found on that second list. So the AD list would have an entry that says "\\fileshare\users\jimnasium14" and I want that to output saying it wasnt found. 

Any Ideas?





message is truncated

$
0
0

Hello,

Powwershell version 2

This is the code:

Get-EventLog -computername Computername -LogName application -EntryType error -After (Get-Date).adddays(-1) -Source "MSExchange Availability" | Where-Object {$_.EventID -eq 4002 -and $_.message -like "*closed*"} | select -Property message,Source,time*,MachineName | export-csv c:\filename.csv -notypeinformation

It gives me what I want except for the message. The message gets truncated . I'm missing 15 characters and I'll be good to go.

does anyone know how to increase the buffer size of the output in message? I would like the full https address and that is it.

WARNING: 5 columns do not fit into the display and were removed.

Message
-------

Process 10764: ProxyWebRequest CrossForest from SID to https://chdc-exca...

appreciate your help

Tacobell



Office 365 Archive File (PST) Import PowerShell Commands?

$
0
0

Good morning!

I have been using the AzCopy.exe tool to upload PST files into an Azure Storage blob and then, using the Import tools in the Office 365 admin console, import the emails into the user's online archive. 

Currently, I have automated the AzCopy.exe steps with PowerShell but the 'import into online archive' step has to be done manually. I would like to automate the entire process.

I would also like the ability to check the status of imports via PowerShell if possible as I have an import stuck at 72% with no way to cancel it.

Is anyone aware of any new cmdlets that have been included in the O365 PowerShell remote session modules that can be used to keep track and automate these tools?

Thanks!

Matt

Trying to compare two multi-dimensional arrays containing (expected) the same files, using LastWriteTime; source files always appears newer

$
0
0

I'm working on a function that I'll be able to incorporate into my PowerShell distribution script that checks a group of local "master" files against targeted "remote" files across several servers. The problem I'm having is that when comparing the LastWriteTime of the master files to the LastWriteTime of the remote files, the master files always show as the newest, even after I've overwritten (or deleted and replaced) the remote files with the "newer" copy of the master files.

My objective here is to compare metadata of the master files with the metadata of the remote files to figure out what's missing and what's newer, then copy/overwrite the remote files as necessary. As stated above, the master files have a LastWriteTime that's greater than the remote "target" files at all times, meaning that every time this is run the files are copied over, regardless if I've edited them or not. I want them copied only if the LastWriteTime of the master files is factually greater than that of the remote "target" files.

Here's the function I'm working with. The issues exists in the first IF check (If(Test-Path $target)), within the $NewerFiles variable.

Keep in mind the following notes...

  1. I've been working on this issue with a nice redditor for the past few days, but we're making slow progress, which I why I'm posting here as well.  Here's a link to the post containing everything we've tried over the past few days.
  2. I know there are a handful of other logic issues in here, so try not to focus on those (namely in the finally loop if the $RemoteFiles variable wasn't used); this isn't complete yet and I plan on addressing those as soon as I hammer out this LastWriteTime comparison.

Function:

function Dist-UpdateModules($ComputerName)
{
    try
    {
        $isSuccess = $false
        [xml]$Configurations = Get-Content "$($PSScriptRoot)\config_UpdateModules.xml"
        $Modules = $Configurations.Settings.Modules.ChildNodes

        foreach($module in $Modules)
        {
            $target = "$($Configurations.Settings.Target.path.Replace('C:',"\\$ComputerName\C$"))\$($module.id)"
            $LocalFiles = Get-ChildItem -Path $module.source | Sort-Object LastWriteTime

            if(Test-Path $target)
            {
                $RemoteFiles = Get-ChildItem $target | Sort-Object LastWriteTime
                $MissingFiles = $LocalFiles | ? {$RemoteFiles.Name -notcontains $_.Name} | Sort-Object LastWriteTime
                $NewerFiles = $LocalFiles | ? {$RemoteFiles.LastWriteTime.TimeOfDay -lt $_.LastWriteTime.TimeOfDay} | Sort-Object LastWriteTime

                if($MissingFiles)
                {
                    Copy-Item $MissingFiles.FullName -Destination $target
                }

                if($NewerFiles)
                {
                    Copy-Item $NewerFiles.FullName -Destination $target -Force
                }
            }
            else
            {
                New-Item -ItemType directory -Path $target
                Copy-Item $LocalFiles.FullName -Destination $target -Recurse -Force
            }
        }
    }
    catch
    {
        $err = $Error
    }
    finally
    {
        if([string]::IsNullOrEmpty($err))
        {
            if(!($LocalFiles | ? {$RemoteFiles.Name -notcontains $_.Name}))
            {
                if(!($LocalFiles | ? {$RemoteFiles.LastWriteTime -lt $_.LastWriteTime}))
                {
                    $isSuccess = $true
                }
            }
        }
    }

    return $isSuccess

XML:

<?xml version="1.0"?><Settings><Logging><EventSource>BIS.Powershell.Management.Distribution</EventSource><EventLogName>BIS-Applications</EventLogName></Logging><Target path='C:\Windows\System32\WindowsPowerShell\v1.0\Modules'/><Modules><Module id='BIS.Powershell.Module.Processing' source='D:\Development\Sandbox\Distribution\Source\BIS.Powershell.Module.Processing\' /><Module id='BIS.Powershell.Module.Monitoring' source='D:\Development\Sandbox\Distribution\Source\BIS.Powershell.Module.Monitoring\' /></Modules></Settings>

Viewing all 21975 articles
Browse latest View live


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