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

change the root password for more than 100 servers using powershell

$
0
0

hi

i need to change the root password  for more than 200 servers without login using powershell script ,where server name are given in excel sheet. can any help me


Remove a caracter

$
0
0

Hello,

I have a dilemma and i would like to know if you can put me on the right track.

by questioning the active directory on the members of the group.


 Get-ADGroupMember -identity "ZRPI.ADMINSERVEURS.BDD" -recursive | Get-ADUser -Properties department| select name

PS C:\windows\system32\windowspowershell\v1.0> Get-ADGroupMember -identity "ZRPI.ADMINSERVEURS.BDD" -recursive | Get-ADUser -Properties department| select name

name    
----    
MJ604328
MJ488840
MP522162
MU150917
MP523812
MU093574
MP509038
ME511502
ME479096
ME409608
ME515183
ME521580
ME525715
ME545280


i'm looking for everything to remove the first character from each account

exemple MJ604328 = J604328

PS C:\windows\system32\windowspowershell\v1.0> Get-ADGroupMember -identity "ZRPI.ADMINSERVEURS.BDD" -recursive | Get-ADUser -Properties department| select name | Get-Member


   TypeName : Selected.Microsoft.ActiveDirectory.Management.ADUser

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
name        NoteProperty string name=MJ604328        

but, i don't know how to do it

Do you have the means to direct me on the track to take ? 


Store registry value output in a variable

$
0
0

Hello! i have been working on script to get the value of a remote registry key. I have tried alot of diffrent versions from technet and stuff i googled and found a version that works for me:

     

$ErrorActionPreference = "SilentlyContinue"

$key = 'Software\MyCompany\OurSoftware'
$valuename = 'Computer Type'
$computers = Get-Content C:\dev\Data\Computers2.csv
$serviceRunning = [System.ServiceProcess.ServiceControllerStatus]::Running
$serviceDisabled = [System.ServiceProcess.ServiceStartMode]::Disabled

foreach ($computer in $computers) {
   $svc = Get-Service -Name RemoteRegistry -ComputerName $computer
    if ( $svc.StartType -eq $serviceDisabled ) {
        $svc | Set-Service -StartupType Manual
    }
    if ( $svc.Status -ne $serviceRunning ) {
        $svc| Start-Service
    }

$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
$regkey = $reg.opensubkey($key)
$regkey.getvalue($valuename)

    $svc | Stop-Service
    $svc | Set-Service -StartupType Disabled
}

However, is there a way for me to store the output in a variable? I have changed the error preference to silently continue since not all computers are online, i will sort that out with a test connection loop when i get this to work.

Script to move in-game character

$
0
0

Hi, i'm pretty new to coding and I am trying to make a basic script that moves my character in a game application so that I dont get offline kicked from server for inactivity.

So what I tried was to make the "w" key (move forward in game) to press automatically each 3rd second. With the following code I got the "w" key to press each 3 seconds (tested in notepad) but it doesnt react at all in game. Any suggestions?

param($minutes = 120)

$myShell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 3
  $myShell.sendkeys("w")
}

 

How to configure cacherefreshplans and update the schedule using API?

$
0
0

We have 100's of reports that were falling behind in refresh schedule, and Microsoft confirmed with us that that is the way it works: refreshes are queued as FIFO, so the more refresh plans on the server, the more it will take time for reports to get their turn to refresh, regardless of the schedule expectation.

After discussions, we have decided to establish refresh schedule governance, so users wont be creating the schedules, we will. But there are hundreds of schedules in place (1 for each report) and it will take forever to update them manually one by one.

How can we update the schedules, to say perform a refresh at 10am or 2 pm daily?

i was able to drill down to the cacherefreshplan information but i am unsure how to "update it" with new values. On swagger, i am seeing PUT, but not sure if that is the right method...

    $refreshplan = Invoke-RestMethod -UseDefaultCredentials <# -Credential $creds #> -uri $($baseURI + "api/v2.0/PowerBIReports(path='" + "/Prototypes/report 1" + "')/CacheRefreshP
lans")

$refreshplan.value.ScheduleDescription

At 2:00 AM every day, starting 9/5/2019

$refreshplan.value.Schedule.Definition

StartDateTime             EndDate              EndDateSpecified Recurrence
-------------             -------              ---------------- ----------
2019-09-05T02:00:00-04:00 0001-01-01T00:00:00Z            False @{MinuteRecurrence=; DailyRecurrence=; WeeklyRecurrence=; MonthlyRecurrence=; MonthlyDOWRecurrence=}


$refreshplan.value.Schedule.Definition.StartDateTime

2019-09-05T02:00:00-04:00

Discrepancy between local execution and invoke-command

$
0
0

I have some scripts that are in a network share that is accessible to all computers on my network, that that location is guaranteed to be including in all of their PATH environments.

I have remote execution configured and enabled to allow the use of "invoke-command"  from anywhere to anywhere, but I must be missing something.

If I log on to one of the machines, open a powershell window, and invoke one of these scripts - it works just fine.

However, if I attempt to run the very same script, on the very same machine, via Invoke-Command -computername -script {<scriptname>}  (started via a powershell window on a different machine). I get back errors that seem to indicate that it can't find the script file.

"The term '<scriptname>' is not recognized as the name of a cmdlet, function, script file, or operable program."

I guarantee that  <scriptname> is present in the PATH for any/all users that logon to any computer in the network, and also if they connect to a machine via remote desktop.

There must be something "funky" going on with how the user environment, including PATH, is built for "remoted" commands via invoke-command that I'm unaware of, I just don't know what it is or what to do to correct it.

Help?

Thanks...

How to decrease memory usage in PowerShell Script?

$
0
0

Hi...

I have powershell script with infinite loop. I do some file processing, read file content, and monitoring.

I know that this code is not good enough, but I already try it. This code works. But the problem is, it consume a huge memory. I try to adjust it, but it still increasing by time. The longer it runs, the more memory consume.

Please give some advice. Thank you

do{
    # [system.gc]::Collect()
    [System.GC]::GetTotalMemory($true) | out-null
Function Check_Path_Report
{
    $Report_Path =  $Config_File.Automation_Config.Path.Report
    # $Report_Path
    $n = 0
    while (-not($Report_Path -eq ".\Resource\Report")) {
        Start-Sleep -s 3
        #Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        $n++
        Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        [xml]$Config_File = Get-Content -path ".\Resource\Agent_Config.xml"
        $Report_Path =  $Config_File.Automation_Config.Path.Report
        Write-Host "Attempt no $n"
    }
    Write-Host "Path found after $n attempts"
    Write-Host "Report_Path: $Report_Path"
    return $true
}
# ============================================#

Function REPORT
{
    if(Check_Path_Report)
    {
    Write-Host "Path is ready, Start Report"
    $Report_Path =  $Config_File.Automation_Config.Path.Report
    Write-Host "Report_Path: $Report_Path"
    if(Test-Path -Path  "$Report_Path\*")
    {
        Write-Host "Report_Path: $Report_Path"
        Write-Host "Remove Previous Folder"
        Remove-Item -Path "$Report_Path\*" -Exclude "*.xsl", "*.png" -Recurse -Force
    }
    Copy-Item -Path "$OpJob_Path\*" -Destination $Report_Path -Recurse -Container -Force   
    $mainFolder = "$Report_Path"

# Initialise file with header information
@"<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="Tool.xsl"?> <report><Type>AUTOGM</Type>`n"@ | Out-File "$mainFolder\BPSIMGAutomation.xml" -NoNewline -Force

# Loop over the folders
$FindFolder = Get-ChildItem -Directory $mainFolder
foreach ($folder in $FindFolder) {
    $que = Get-ChildItem -Name "$mainFolder\$folder" -Recurse -File -Include *.que |
           Measure-Object |
           ForEach-Object {$_.Count}
    $pro = Get-ChildItem -Name "$mainFolder\$folder" -Recurse -File -Include *.pro |
           Measure-Object |
           ForEach-Object {$_.Count}
    $don = Get-ChildItem -Name "$mainFolder\$folder" -Recurse -File -Include *.don |
           Measure-Object |
           ForEach-Object {$_.Count}
    $err = Get-ChildItem -Name "$mainFolder\$folder" -Recurse -File -Include *.err |
           Measure-Object |
           ForEach-Object {$_.Count}

# Append individual folder report to file
@"<BuildID>$folder</BuildID><que>$que</que><pro>$pro</pro><don>$don</don><err>$err</err>`n`n"@ | Out-File "$mainFolder\BPSIMGAutomation.xml" -NoNewline -Force -Append
}

# Append footer information to file
@"</report>"@ | Out-File "$mainFolder\BPSIMGAutomation.xml" -NoNewline -Force -Append
}
else{
    Write-Host "Report Path is not ready"
}

# #SSID REMOVE
if(Test-Path -Path "$OpJob_Path\*\SSID_LST_DON"){
$Path_SSID_DON = Get-ChildItem -Path "$OpJob_Path\*\SSID_LST_DON"
$Split = Split-Path -Path $Path_SSID_DON
$Split
$Split | ForEach-Object { 
    $file = Join-Path $_ 'SSID_LST'
    if (Test-Path $file) { Remove-Item $file }
  }
}
[System.GC]::GetTotalMemory($true) | out-null
}
# ============================================#

Function Job_Handling
{
    Write-Host "Start job handling"
    #check path odmic and agent
    $Modif_ODMIC = $Config_File.Automation_Config.Path.Modif_ODMIC
    $Modif_Agent = $Config_File.Automation_Config.Path.Modif_Agent
    If(!(Test-Path -Path $Modif_ODMIC))
    {
        Write-Host "Modif_ODMIC path NOT exist"
        pause
    }
    else{
        Write-Host "Modif_ODMIC path exist"
        #check modification.que file
        if(Test-Path -Path $Modif_ODMIC\*.que)
        {
            Write-Host "Modification.que exist"
            #copy .que file to Agent
            Copy-Item -Path $Modif_ODMIC\*.que -Destination $Modif_Agent -Force
            if(!(Test-Path -Path $Modif_Agent\*.que))
            {
                Write-Host "Copy file fail!"
                REPORT
            }
            else{
                Write-Host "Copy file succesfully!"
                #continue delete the job
                Get-ChildItem -Path $Modif_Agent\*.que | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".pro")}
                $Folder_Name = Get-ChildItem -Name $Modif_Agent\*.pro
                ForEach($file in $Folder_Name)
                {
                    $Folder_Name = $file.Substring(11,11)
                    [xml]$File_Name = Get-Content -Path "$Modif_Agent\$file"
                    $All_File = $File_Name.JobHandling.DeletedJob.ChildNodes | Select-Object -ExpandProperty "#text"
                    $OpJob_Path = $Config_File.Automation_Config.Path.OpJob
                    Set-Location $OpJob_Path\$Folder_Name
                    $All_File | ForEach-Object {
                            $Modif_File = Get-ChildItem -Path $_ | Remove-Item
                            # Write-Host "File modification $Modif_File"              
                    }                
                }
                 #verify the modification
                 $All_File | ForEach-Object {
                    if(Test-Path -Path $_)
                     {
                         Write-Host "Modification fail!"
                         #modify file to .err
                         Get-ChildItem -Path $Modif_Agent\$file | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".err")} -Force
                         REPORT
                     }
                     else{
                         Write-Host "Modification PASS!"
                         Write-Host "Continue to Modify file to .don"
                     }
                    }
                }
                #modify extension
                Set-Location ..
                Set-Location ..
                Set-Location ..
                Get-ChildItem -Path $Modif_Agent\*.pro | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".don")}
                Start-Sleep -Seconds 2

                Write-Host "Reporting"
                REPORT

    }
        else{
            
            Write-Host "Modification.que NOT exist, REPORTING"
            REPORT
        }
    }
[System.GC]::GetTotalMemory($true) | out-null
}


Function Check_Jobpro_Path
{
    $OpJob_Path = $Config_File.Automation_Config.Path.OpJob
    # $Report_Path
    $n = 0
    while (-not($OpJob_Path -eq ".\Job\Process")) {
        Start-Sleep -s 3
        #Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        $n++
        Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        [xml]$Config_File = Get-Content -path ".\Resource\Agent_Config.xml"
        $OpJob_Path = $Config_File.Automation_Config.Path.OpJob
        Write-Host "Attempt no $n"
    }
    Write-Host "Path found after $n attempts"
    Write-Host "OpJob_Path: $OpJob_Path"
    return $true
}
# ============================================#
Function Check_Jobpro
{
    if(Check_Jobpro_Path)
    {
        Write-Host "Path is ready"
    #Job.pro Monitoring
    $OpJob_Path = $Config_File.Automation_Config.Path.OpJob   # the root folder where .pro and .que files should be
    Write-Host "Jobpath:$OpJob_Path"
    $MaxAttempts = 10
    $L_Name = $Config_File.Automation_Config.LengthName
    #try and get an array of .pro filenames without extension and having the first 7 characters stripped off
    $n = 0
    while ($true) {
    $n++
    Write-Host "Attempt no $n finding .pro files"
    $ProFiles = @(Get-ChildItem -Path $OpJob_Path -Filter '*.pro' -File -Recurse | ForEach-Object { $_.BaseName.Substring($L_Name) })
    Write-Host "Profile:$ProFiles"
    # exit the endless loop if we found .pro files OR the number of attempts have reached the maximum
    if ($ProFiles.Count -gt 0 -or $n -gt $MaxAttempts) { break }
    # Start-Sleep -Seconds 1
}
    if ($ProFiles.Count) {
        #try and find .que files where the BaseName can be found in the $ProFiles array
        $n = 0
        while ($true) {
            $n++
            Write-Host "Attempt no $n finding .que files"
            $QueFiles = @(Get-ChildItem -Path $OpJob_Path -Filter '*.que' -File -Recurse | Where-Object { $ProFiles -contains $_.BaseName })
            Write-Host "QueFile:$QueFiles"
            # exit the endless loop if we found .que files OR the number of attempts have reached the maximum
            if ($QueFiles.Count -gt 0 -or $n -gt $MaxAttempts) { break }
            # Start-Sleep -Seconds 1
        } 
        # if .que files with similar names were found, remove them
        if ($QueFiles.Count) {
            Write-Host "Job  match files found after $n attempts"
            foreach ($que in $QueFiles) { 
                Write-Host "Removing file '$($que.FullName)'"
                Write-Host "Que:$que"
                $que | Remove-Item -Force
            }
        }

        else {
            Write-Warning "No Job match files (.QUE) found after $n attempts.."
        }
    }
    else {
        Write-Warning "No Job files (.PRO) found after $n attempts.."
           }

           ###CHECK JOB HANDLING RESULT###

           Job_Handling
    # # Write-Host "Continue for reporting"
    # REPORT
}
else{
    Write-Host "Path is not ready"
}
[System.GC]::GetTotalMemory($true) | out-null
}
# ============================================#

# MONITORING ERROR FILE
# ============================================#
Function Error_Monitoring
{
    Write-Host "Start Error Monitoring"
    #Error Job Monitoring
    $Job_Path = $Config_File.Automation_Config.Path.OriJob
    $L_NameError = $Config_File.Automation_Config.LengthName_Err
    $OpJob_Path = $Config_File.Automation_Config.Path.OpJob

    If(Test-Path "$OpJob_Path\*\*.err")
    {
        Write-Host "Job.err exist"
    Get-ChildItem -Path "$OpJob_Path\*\*.err" | ForEach-Object {
    $basename = $_.BaseName.Substring($L_NameError)
    $job = "$Job_Path\${basename}.job"
    if (Test-Path $job) {
        $timestamp = Get-Date -Format 'yyyyMMddhhmmss'
        $dst = Join-Path $_.DirectoryName "${timestamp}_${basename}.que"
        $GetFile = Get-ChildItem -Name "$OpJob_Path\*\*$basename.err*"
        Write-Host "Getfile:$GetFile"
        $Get = (Get-ChildItem -Name "$OpJob_Path\*\*$basename.err*" | Measure-Object).Count
        $limit_1 = $Config_File.Automation_Config.Limit_1
        Write-Host "Total Limit: $limit_1"
        if($Get -ge "$limit_1")
        {
                Write-Host "Continue Reporting"
                Check_Jobpro

        }
        else{
            Write-Host "Less than 3"
            Write-Host "Job: $job"
            Get-ChildItem -Path "$Job_Path\${basename}.job" | ForEach-Object{ $job_name = $_.BaseName.Substring(0)}
            Write-Host "Jobname: $job_name"

            if(-Not(Test-Path -Path "$OpJob_Path\*\*$basename.que*"))
            {   
                if(-Not(Test-Path -Path "$OpJob_Path\*\*$basename.pro*"))
                {
                    if(-Not(Test-Path -Path "$OpJob_Path\*\*$basename.don*"))
                {

                Write-Host "Copy Job Not Assigned"
                Copy-Item $job $dst -Force
                Check_Jobpro
            }
        }
        }
            else{
                Write-Host "Continue Check Job.pro"
                Check_Jobpro
            }
            Check_Jobpro
        }
    }  
}
    }
    else{
        Write-Host "Job.err not exist, continue check job.pro"
        Check_Jobpro
    }
    [System.GC]::GetTotalMemory($true) | out-null
}
# ============================================#

# CREATE OPERATIONAL JOB FILE
#============================================#
Function Create_OpJob
{
    Write-Host "Create OPJob"
    $Job_Path = $Config_File.Automation_Config.Path.OriJob
    $OpJob_Path = $Config_File.Automation_Config.Path.OpJob
        # Copy Job to BID Folder
        $Timestamp = Get-Date  -Format yyyyMMddhhmmss
        New-Item -ItemType Directory -Path "$OpJob_Path\$BID" -Force
        Copy-Item -Path "$Job_Path\*$BID*.job" -Destination "$OpJob_Path\$BID" -Force
        $GetOriJob = Get-ChildItem -Path "$OpJob_Path\$BID\*.job"
        $RenameJob = $GetOriJob | Rename-Item -NewName {"$Timestamp`_" + $_.Name.Replace('.job','.que')}
        # $RenameJob = $GetOriJob | Rename-Item -NewName {$_.Name.Replace('.job','.que')}

    if(Test-Path -Path "$PO_Path\*$BID*")
    {   
    #Export SSID
    $ReadSSID = $Read_Flag.SkyViewFlag.Platform.InnerText -split '(.{4})' |                             
    Where-Object { $_.Length -eq 4} | ForEach-Object { [Regex]::Escape($_) } 
    $Get_SSID = $ReadSSID -join '|'
    $OutputSSID = $Get_SSID | Out-File "$OpJob_Path\$BID\SSID_LST"

    #Copy SSID LST to allow ODMIC can modify
    Copy-Item -Path "$OpJob_Path\$BID\SSID_LST" -Destination "$OpJob_Path"
    Remove-Item "$OpJob_Path\$BID\SSID_LST"
    $GetSSID = Get-ChildItem -Path "$OpJob_Path\SSID_LST" 
    Move-Item -Path $GetSSID -Destination "$OpJob_Path\$BID"
    #Modify Ext SkyView Flag
    Write-Host "Modify Extentsion SkyView Flag"
    $Flg = Get-ChildItem "$Flag_Path\*$BID*.xml"
    $Flg
    Copy-Item -Path $Flg -Destination "$Job_Path"
    #Remove-Item "$Flag_Path\*.xml"
    $GetFlag = Get-ChildItem -Path "$Job_Path\*.xml"
    $RenameFlag = $GetFlag | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".PRO")}
    Move-Item "$Job_Path\*.PRO" -Destination "$Flag_Path"
    Remove-Item "$Flag_Path\*$BID*.xml"
    # Write-Host "Continue Error Monitoring"
    # Error_Monitoring
}
[System.GC]::GetTotalMemory($true) | out-null
}
#============================================#

Function Create_OriJob_Path
{
    $Job_Path = $Config_File.Automation_Config.Path.OriJob
    # $Report_Path
    $n = 0
    while (-not($Job_Path -eq ".\Job\Initial")) {
        Start-Sleep -s 3
        #Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        $n++
        Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
        [xml]$Config_File = Get-Content -path ".\Resource\Agent_Config.xml"
        $Job_Path = $Config_File.Automation_Config.Path.OriJob
        Write-Host "Attempt no $n"
    }
    Write-Host "Path found after $n attempts"
    Write-Host "OriJob_Path: $Job_Path"
    return $true
}
# ============================================#

# CREATE ORIGINAL JOB FILE
#============================================#
Function Create_OriJob
{
    if(Create_OriJob_Path)
    {
        Write-Host "Path is ready"
    Write-Host "Starting Mapping SWPO"
    $Sureload = $Config_File.Automation_Config.Out_Job.Sureload_identifier
    $Job_Path = $Config_File.Automation_Config.Path.OriJob
    $PO_Path = $Config_File.Automation_Config.Path.POfiles
    @(Get-ChildItem "$Flag_Path\*.xml") |
     ForEach-Object{
        [xml]$Read_Flag = Get-Content $_.FullName 
        $BID = $Read_Flag.SkyViewFlag.Build.BID   
    if(Test-Path -Path "$PO_Path\*$BID*")
    {   
        Write-Host "SWPO File Found"
        Get-ChildItem -Path "$PO_Path\*$BID*" | ForEach-Object{
        $Get_PO = Get-childItem -Path "$PO_Path\*$BID*"
        Write-Host "Get-PO: $Get_PO"
        $Read = Get-Content $Get_PO[0] | Where-Object {$_ -like "*;Feature_Byte*"}
        $Split = $Read.Substring(0, $Read.Length-3)
        $FB = $Split -split "="
        $FB_Sprt = $FB[1] -split '(..)' -join '|'
        $regex = [regex]$Sureload
        $matching = $regex.Match($FB_Sprt)
        $matching
        if ($matching.Success){
            Write-Host "Match"
            $SureLoad_Content = $Config_File.Automation_Config.Out_Job.Sureload_match
        }
        else{
            Write-Host "Not Match"
            $SureLoad_Content = $Config_File.Automation_Config.Out_Job.Sureload_notmatch
        }
    }
        #Create Job Content
        $PO_Content = Get-Content -path "$PO_Path\*$BID*"
        $POfile = Get-ChildItem -Name "$PO_Path\*$BID*"
        $Get_CRM = $PO_Content | Where-Object {$_ -like "*;CRM*"}
        $CRM = $Get_CRM.Substring(5,2)
        $CRM = $CRM.split()
        $POCountry = Get-ChildItem -Name "$PO_Path"
        $GetCountry = $POCountry.Substring(15,3)
        $GetCountry = $GetCountry.split()
        For($i = 0; $i -lt $POfile.Count; $i++){ 
            # try{
                $po = $POfile[$i]
                $c = $CRM[$i]
                $cc = $GetCountry[$i]
                # New-Item -ItemType File -Path "$Job_Path\$JobType`_$Prefix$BID`_$c.job" -Force
                $Title =  $Config_File.Automation_Config.Out_Job.Title
                $Auto = $Config_File.Automation_Config.Out_Job.Auto
                $Proc = $Config_File.Automation_Config.Out_Job.Process
                $AutoGM =  $Config_File.Automation_Config.Out_Job.AutoGM
                $PO_Conf =  $Config_File.Automation_Config.Out_Job.PO
                $BIDINFO = $Config_File.Automation_Config.Out_Job.BIDINFO
                $BuildID =  $Config_File.Automation_Config.Out_Job.BID
                $PFX =  $Config_File.Automation_Config.Out_Job.PFX
                $CRM_Conf =  $Config_File.Automation_Config.Out_Job.CRM
                $CountryConf = $Config_File.Automation_Config.Out_Job.Country
                $Platform = $Config_File.Automation_Config.Out_Job.Platform
                $Sureload_title = $Config_File.Automation_Config.Out_Job.Sureload_title
                $TSJobcreate = Get-Date
$Output_JOB = @"<?xml version="1.0" encoding="UTF-8"?><$Title><$Auto><$Proc>$AutoGM</$Proc><$PO_Conf>$po</$PO_Conf><$Sureload_title>$SureLoad_Content</$Sureload_title> </$Auto><$BIDINFO><$BuildID>$BID</$BuildID><$PFX>$Prefix</$PFX><$CRM_Conf>$c</$CRM_Conf><$CountryConf>$cc</$CountryConf></$BIDINFO><$Platform>
        $All_SSID</$Platform><Timestamp><JobCreate>$TSJobcreate</JobCreate></Timestamp>                </$Title>"@
Write-Host "$c"

                $Output_JOB | Out-File "$Job_Path\$JobType`_$Prefix$BID`_$c.job" -NoNewline 
                Write-Host "Output"
        }  
        Write-Host "Continue to create operational job"
        Create_OpJob 
    }
    else{
        Write-Host "SWPO Not Found, Do Error checking file"
        Error_Monitoring
    }
    #Error_Monitoring  
    }
}
else{
    Write-Host "Path is not ready"
}
[System.GC]::GetTotalMemory($true) | out-null
}
# ============================================#

# CHECKING THE FUNCTION
# ============================================#
Function Check_Function
{
    if($Function -eq "AutoGM")
    {
        Write-Host "AutoGM function found"
        #Create_OriJob#
        #Mapping BID with SWPO
        Create_OriJob
    }
    else{
        Write-Host "AutoGM function not found"
        Pause
    }
}
# ============================================#

# CONFIG FILE LOAD
#============================================#
if(Test-Path -Path .\Agent_Config.xml)
{
    Write-Host "Config file exist"
    Copy-Item -Path ".\Agent_Config.xml" -Destination ".\Resource" -Force
}
else{
    Write-Host "Config file not exist"
    Pause
}

[xml]$Config_File = Get-Content -path ".\Resource\Agent_Config.xml"

# LOG
#============================================#
$Log_Path = $Config_File.Automation_Config.Path.Log
$Log = Start-Transcript -Path $Log_Path -Force
Get-Date
Write-Host ">>Log_File: $Log"
$JobType = $Config_File.Automation_Config.Out_Job.JobType

# CHECKING THE FLAG FROM SKYVIEW
# ============================================#
$Flag_Path = $Config_File.Automation_Config.Path.Flag_Path
if(Test-Path -Path "$Flag_Path\*.xml")
{
    Write-Host "Flag Found"  
    $duplicates = Get-ChildItem -Path "$Flag_Path\*" -File -Include '*.xml', '*.pro' | 
    Group-Object -Property BaseName | Where-Object { $_.Count -gt 1 }
    if ($duplicates) {
    # output the duplicate XML to Flag_Duplicate.txt
    $duplicates.Group | Where-Object {$_.Extension -eq '.xml' } | ForEach-Object {
        $_.FullName | Out-File $Flag_Path\Flag_Duplicate -Append
    }   
    Write-Host "Flag duplicated, continue for Error_Monitoring"
    Error_Monitoring
}
    else{
    Write-Host "Flag does not duplicate, continue the process"
    @(Get-ChildItem "$Flag_Path\*.xml") | ForEach-Object{
        [xml]$Read_Flag = Get-Content $_.FullName     
        $BID = $Read_Flag.SkyViewFlag.Build.BID
        Write-Host ">>Build_ID: $BID"
        $Prefix = $Read_Flag.SkyViewFlag.Build.Prefix
        Write-Host ">>Prefix: $Prefix"
        $Function = $Read_Flag.SkyViewFlag.Automation.Type
        Write-Host "Function: $Function"
        $All_SSID = $Read_Flag.SkyViewFlag.Platform.InnerXml
        Write-Host "SSID: $All_SSID"        
    }      
    Check_Function
}
}
else{
    Write-Host "Flag not found, continue for Error_Monitoring"
    Error_Monitoring
}
Stop-Transcript

}
while(1)
[System.GC]::GetTotalMemory($true) | out-null

based on a csv file to set-aduser

$
0
0

hello,

I have a users list (csv file format). I wanna to set every user in the list password never expired.

so I do a test to verufy my idear :

first I use below commad :

get-aduser -Identity uat01 | Set-ADUser -PasswordNeverExpires $true

and the command excuted success.

so I want to export a csv file as a sample file:

get-aduser -Identity uat01 | export-csv c:\users\jerrysu\desktop\list01.csv

edit the file and then import :

$users = Import-Csv c:\users\jerrysu\desktop\list01.csv

then try:

PS C:\> foreach ($a in $users) {Set-ADUser $a -PasswordNeverExpires $true}
Set-ADUser : Cannot bind parameter 'Identity'. Cannot create object of type "Microsoft.ActiveDirectory.Management.ADUser". The adapter cannot set the value of
property "Name".
At line:1 char:36
+ foreach ($a in $users) {Set-ADUser $a -PasswordNeverExpires $true}
+                                    ~~
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.SetADUser

PS C:\>
PS C:\> foreach ($a in $users) {Set-ADUser -Identity $a -PasswordNeverExpires $true}
Set-ADUser : Cannot bind parameter 'Identity'. Cannot create object of type "Microsoft.ActiveDirectory.Management.ADUser". The adapter cannot set the value of
property "Name".
At line:1 char:46
+ foreach ($a in $users) {Set-ADUser -Identity $a -PasswordNeverExpires ...
+                                              ~~
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.SetADUser

why ? how can I set the users pw never expired by a csv file ?

thanks!


Adding O365 users with Powershell failed

$
0
0

Hello,

I am trying to add new O365 users by using Powershell. Unfortunately there's an error message:

New-MsolUser : You must provide a required property: Parameter name: UserPrincipalName
At line:1 char:26+ ... ach-Object {New-MsolUser -FirstName $_.FirstName -LastName $_.LastNam ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OperationStopped: (:) [New-MsolUser], MicrosoftOnlineException+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.RequiredPropertyNotSetException,
Microsoft.Online.Administration.Automation.NewUser

My command looks like that:
Import-Csv -Path "C:\Users\user\Downloads\O365-NewAccounts.csv" | foreach {New-MsolUser -DisplayName 
$_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName} |
Export-Csv -Path "C:\Users\user\Downloads\O365-NewAccountsResults.csv" -Verbose

Why is my command not working?



compare AD group users with server share with home directories

$
0
0

Hello,

If you can help me guys with this

I have server share where all users must have private directory and I want to see if I missed anyone

group is GroupA

directory is \\server01\Users

PowerShell Export-Csv can't work with UseQuotes parameter

$
0
0

I'm trying to start this from my Powershell script:

Import-Csv -Path $filecur -Delimiter ";" | Export-Csv -Path $filenext -Delimiter ";" -NoTypeInformation -Encoding Unicode -UseQuotes Never

But after executing Powershell script command promt show the next text:
Export-Csv : A parameter cannot be found that matches parameter name 'UseQuotes'.
At C:\Users\vad\Desktop\QuatesDeleter.ps1:4 char:116+ ... ilenext -Delimiter ";" -notypeinfo -Encoding Unicode -UseQuotes Never+                                                          ~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Export-Csv], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.ExportCsvCommand

How can I solve this problem? My computer is running under Windows 7, SP1, X64, PowerShell version is 5.1.14409.1005.

In Microsoft documentation I could't find some information about this problem

Link here

get-mobiledevicestatistics script

$
0
0

Hello all

I created this script to export certain information regarding mobile devices. The script is working fine, except I cant seem to figure out how to export the primarysmtp address to .csv. Appreciate any assistance. Thank you in advance

$today = get-date -format yyyyMMdd

$thisdevice =@()
$incre = 0
$o365users = import-csv C:\temp\MobileDevice\mobiledevice_$today.csv
    $o365users.count
 foreach ($item in $o365users) 
 {
     $incre++
     $incre
     $item.name
     $userdevices= get-mobiledevicestatistics -mailbox $item.alias
     if($null -ne $userdevices) {
     foreach ($device in $userdevices) {
     $device=$device |Select-Object deviceos,DeviceModel,lastsuccesssync,guid
     $thisdevice+=new-object psobject -property @{loginID=$item.alias;Name=$item.name;Email=$item.primarysmtpaddress;Model=$device.devicemodel;Deviceos=$device.deviceos;lastsuccesssync=$device.lastsuccesssync;guid=$device.guid}
     #if($device.lastsuccesssync -lt (get-date).addDays(-30)){
     $device  
     #remove-mobiledevice $device.guid#  
     }
    }}

$thisdevice |export-csv -append c:\temp\mobiledevice\mobiledeviceoutput_$today.csv


Bulls on Parade

PS-Script Import-Clixml Problem with password

$
0
0

Hi guys

Im scheduling a ps-script for transfer of data between directories. I need to provide local credentials from destination server and I am doing with import-clixml.

It doesnt work out. If I am running the script I get this error:

Import-Clixml : Data at the root level is invalid. Line 1, position 1.
At C:\scripts\xxx.ps1:13 char:36+ $password = ConvertTo-SecureString(Import-Clixml -Path  C:\Temp\pw_file.xml ...+                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Import-Clixml], XmlException+ FullyQualifiedErrorId : System.Xml.XmlException,Microsoft.PowerShell.Commands.ImportClixmlCommand
New-Object : Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "password" is null. Change the 
value of argument "password" to a non-null value."
At C:\scripts\xxx.ps1:15 char:16+ $credentials = New-Object System.Management.Automation.PSCredential($user,$p ...+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

I use this config:

$password = ConvertTo-SecureString(Import-Clixml -Path C:\Temp\pw_file.xml)
$user= 'testuser'
$credentials = New-Object System.Management.Automation.PSCredential($benutzer,$password)

#drive mapping

New-PSDrive –Name S –PSProvider FileSystem –Root \\testserver\inbox -Credential $credentials
New-PSDrive –Name T –PSProvider FileSystem –Root \\testserver\outbox -Credential $credentials
...

The pw_file.xml contains the password from the user in plain text (I know not the best way...). 
Why do I get this error?

Greets

Set-CsUser, How can I pass Identity and OnPremLineURI tel from a CSV list?

$
0
0

How can i make this script work below so that i can auto-add BULK USERS AND NUMBERS into MS Teams? 

$UserList = Import-Csv "C:\FILEPATH\Bulkusers.csv"
ForEach ($item in $UserList){   
$Identity = $($item.identity)  
$OnPremLineURI  = $($item.OnPremLineURI )
$EnterpriseVoiceEnabled = $($item.EnterpriseVoiceEnabled)
$HostedVoiceMail = $($item.HostedVoiceMail)

$PolicyName = Amazon

set-csuser -identity "sip:.$identity" -EnterpriseVoiceEnabled $EnterpriseVoiceEnabled -HostedVoiceMail $HostedVoiceMail -OnPremLineURI "tel:.$OnPremLineURI"

Grant-CsOnlineVoiceRoutingPolicy -Identity $_ -PolicyName $PolicyName

}

How to pass windows patch information into a sql table?

$
0
0

Hi!

I have the following command which gives me the patch history information for a server:

wmic qfe list

Is there any way I can pass this through to a SQL Server table?

Thanks,

Zoe



Get-ItemProperty

$
0
0

So I have a command: $Result = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation | Select-Object DependOnService)

The result comes back as :

DependOnService        
---------------        
{bowser, mrxsmb10, nsi}

How can I make the following command result in a true statement?

If ($Result -eq '{bowser, mrxsmb10, nsi}')
   {
    Write-Output "Success!!"
   }

else {}

Normally when I do this, there is one value listed.  I have never had to do this with multiple values.  WIll search the web, but time is pressing at the moment and I figured I'd reach out here. 

Thank you

Matt 


Matt Dillon

Convert CURL syntax to Powershell Invoke-Webrequest

$
0
0

Hello,

I'm having a tough time converting the following CURL command line to powershell.  Specifically the data (-d) portion.  I'm close but get an error stating I'm providing an invalid roleID which seems I'm close but must be missing something.  Any help would be much appreciated.  Thanks.

curl -X POST https://some-api-url \    -H 'Authorization: bearer ABCDE....' \    -d {"roleIds":["falconhost_read_only"]}

******************************

$Token = "a-very-long-number"

$USER_UUID = "some-long-number"
$Uri = "https://some-api-url"
$Authorization = "Bearer $Token"
$Body = @{
    'roleIds'='falconhost_read_only'
}
$Headers = @{
    Authorization = $Authorization

}
$Response = Invoke-WebRequest -Method POST -Uri $Uri -Body $Body -Headers $Headers -ContentType 'application/json; charset=utf-8'


Incrementing Version Numbers in PowerShell

$
0
0

Hi All

Not a question but I had a situation where I needed to organise version numbers and then pull the latest and increment it. I thought this might be of help to others who need to do the same thing.

I needed to get my version number from git. This is how you do it.

((git tag).split([environment]::newline) | sort {[version] ($_)} -descending)[0]

The above will work for any multi-line string of version numbers. PowerShell is able to sort them when you call the [Version] accelerator

I created a function to increment the version number, it's used as follows:

PS C:\bitbucket\pcs_cam> ((git tag).split([environment]::newline) | sort {[version] ($_)} -descending)[0]                              0.0.21
PS C:\bitbucket\pcs_cam> ((git tag).split([environment]::newline) | sort {[version] ($_)} -descending)[0] | Increment-Version -build                 

0.0.22
PS C:\bitbucket\pcs_cam> ((git tag).split([environment]::newline) | sort {[version] ($_)} -descending)[0] | Increment-Version -minor                 

0.1.0
PS C:\bitbucket\pcs_cam> ((git tag).split([environment]::newline) | sort {[version] ($_)} -descending)[0] | Increment-Version -major                 

1.0.0

Here is the function:

Function Increment-Version {<#
.SYNOPSIS
Increments a version number.
.DESCRIPTION
Increments a Major, Minor or Build version number.
.PARAMETER Version
Version number to increment.
.PARAMETER Major
Increments the major version
.PARAMETER Minor
Increments the minor version
.PARAMETER Build
Increments the build version
.EXAMPLE
Increments the build version
Increment-Version -Version 0.0.10 -Build

0.0.11
.EXAMPLE
Increments the minor version
    
Increment-Version -Version 0.1.10 -Minor

0.2.0
.EXAMPLE
Increments the major version
    
Increment-Version -Version 1.1.10 -Major

2.0.0
.NOTES
#>    
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName, ValueFromPipeline)][ValidateNotNullOrEmpty()][Version]$Version,
        [Parameter(ParameterSetName = 'Build', Mandatory = $true)][Switch]$Build,
        [Parameter(ParameterSetName = 'Minor', Mandatory = $true)][Switch]$Minor,
        [Parameter(ParameterSetName = 'Major', Mandatory = $true)][Switch]$Major
    )

    Switch ($PSCmdlet.ParameterSetName) {
        Build {Return "{0}.{1}.{2}" -f $Version.Major, $Version.Minor, ($Version.Build +1)}
        Minor {Return "{0}.{1}.{2}" -f $Version.Major, ($Version.Minor +1), 0}
        Major {Return "{0}.{1}.{2}" -f ($Version.Major +1), 0, 0}
    }
}

Hope this helps.


How to increment in a loop every n items?

$
0
0

we have several reports that require updating their schedules and so ive written a script that does the updates but i am on the last part and not sure how to do it.

suppose i have an array containing 3 items

$bodyArray = @(@{"schedule1"},@{"schedule2"},@{"schedule3"})

I have the following loop

$loopCount = 0

foreach ($refreshSchedulePlanId in $reportRefreshScheduleSubscriptionIdDataWithoutHeader)
{   $loopCount++
    Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/CacheRefreshPlans($refreshSchedulePlanId)") -Method Put -Body ($bodyArray[$loopCount] | ConvertTo-Json -Depth 100) -ContentType "application/json"
}

Now of course this means -Body ($bodyArray[$count] will be iterating +1 everytime, which will eventually break the limit of the 3 items in the array.

What i want to do is something like this:

$loopCount = 0

foreach ($refreshSchedulePlanId in $reportRefreshScheduleSubscriptionIdDataWithoutHeader)
{   
    #$loopCount++ every $refreshSchedulePlanId/$bodyArray.Count

    Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/CacheRefreshPlans($refreshSchedulePlanId)") -Method Put -Body ($bodyArray[$loopCount] | ConvertTo-Json -Depth 100) -ContentType "application/json"
}

Note the comment in the pseudocode. This means that say i have 23 ID's, so for every 23/3 or about 8 ID's increment the $loopCount

Powershell script to remove expired cert from specific issuer

$
0
0

I'm trying to do a script to remove a cert from workstations in the Computer Personal store that is expired and from a specific issuer,

This works fine to remove all expired certs from the store:

        $Certs = Get-ChildItem "Cert:\LocalMachine\My" -Recurse
       Foreach($Cert in $Certs) {
            If($Cert.NotAfter -lt (Get-Date)) {
                $Cert | Remove-Item
            }
        }


This is what I've tried to add the issuer but I can't get it to work:

        $Certs = Get-ChildItem "Cert:\LocalMachine\My" -Recurse
       Foreach($Cert in $Certs) {
            If($Cert.NotAfter -lt (Get-Date) -and ($_.issuer -eq "Issuer Name") {
                $Cert | Remove-Item
            }
        }

Additionally it would be cool to be able to also base the condition on if the Certificate was issued to the FQ host name of the client but this is less important.

Any help in the right direction is appreciated.

Viewing all 21975 articles
Browse latest View live


Latest Images

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