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

Update user's AD properties according to CSV given by ADP?

$
0
0

Hello,

I have to write a PS script to update AD users' managers, job titles and description based on the employeeID value because that is the only unique value from ADP data.

The CSV comes in this format. "File Number" is employeeID, employee First name/Last Name, Job Title, Reports to Email is their manager's email
























This is basically my script

Import-Module ActiveDirectory
$import = import-csv "$env:C:\ADPADupdate\HRData.csv"

foreach ($user in $import) {
    $manager = get-aduser -filter "emailaddress -eq '$($user.'Reports to Email')'"
    get-aduser -Filter "enabled -eq 'true' -and employeeID -eq '$($user.'File Number')'" -Properties employeeID |
    set-aduser -Manager $manager.DistinguishedName -description $user.'Job Title Description' -title $user.'Job Title Description'
}

The PROBLEM is that. The data in the CSV are not perfect, some miss employeeID, some miss manager's email. When I clean out the incomplete rows, basically just delet them, then my script works perfectly. If I leave the incomplete rows in there, the script will error out and I get unexpected results, like employees get wrong job titles or managers.

How can I use the IF else statement to skip the incomplete rows? For example, tell it to update if the employeeID matches the one in CSV, SKIP if employeeID or manager fields are empty??

Thanks so much in advance for your feedback!

























PowerShell Outlook Advanced Search Complete Event

$
0
0

Hello !

In a PowerShell script, I want to do some research in Windows local mails.

I have the following script : 

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null

$outlook = New-Object -com Outlook.Application;

$namespace = $outlook.GetNamespace("MAPI");

Function Get-OutlookInbox {

    $accountsList = $namespace.Folders

    $query = "Test"
    $filter = "urn:schemas:httpmail:subject LIKE '"+$query+"'"

    foreach($account in $accountsList) {
        write-host "SEARCHING IN MAILBOX : " $account.name

        $scope = $account.FolderPath

        $search = $outlook.AdvancedSearch("'$scope'", $filter, $True)

        Start-Sleep -Seconds 10

        foreach ($result in $search.Results) {
            $result.Subject
            $result.ReceivedTime
            $result.SenderName
        }

    }

$inbox = Get-OutlookInbox

$inbox


It works well thanks to the `Start-Sleep -Seconds 10` as the `$outlook.AdvancedSearch` function is asynchronous, but I don't really like this way of developing, a bit crappy.

I would like to use AdvancedSearchComplete Event but I don't know how to use it in PowerShell, and the documentation is for VBA. I'm not very good at PowerShell development, I don't find a way to do it.

Thanks for your help !


Powershell - Downloading excel file from Online sharepoint portal

$
0
0

Hi Experts,

 I am having trouble downloading excel file from online sharepoint portal using power shell. Could you please point me to the right directions. Here is the error. Thank you. 

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

Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (403) Forbidden."
+ $WebClient.DownloadFile($SharePoint, $Path)

   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
   + FullyQualifiedErrorId : WebException
$SharePoint = "https://MyCompanyOnlineSharepointPortal/SomeExcelFile.xlsx"
$Path = "c:\Temp\SomeExcelFile.xlsx"

#User Information'

$username = "Myusername@Company"
$password = "Mypassword"

#Download Files

$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($userName, $password)

$WebClient.DownloadFile($SharePoint, $Path)

Why $error[0].tostring().contains not working correctly?

$
0
0
I have the following try-catch statement to process a DB table/dimension. For some reason, if i turn off the (MSSQLSERVER) service on the server, the 1st if statement to capture the exception that

Ensure that the server is running

is never touched and instead it goes to the second if condition and writes to host

Error Processing dimension: A connection cannot be made. Ensure that the server is running.

        try {Invoke-ProcessTable-DatabaseName"$DB"-Server"$server"-RefreshType"Full"-TableName"sometable"> $null

                write-host "Processing completed!"}
        catch{if($error[0].tostring().contains("Ensure that the server is running")){
                    write-host "`r`nProcessing failed!`r`n(MSSQLSERVER) service is not running on $server!"#$exit = 1}
                elseif ($error[0]){Write-Host"Error Processing dimension: $($error[0])"}}

The exception message if the service is not running on the server is as follows:

A connection cannot be made. Ensure that the server is running.

so what is wrong with $error[0].tostring().contains("Ensure that the server is running")

it should be outputting this:

Processing failed!(MSSQLSERVER) service is not running on server!

[Powershell] - Copy table to another SQL Instance (add column)

$
0
0

Hi, 

i'm looking for a way to copy data from one table to another for auditing purposes. 
In fact i'd would like to copy the entire table to another table and add the date of "copy" for each record in a new column. 

Source: SQLSERVER1\SQLInstance1 ; DB1 ; Table1
Target: SQLSERVER2\SQLInstance2; DB2; Table2

where Target is a drop of the source Table + DateReference column. 

Would this be possible through Powershell so I don't have to ask our DBA's to create a SSIS package for this? 

kr

Sam

Replacing generated Image file instead of creating a new one at every run

$
0
0

HI,

We found this code at this location. https://github.com/octan3/img-clipboard-dump. We are beginner in Powershell and we are having a difficult time trying to understand the code.

Add-Type -Assembly PresentationCore
$img = [Windows.Clipboard]::GetImage()
if ($img -eq $null) {
    Write-Host "Clipboard contains no image."
    Exit
}

$file = "{0}\clipboard-{1}.jpg" -f [Environment]::GetFolderPath('MyPictures'),((Get-Date -f s) -replace '[-T:]','')
Write-Host ("`n Found picture. {0}x{1} pixel. Saving to {2}`n" -f $img.PixelWidth, $img.PixelHeight, $file)

$stream = [IO.File]::Open($file, "OpenOrCreate")
$encoder = New-Object Windows.Media.Imaging.JpegBitmapEncoder
$encoder.QualityLevel = 90
$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($img))
$encoder.Save($stream)
$stream.Dispose()& explorer.exe /select,$file

We would need to get this modified so that the files gets overwritten at every run instead of creating a new one at each run. How can we edit the script so that it would save to a specific folder with a file name provided that the path and the file name has been hard-coded inside the script. Please assist. 

For example : Say, we need the file to be saved into this path : --> C:\Images and the filename should be --> Image01.jpg resulting in this --> C:\Images\Image01.jpg

How to download attachment from Office 365 Shared Mailbox

$
0
0

I am using below script from technet gallery for downloading an attachment from Office 365 Sharedmailbox. However I am getting following error

https://gallery.technet.microsoft.com/office/O365-Email-Attachments-to-6a45e84c#content

ERROR:

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

At line:21 char:13
+ $messages = Invoke-RestMethod $messageQuery -Credential $cred
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebReq 
   uest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Comm 
   ands.InvokeRestMethodCommand



Thanks, Samer Please take a moment to "Vote as Helpful" and/or "Mark as Answer" where applicable. This helps the community, keeps the forums tidy, and recognizes useful contributions. Thanks!

powershell to csv getting columns

$
0
0

Hi all,

For my internship I need to write a script. My script is: Get-ADUser -Filter * -Properties * | select Name,whenCreated, Description, whenchanged, Lastlogondate, LastBadPasswordAttempt, BadlogonCount, LockedOut, Enabled |export-csv c:\informatie-user-csv.csv.

how can I get all these properties in a different columns in my csv-file?

Greetings

Sam


Changing PS language supresses errors

$
0
0

Hi all.

I would like to change the language in this script to Norwegian, and believe I have done it successfully, however, this change has suppressed error messages that is output. The same issue is present with Using-Culture en-US

Any ideas on why this happens and how to fix it if possible?

My method of testing what the output error is, is by creating a new VPN connection with the same name as a existing one. Without the Using-Culture function, errors are shown. With it, the errors are supressed and the script only shows the custom message (Which is shown when a error is present regardless).

>The script adds a VPN connection based on Cisco Meraki default connections.

Below is a example that produces errors as normal:

try {
        $Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
        $password = Read-Host -AsSecureString "Please enter your Pre-shared Key"

        # Default Cisco Meraki parameters
        $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
        Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force

        # Gives popup with information on next steps
        $wshell = New-Object -ComObject WScript.Shell
        $wshell.Popup("VPN-profile for $Name has been created.`nYou may now use this connection.`nUsername and password is required on first time sign on.`nSupport: contact | company", 0, "Completed") | Out-Null
    } catch {
        # Reports error and supresses "Completed"
        Write-Error $_.Exception.ToString()
        Read-Host -Prompt "The above error occurred, please try again. If the issue persists, please contact support.`nSupport: contact | company`nPlease press Enter to exit"
    }

See below for the full script, in which the language change is implemented (I belive). 

Function Using-Culture([Globalization.CultureInfo]$culture, [ScriptBlock]$script) {
    $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
    trap {
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
    }
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
    $ExecutionContext.InvokeCommand.InvokeScript($script)
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}

Using-Culture nb-NO {
    try {
        $Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
        $password = Read-Host -AsSecureString "Please enter your Pre-shared Key"

        # Default Cisco Meraki parameters
        $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
        Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force

        # Gives popup with information on next steps
        $wshell = New-Object -ComObject WScript.Shell
        $wshell.Popup("VPN-profile for $Name has been created.`nYou may now use this connection.`nUsername and password is required on first time sign on.`nSupport: contact | company", 0, "Completed") | Out-Null
    } catch {
        # Reports error and supresses "Completed"
        Write-Error $_.Exception.ToString()
        Read-Host -Prompt "The above error occurred, please try again. If the issue persists, please contact support.`nSupport: contact | company`nPlease press Enter to exit"
    }
}

I have kept all the custom text that a user will see in English here, to hopefully help you assist me better.

Thanks in advance!

Print Server

$
0
0

I am migrating one of my print servers. I want to create a powershell script to point the clients/users to the new print server.

Any inputs on the logic I can use to accomplish this and how can I accomplish this for one client/user using powershell? If I have that I can then create a loop to do it for all clients/users?

Roles Based Access and PowerShell

$
0
0

I would like to compile a spreadsheet with the following data sources. 

Account Tab - User Logon Name

Organization Tab - Title

Member Of Tab - <All Group Memberships>

How would I use PowerShell to pull the member of information of a position title if I were to provide a user logon name?  I would also want this to export to a spreadsheet.

The only other method I'm using currently in-place of this is to run a vbscript to pull the member of data after providing the script a user logon name.  This then creates a txt document to which I manually pull the information and insert to spreadsheet.

Thanks for the support all!


Trying to run a bat file as admin

$
0
0

This script is to check the name of the PC and depending on what site it is located it, it will run the .bat file which has registry settings that contain that site's autologin info. The script executes with no errors however, it's not actually modifying the registry settings. I've used all these .bat files in the past and know they work but I also know they have to be ran as an admin in order to work. 

Can anyone help me understand where I need to modify?

###Variables
$hostname = hostname
$AMIK = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\amiklogin.bat"
$CRIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\criclogin.bat"
$FJIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ftjesselogin.bat"
$HFDH = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hfdhlogin.bat"
$HDSV = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hfsvloging.bat"
$HINJ = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hinjlogin.bat"
$ICWR = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ICWRlogin.bat"
$LTR = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ltrlogin.bat"
$MSBA = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSBAlogin.bat"
$MSBW = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSBWlogin.bat"
$MSLF = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSLFlogin.bat"
$MSTM = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSTMlogin.bat"
$NHI = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\NHIlogin.bat"
$ODCA = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ATHlogin.bat"
$ODCK = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCklogin.bat"
$ODCH = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCHlogin.bat"
$ODCN = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCNlogin.bat"
$SMIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\SMIClogin.bat"

###Identify Workstation Location

If ($hostname -like 'IT-*') { $Software = $BSC

  ElseIf ($hostname -like 'AMIK-*') { $Software = $AMIK
}
  ElseIf ($hostname -like 'ATH-*') { $Software = $ODCA

  ElseIf ($hostname -like 'CRIC-*') { $Software = $CRIC
}
  ElseIf ($hostname -like 'CRIN-*') { $Software = $CRIC
}
  ElseIf ($hostname -like 'ODCH-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'DHCH-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'ODCM-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'ODCK-*') { $Software = $ODCK
}
  ElseIf ($hostname -like 'FJIC-*') { $Software = $FJIC
}
  ElseIf ($hostname -like 'ICWR-*') { $Software = $ICWR
}
  ElseIf ($hostname -like 'ODCN-*') { $Software = $ODCN
}
  ElseIf ($hostname -like 'LTR-*') { $Software = $LTR
}
  ElseIf ($hostname -like 'HFDH-*') { $Software = $HFDH
}
  ElseIf ($hostname -like 'HFSV-*') { $Software = $HFSV
}
  ElseIf ($hostname -like 'HINJ-*') { $Software = $HINJ
}
  ElseIf ($hostname -like 'MSBA-*') { $Software = $MSBA
}
  ElseIf ($hostname -like 'MSBW-*') { $Software = $MSBW
}
  ElseIf ($hostname -like 'MSLF-*') { $Software = $MSLF
}
   ElseIf ($hostname -like 'MSTM-*') { $Software = $MSTM
}
  ElseIf ($hostname -like 'NHI-*') { $Software = $NHI
}
  ElseIf ($hostname -like 'RRC-*') { $Software = $RRC
}
  ElseIf ($hostname -like 'SMIC-*') { $Software = $SMIC
}


write-output $hostname
write-output $Software

powershell -command "start-process cmd -argumentlist '/c %CD% && $software' -Verb runas" 

aasdfsadf

Bat file to be ran as admin in powershell

$
0
0

I need help making my powershell command to execute the .bat file in CMD as an admin. The PS script determines the hostname of the PC and then maps a UNC path to the correct .bat file thats needed for that site.

Example: PS script determines that a computer's hostname his HINJ-%SerialNumber% so the UNC path for HINJ is mapped:  "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hinjlogin.bat"

HINJlogin.bat contains the following add registry keys to add the AD autologin account for HINJ computers. 

reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /t REG_SZ /d 1 /f

reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName /t REG_SZ /d HINJkiosk /f

reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName /t REG_SZ /d <MyDomain.com> /f

reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d <Account Password /f

The .bat file works if you right-click and run as admin. However, when ran from PS, it does not run the .bat file as admin so the registry keys are not changed properly. The last line of the PS script is supposed to run variable $Software as admin.

Below is the full PS:

###Variables
$hostname = hostname
$AMIK = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\amiklogin.bat"
$CRIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\criclogin.bat"
$FJIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ftjesselogin.bat"
$HFDH = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hfdhlogin.bat"
$HDSV = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hfsvloging.bat"
$HINJ = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\hinjlogin.bat"
$ICWR = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ICWRlogin.bat"
$LTR = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ltrlogin.bat"
$MSBA = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSBAlogin.bat"
$MSBW = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSBWlogin.bat"
$MSLF = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSLFlogin.bat"
$MSTM = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\MSTMlogin.bat"
$NHI = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\NHIlogin.bat"
$ODCA = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ATHlogin.bat"
$ODCK = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCklogin.bat"
$ODCH = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCHlogin.bat"
$ODCN = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\ODCNlogin.bat"
$SMIC = "\\mydomain.com\mdt\Deployments\Production\Applications\Imprivata\Autologin\SMIClogin.bat"

###Identify Workstation Location

If ($hostname -like 'IT-*') { $Software = $BSC
} 
  ElseIf ($hostname -like 'AMIK-*') { $Software = $AMIK
}
  ElseIf ($hostname -like 'ATH-*') { $Software = $ODCA
} 
  ElseIf ($hostname -like 'CRIC-*') { $Software = $CRIC
}
  ElseIf ($hostname -like 'CRIN-*') { $Software = $CRIC
}
  ElseIf ($hostname -like 'ODCH-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'DHCH-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'ODCM-*') { $Software = $ODCH
}
  ElseIf ($hostname -like 'ODCK-*') { $Software = $ODCK
}
  ElseIf ($hostname -like 'FJIC-*') { $Software = $FJIC
}
  ElseIf ($hostname -like 'ICWR-*') { $Software = $ICWR
}
  ElseIf ($hostname -like 'ODCN-*') { $Software = $ODCN
}
  ElseIf ($hostname -like 'LTR-*') { $Software = $LTR
}
  ElseIf ($hostname -like 'HFDH-*') { $Software = $HFDH
}
  ElseIf ($hostname -like 'HFSV-*') { $Software = $HFSV
}
  ElseIf ($hostname -like 'HINJ-*') { $Software = $HINJ
}
  ElseIf ($hostname -like 'MSBA-*') { $Software = $MSBA
}
  ElseIf ($hostname -like 'MSBW-*') { $Software = $MSBW
}
  ElseIf ($hostname -like 'MSLF-*') { $Software = $MSLF
}
   ElseIf ($hostname -like 'MSTM-*') { $Software = $MSTM
}
  ElseIf ($hostname -like 'NHI-*') { $Software = $NHI
}
  ElseIf ($hostname -like 'RRC-*') { $Software = $RRC
}
  ElseIf ($hostname -like 'SMIC-*') { $Software = $SMIC
}


write-output $hostname
write-output $Software

powershell -command "start-process cmd -argumentlist '/c %CD% && $software' -Verb runas" 



break out by inv and line

$
0
0

 I bring in 2 daily files where I want to compare down to an invoice\line\day any record where a measure is different that
its source counterpart.

header
inv|line|day|qtyshipped|margin|source

Data:

2819|1|1|89|43.50|prd
2819|1|1|89|42.50|zrg

2820|1|1|89|43.50|prd
2820|1|1|85|43.50|zrg

 In this example I want to see an output that shows:

The key(inv\line\day) and then the measures that doesn't match 

 2819|1|1|1    --> display the record because margin is different between the sources.
 2819|1|1|4    --> display the record because qtyshipped is different between the sources.

 This script does it at a higher level Invoice Count and just lists the overall summed values. I need it at a more granular
level.

Get-ChildItem -Path 'C:\margin_data\*.csv' | # Get each file
    ForEach-Object -Process {
        Import-Csv -Path $PSItem.FullName -Delimiter '|' # Import data
    } | 
    Group-Object -Property Source | 
    Select-Object -Unique -Property Name, @{
        Label = "Sum";
        Expression = {
            # Sum all the counts for each domain
            ($PSItem.group | Measure-Object -Property Source -sum).Count
            ($PSItem.group | Measure-Object -Property QtySHipped -sum).Sum
            ($PSItem.group | Measure-Object -Property Margin -sum).Sum
        }
    } |
    Sort-Object -Property Sum -Descending | Export-Csv -Path 'C:\margin_data\margin_data_compare.csv' -NoTypeInformation

Thanks.


Add quote in directory list in output file

$
0
0

I am executing this script to have a list of all directories and sub-directories located in the appdata of a user profile.  My script works like I want but, because some directories, many directories have space in name, I would to add quote at the beginning of each output line and a quote at the end of each line.

Now I am getting:

C:\users\xyz\appdata\dir 1

C:\users\xyz\appdata\dir 2

C:\users\xyz\appdata\dir 3

I would like to have:

“C:\users\xyz\appdata\dir 1”

“C:\users\xyz\appdata\dir 2”

“C:\users\xyz\appdata\dir 3”

Here my script:

$ExcludeDirList=Get-ChildItem-Path“c:\users\xyz\appdata”-Recurse-Directory-Force-ErrorActionSilentlyContinue |  Select-Object -expandproperty FullName

Out-File-FilePath./list.txt-Append-InputObject$ExcludeDirList

Need a script to delete all subfolders except ones with a certain name

$
0
0

Greetings,

I have a network directory \\network\folder that contains multiple directories with subdirectories, with the floowing hierarchy:

Root

    Folder A

        Data

        To Discard 1

         ....

         To Discard 2

    Folder B

        To Discard 1

         ....

         To Discard 2

....

    Folder N

        Data

        To Discard 1

         ....

         To Discard 2

Basically, I want in every level 1 directory delete all the To Discard folders with files, leaving only the Data folders.

Thanks!

 

Input Variable

$
0
0

I’ve got an input variable called DatabaseInput.

I would like to get all the subfolders from a folder location and use a substring function to remove the datestamp from the folder and match it to my input variable (DatabaseInput)

Example of the folder structure: Database1_20190221171833

I would like to remove the datestamp from the folder., however my code is bombing out. Please help!

Code below:

#Get all child items of the root backup folder
$BackupMounts = Get-ChildItem -Force $RestorePath | Where-Object { ($.Name -like “B1”) -or ($.Name -like “B2”)}

ForEach ($backupMount in $BackupMounts) {
(’------backupMount: ’ + $backupMount) | Out-File $SQLOutputFile -append
$RestorePath = “\xxxx\Backups” + $backupMount
(’------Restore Path: ’ + $RestorePath) | Out-File $SQLOutputFile -append

$databaseFolders =Get-ChildItem -Force $RestorePath"\Backups" | Where-Object { ($.Name -like “Database1*”) -or ($.Name -like “Database2*”) -or ($.Name -like “Database3*”) -or ($.Name -like “Database4*”) -or ($.Name -like “Database5*”) -or ($.Name -like “Database6*”) -or ($.Name -like “Database7*”) -or ($.Name -like “Database8*”) -or ($.Name -like “Database9*”)} | % {$.Name} | Sort -descending

#$databasefolders = Get-ChildItem -Force $RestorePath"\Backups" | Where-Object {($.Name -like $databasefolders.substring(0,($databasefolders.length -15)) -eq $DatabaseInput)} | % {$.Name} | Sort -descending

Import-Excel - Export Columns

$
0
0

Hello, 

I am using Import-Excel to import a spreadsheet into PowerShell. I want to export specific columns to a separate sheet in the same spreadsheet. I know this is likely a simple task, but I'm having trouble finding examples. Any information is appreciated! 

- Matt

Powershell started from Task Scheduler generates EventID 1530

$
0
0

I have a task scheduler setup to run a powershell at startup using a service account.  The powershell itself starts a second powershell which monitors a group of folders continuously and upon seeing a certain condition starts a third powershell.  The first and third powershells close after executing their tasks.  A period of time (~5 minute) after running the task scheduler task the Event viewer reports an EventID 1530 warning and the monitoring (2nd) powershell looses the ability to start the third powershell (it's unable to get a PID).  The problem only exists when using task manager to start the powershell, starting the powershell from a command window running as the service account does not have the problem.

So 1) Why is my powershell accessing registry keys to begin with, nothing in my script is explicitly doing it.  2) How can I automate the startup of the powershell so that it doesn't create EventID 1530.

Viewing all 21975 articles
Browse latest View live


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