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

help: Import-Module ActiveDirectory from remote server share

$
0
0

So here's the rub: I don't want to enable constrained delegation on the target server (WS2012R2 with latest WMF/RSAT); I'm betting this is why I see errors about AD Web Services being unavailable when I actually import this module in a possession from client to this server.

What I WANT to do is simply load the ActiveDirectory module onto the client from a UNC share e.g. Import-Module -Name \\server\share\ActiveDirectory

Now...this will work on a client with RSAT tools installed, but on any client that does NOT have RSAT tools installed, I'm stuck with this error:

import-module : Could not load file or assembly
'file://\\server\share\ActiveDirectory\Microsoft.ActiveDirectory.Management' or one of its dependencies. The system
cannot find the file specified.
At line:1 char:1
+ import-module -Name \\server\share\ActiveDirectory\ActiveDirectory.psd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

I'm assuming I could use Add-Type to similarly add the necessary file/assembly from a share, but I've had no luck figuring out exactly how to do so.


born to learn!


Mapping Service Accounts to Services without SPN mapping

$
0
0

Hello Team, 

I have a requirement where i would need to Map Windows Service Accounts to the Services they use when they logon to a particular application . We are basically trying to do a Clean up activity of the Service Accounts and not sure which service account uses what application within the infrastructure . 

Requirement 

65 Applications within the Infrastructure that needs to be mapped to the Service Accounts that uses it . I know i can pull out all the service accounts on power shell , The question is can i map these service accounts to the application services that they use ? 

Regards

K_Sundar

WMI command “ select Name and DeviceID from Win32_Volume” is giving same value for both Name and DeviceID for System Reserved Volume partition.

$
0
0

I am trying to get the details of all the partitions of one machine using WMI command. I need Name, Capacity and FreeSpace of each partitions, so used Win32_Volume command but this command is not giving appropriate Name for System Reserved Volume Partition. Name is coming as like this “ \?\Volume{0df78724-c412-11e4-80b4-806e6f6e6963}". it is same as DeviceID.

For all other partitions the Name value is proper. But how to get the appropriate human readable name for system Reserved volume.

Problem Launching PoweShell

$
0
0

Hay

I have Server 2016 standart.

When i open PS i get the attached screen and i cant run scripts, cmdlets etc.

Thanks

How can I pass the rename-computer credential in a powershell script (.ps1)?

$
0
0

Hello everyone,

How can i give the password to "rename-computer" for the "-domaincredential" attribute in the powershell script,?

There are no properties/methods like "-password" (eg image)

I want the script to execute silently, the without HAVING to Manually The Enter password that Needs to be encrypted.

I have read the links below,  but still confused How to Write the completely command in .ps1
: HTTPS: //stackoverflow.com/questions/23482389 /entering-a -password-for-domaincredential-in-rename-computer -in-powershell?Noredirect = 1&lq = 1
https://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename- Command

I wrote the following, but it n't work to rename my computer name.

$path=\\sc\cont
$computername="CN-D"+$number
$currentname=(Get-CimInstance -ClassName Win32_ComputerSystem).Name
$user="sc\joindomain"
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $passwd
if($computername -ne $currentname){
    Rename-Computer -NewName $computername -DomainCredential $credential
}

Thank you in advance.

fixing two errors on powershell script

$
0
0

I have a semi completed power script program that is used as Quick SQL server manager. the users are able to login with their sql server creds and select whatever option form a list to do commands. I need some help about how to fix these two errors. what will the script look like after the errors are fixed? you can show the new script after the errors are fixed then I'll be able to compare my original script with the new script.

This is the powershell script below

$nl = [Environment]::NewLine

class DatabaseConfig {
    [string]$Name
    [string]$Uuid
    [string]$DbHost
    [int]   $Port
    [string]$Login
    [string]$Password

    [System.Data.SqlClient.SqlConnection] $connection

    DatabaseConfig([string] $name, [string] $db, [string] $login, [string] $pwd = $null, [int] $port = 1433, [string] $uuid = (New-Guid).Guid) {
        $this.Uuid = $uuid
        $this.Name = $name
        $this.DbHost = $db
        $this.Port = $port
        $this.Login = $login
        $this.Password = $pwd
    }

    static [DatabaseConfig] Deserialize([string] $json) {
        $data = ConvertFrom-Json $json
        return [DatabaseConfig]::new($data.Name, $data.DbHost, $data.Login, $data.Password, $data.Port, $data.Uuid)
    }

    [string]Serialize() {
        if ($this.connection -and $this.connection.State -eq 'Open') {
            $this.connection.Close()
        }

        $this.connection = $null

        return $this | ConvertTo-Json -Compress
    }

    [bool]TestConfig() {
        Write-Host "Testing configuration..."

        if ($this.connect()) {
            $cmd = [System.Data.SqlClient.SqlCommand]::new("select 1", $this.connection)
            [int]$res = $cmd.ExecuteScalar()

            if ($res -eq 1) {
                return $true
            }
            else {
                Write-Host "Error: Could not execute sample query on server..." -ForegroundColor Red
                return $false
            }
        }
        else {
            Write-Host "Error: Could not establish database connection..." -ForegroundColor Red
            return $false
        }

    }

    [bool]connect() {
        if ($this.connection -and $this.connection.State -eq 'Open') {
            return $true
        }

        $pwd = $this.Password

        if (!$pwd) {
            $pass = Read-Host "Database password" -AsSecureString
            $pwd = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
        }

        try {
            # Write-Host 'here 1'
            $connStr = $this.getConnectionString($pwd)
            # Write-Host "Connection String: $connStr"
            $this.connection = [System.Data.SqlClient.SqlConnection]::new($connStr)
            $this.connection.Open()
            return $true
        }
        catch {
            Write-Error $_
            return $false
        }
    }

    [string]getConnectionString([string] $password) {
        return "Server = $($this.DbHost),$($this.Port); Database = master; User ID = $($this.Login); Password = $password;"
    }
}

function LoadConfigs {
    [DatabaseConfig[]]$dbs = @()
    # Write-Host "dbstype: $($dbs.GetType() | Format-Table | Out-String)"
    if (Test-Path .\config.json -PathType Leaf) {
        Get-Content .\config.json | ForEach-Object {
            $xdb = [DatabaseConfig]::Deserialize($_)
            if ($xdb.Uuid -and ($xdb.Uuid.Length -gt 5)) {
                $dbs += $xdb
            }
        }
    }
    # Write-Host "dbstype: $($dbs.GetType() | Format-Table | Out-String)"

    return , $dbs
}

function UpdateConfigFile([DatabaseConfig[]] $objects) {
    $contents = ""

    # Write-Host "objects: $($objects | Format-Table | Out-String)"

    $objects | ForEach-Object {
        $contents += $_.Serialize()
        $contents += $nl
    }

    $contents | Out-File .\config.json
}

function NewConfig {
    Write-Host "$($nl)Adding new configuration option...$nl"

    $defaultName = "Config $((Get-Date).ToString("yyyyMMddhhmmss"))"

    $name = Read-Host "Profile Name ($defaultName)"
    if (!$name) {
        $name = $defaultName
    }

    $db = Read-Host "Database host (127.0.0.1)"
    if (!$db) {
        $db = '127.0.0.1'
    }
    $port = Read-Host "Port (1433)"
    if (!$port) {
        $port = '1433'
    }
    $login = Read-Host "User name (sa)"
    if (!$login) {
        $login = 'sa'
    }
    $pass = Read-Host "Password (WILL BE STORED IN PLAIN TEXT; leave blank to be prompted every time)" -AsSecureString
    $pwd = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
    if (!$pass) {
        $pwd = $null
    }

    $conf = [DatabaseConfig]::new($name, $db, $login, $pwd, $port, (New-Guid).Guid)

    Write-Host "$($nl)Confirmation:$nl"
    Write-Host "Profile Name: $name"
    Write-Host "Host: $db,$port"
    Write-Host "Login: $login"
    Write-Host "Password: $(if ($pwd) { "(hidden)$nl" } else { "(prompt)$nl" })"

    Write-Host "Confirm [(y)es, (n)o, (c)ancel]? " -NoNewline

    Do {
        $key = $Host.UI.RawUI.ReadKey()
        Write-Host $nl

        switch ($key.Character) {
            'y' {
                if ($conf.TestConfig()) {
                    Write-Host "Database record created successfully..." -ForegroundColor Green
                    return $conf
                }
                else {
                    Write-Host "Error: Could not create database configuration record..." -ForegroundColor Red
                    return $null
                }
            }
            'n' {
                NewConfig
            }
            'c' {
                return $null
            }
        }
    } Until (($key.Character -eq 'y') -or ($key.Character -eq 'n') -or ($key.Character -eq 'c'))
}

class TableInfo {
    [string]$tableName
    [int]   $approxRowCount
}

class DatabaseLayout {
    [string] $dbName
    [TableInfo[]] $tableInfo
}

class DatabaseInstanceLayout {
    [DatabaseLayout[]] $databases

    DatabaseInstanceLayout([System.Data.SqlClient.SqlConnection] $connection) {
        $dbQuery = "use master; select name from sys.databases where name not in ('master','model','msdb','tempdb') and is_distributor = 0 order by name asc"
        $tableDataQuery = "select t.name, x.row_count from sys.tables t outer apply (select ix.Row_Count from sys.dm_db_partition_stats ix where ix.object_id = t.object_id) x order by t.name asc"

        [string[]]$_dbNames = @()
        [DatabaseLayout[]] $_allDbs = @()

        if ($connection.State -ne 'Open') {
            $connection.Open()
        }

        $cmd = [System.Data.SqlClient.SqlCommand]::new($dbQuery, $connection)
        $reader = $cmd.ExecuteReader()
        while ($reader.Read()) {
            $_dbNames += $reader.GetString(0)
        }

        $reader.Close()

        # w "DB Names: $($_dbNames | Format-Table | Out-String)"

        $_dbNames | ForEach-Object {
            $_dbName = $_
            [TableInfo[]] $_tblInfo = @()

            $cmd.Parameters.Clear()
            $cmd.CommandText = "use [" + $_dbName + "]; $tableDataQuery"
            $reader = $cmd.ExecuteReader()
            # w "xxDB Names: $($_dbNames | Format-Table | Out-String)"
            # w "rdr: $($reader | Format-Table | Out-String)"

            while ($reader.Read()) {
                [TableInfo] $_info = [TableInfo]::new()
                $_info.tableName = $reader.GetString(0)
                $_info.approxRowCount = $reader.GetInt64(1)
                $_tblInfo += $_info
            }

            $reader.Close()

            [DatabaseLayout]$newDb = [DatabaseLayout]::new()
            $newDb.dbName = $_dbName
            $newDb.tableInfo = $_tblInfo

            $_allDbs += $newDb
            # w "_tblInfo: $($_tblInfo | Format-Table | Out-String)"
        }

        $this.databases = $_allDbs
    }
}


function main() {
    $dbInstances = @()
    Set-Alias -Name w -Value Write-Host

    # [DatabaseConfig] $activeDbConfig = $null
    Set-Variable -Name activeDbConfig -Option AllScope
    Set-Variable -Name activeDbLayout -Option AllScope
    
    Set-Variable -Name actionSelectedDatabase -Option AllScope
    Set-Variable -Name actionSelectedTable -Option AllScope
    Set-Variable -Name actionPendingSqlStatement -Option AllScope

    $header = {
        Clear-Host
        w "Quick SQL Manager$($nl)-------------------------------------$($nl)"
    }

    $selectConfig = {
        param([DatabaseConfig] $config)

        w "$nl$($nl)Reading database server layout..."

        if (!$config.connect()) {
            Write-Host "Error: Could not connect to database... Error selecting config" -ForegroundColor Red
        }
        else {
            $activeDbLayout = [DatabaseInstanceLayout]::new($config.connection)
            Write-Host "Done... Read $($activeDbLayout.databases.count) databases" -ForegroundColor Green

            $activeDbConfig = $config
        }
    }

    $configController = {
        $configSelection = {
            w "Configuration Profiles:$nl" -ForegroundColor Cyan
            $i = 1
            $dbInstances | ForEach-Object {
                [DatabaseConfig]$p = $_
                w "$i) $($p.Name) ($($p.DbHost),$($p.Port))"
                $i += 1
            }
            w $nl
            w "Administrative Options:$nl" -ForegroundColor Cyan
            w "a) Add a new profile"
            w "$nl"
            w "Select a profile or an administrative option: " -NoNewline
            $inputLoop = $false

            do {
                $key = $Host.UI.RawUI.ReadKey()
                switch ($key.Character) {
                    'a' {
                        & $header& $newConfig
                        $inputLoop = $false
                        break
                    }
                    default {
                        $n = $_ - 48
                        if (($n -gt 0) -and ($n -lt $i)) {& $selectConfig($dbInstances[$n - 1])
                            $inputLoop = $false
                        }
                        else {
                            $inputLoop = $true
                        }
                        break
                    }
                }
            } until(!$inputLoop)
        }

        $newConfig = {
            $res = NewConfig

            if ($null -ne $res -and $res.Uuid -and ($res.Uuid.Length -gt 5)) {
                $dbInstances = $dbInstances + [DatabaseConfig]$res
                UpdateConfigFile($dbInstances)
            }
        }

        while ($null -eq $activeDbConfig) {
            & $header

            # Write-Host "type: $($dbInstances.GetType() | Format-Table | Out-String)"
            $dbInstances = LoadConfigs
            # Write-Host "type: $($dbInstances.GetType() | Format-Table | Out-String)"

            if ($dbInstances.count -lt 1) {
                w "No configuration profiles detected...$nl"& $newConfig 
            }
            else {& $configSelection
            }

            if ($null -eq $activeDbConfig) {
                pause
            }
        }
        # w "Selected Config: $($activeDbConfig | Format-Table | Out-String)"
        # w "Db layout: $($activeDbLayout | Format-Table | Out-String)"
        pause
    }

    $actionController = {
        $actionHeader = {
            & $header
            w "Active Database Profile: $($activeDbConfig.Name) (Server: $($activeDbConfig.DbHost),$($activeDbConfig.Port); User: $($activeDbConfig.Login))$nl" -ForegroundColor Blue
        }

        $selectDb = {
            w "Databases detected on instance:$nl" -ForegroundColor Cyan
            $i = 1
            $activeDbLayout.databases | ForEach-Object {
                [DatabaseLayout]$p = $_
                w "$i) $($p.dbName)"
                $i += 1
            }
            w $nl
            w "Select a database or 'c' to cancel: " -NoNewline
            $inputLoop = $false

            do {
                $key = $Host.UI.RawUI.ReadKey()
                switch ($key.Character) {
                    'c' {
                        $inputLoop = $false
                        break
                    }
                    default {
                        $n = $_ - 48
                        if (($n -gt 0) -and ($n -lt $i)) {
                            $actionSelectedDatabase = $activeDbLayout.databases[$n - 1]
                            $inputLoop = $false
                        }
                        else {
                            $inputLoop = $true
                        }
                        break
                    }
                }
            } until(!$inputLoop)
        }

        $selectTable = {
            if (!$actionSelectedDatabase) {
                Write-Host "Error: No database selected..." -ForegroundColor Red
                pause
                return
            }

            w "Tables detected in [$($actionSelectedDatabase.dbName)]:$nl" -ForegroundColor Cyan
            $i = 1
            $actionSelectedDatabase.tableInfo | ForEach-Object {
                [TableInfo]$p = $_
                w "$i) $($p.tableName) (~$($p.approxRowCount) rows)"
                $i += 1
            }
            w $nl
            w "Select a table or 'c' to cancel: " -NoNewline
            $inputLoop = $false

            do {
                $key = $Host.UI.RawUI.ReadKey()
                switch ($key.Character) {
                    'c' {
                        $inputLoop = $false
                        break
                    }
                    default {
                        $n = $_ - 48
                        if (($n -gt 0) -and ($n -lt $i)) {
                            $actionSelectedTable = $actionSelectedDatabase.tableInfo[$n - 1]
                            $inputLoop = $false
                        }
                        else {
                            $inputLoop = $true
                        }
                        break
                    }
                }
            } until(!$inputLoop)
        }

        $actionSelection = {
            $actionSelectedDatabase = ""
            $actionSelectedTable = ""
            $actionPendingSqlStatement = ""& $actionHeader

            w "Database Options:$nl" -ForegroundColor Cyan
            w "a) Drop a database"
            w "b) Backup a database"
            w "c) Restore a database"
            w "d) Truncate a table"
            w "$nl"
            w "Select a database action: " -NoNewline
            $inputLoop = $false

            do {
                $key = $Host.UI.RawUI.ReadKey()
                switch ($key.Character) {
                    'a' {
                        & $actionHeader& $selectDb

                        if ($actionSelectedDatabase) {
                            $actionPendingSqlStatement = "use master; alter database [$($actionSelectedDatabase.dbName)] set single_user with rollback immediate; drop database [$($actionSelectedDatabase.dbName)];"
                        }

                        $inputLoop = $false
                        break
                    }
                    'b' {
                        & $actionHeader& $selectDb

                        if ($actionSelectedDatabase) {
                            $backupName = $((Get-Date).ToString("yyyyMMddhhmmss"))
                            $backupPath = Read-Host "Full Backup Path With Drive Letter (on local server)"

                            if ($backupPath) {
                                $actionPendingSqlStatement = "use [$($actionSelectedDatabase.dbName)]; BACKUP DATABASE [$($actionSelectedDatabase.dbName)] TO DISK = '$backupPath' WITH FORMAT, MEDIANAME = 'Backup$backupName', NAME = 'Full Backup of $($actionSelectedDatabase.dbName)_$backupName' ;;"
                            }
                        }

                        $inputLoop = $false
                        break
                    }
                    'c' {
                        & $actionHeader& $selectDb

                        if ($actionSelectedDatabase) {
                            $backupName = $((Get-Date).ToString("yyyyMMddhhmmss"))
                            $backupPath = Read-Host "Full Backup Path With Drive Letter (on local server)"

                            if ($backupPath) {
                                $actionPendingSqlStatement = "use [master]; RESTORE DATABASE [$($actionSelectedDatabase.dbName)] FROM DISK = '$backupPath' WITH REPLACE;"
                            }
                        }

                        $inputLoop = $false
                        break
                    }
                    'd' {
                        & $actionHeader& $selectDb

                        if ($actionSelectedDatabase) {
                            & $actionHeader& $selectTable
                            if ($actionSelectedTable) {
                                $actionPendingSqlStatement = "use [$($actionSelectedDatabase.dbName)]; truncate table [$($actionSelectedTable.tableName)];"
                            }
                        }

                        $inputLoop = $false
                        break
                    }
                }
            } until(!$inputLoop)
        }

        while (1) {
            & $actionSelection

            if ($actionPendingSqlStatement) {
                w "$($nl)Confirm execution of SQL statement: " -ForegroundColor Red -NoNewline
                w $actionPendingSqlStatement -ForegroundColor White
                Write-Host "[(y)es, (n)o]? " -NoNewline
                Do {
                    $key = $Host.UI.RawUI.ReadKey()
                    Write-Host $nl

                    switch ($key.Character) {
                        'y' {
                            try {
                                if ($activeDbConfig.connect()) {
                                    $cmd = [System.Data.SqlClient.SqlCommand]::new($actionPendingSqlStatement, $activeDbConfig.connection)
                                    $res = $cmd.ExecuteNonQuery()

                                    w "Query executed successfully" -ForegroundColor Green
                                    # w "$res rows affected"        // This is irrelevant for any operations here
                                    w "$nl$($nl)Reading database server layout..."
                                    $activeDbLayout = [DatabaseInstanceLayout]::new($activeDbConfig.connection)
                                    Write-Host "Done... Read $($activeDbLayout.databases.count) databases" -ForegroundColor Green
                                }
                                else {
                                    Write-Host "Error: Could not establish database connection..." -ForegroundColor Red
                                }
                            }
                            catch {
                                Write-Host "Query execution error: $_" -ForegroundColor Red
                                return $false
                            }

                            $actionPendingSqlStatement = $null

                            pause
                        }
                        'n' {
                            $actionPendingSqlStatement = $null
                        }
                    }
                } Until (($key.Character -eq 'y') -or ($key.Character -eq 'n'))
            }
        }
    }

    & $configController

    if ($null -ne $activeDbConfig -and $null -ne $activeDbLayout) {
        & $actionController
    }
}

main

([App]::new()).Run()

[DatabaseConfig[]]$databases = LoadConfigs

Write-Host $databases

$n = NewConfig

echo Done
 echo "n:"
 echo $n
 echo "n serialized:"
 echo $n.Serialize()

 if($n) {
     $databases += $n
     UpdateConfigFile($databases)
 }

Error 1: In the program, the user is supposed to be able to select any number when asked, "select a database". The issue is, it only can select a signal digit number. It needs to be able to select double digit numbers. 


Error 2: In the program, There's a option to "restore a database". The issue is, when the user selects that option, the script shows the list of databases that already exists. It's not suppose to do that. It needs to shows the dropped databases. So when the user selects restore a database, the script shows the databases that were dropped and that user can pick which database they want to restore.



PowerShell Core on Linux Wait-Job timeout not working

$
0
0

Hi - 

I'm having trouble with the Wait-Job cmdlet on PowerShell Core for Linux. I have a Job created with Start-Job, which I wait for with:

Wait-Job $job -Timeout 30

Which should timeout after 30-seconds. However, the command consistently hangs for 2-minutes before it completes. Am I doing something wrong, and if not, could this bug be fixed? I'm running PowerShell 6.2.0 on Ubuntu 16.04.6 LTS.


Many thanks!

Import-WdsInstallImage : An install image could not be found in the image file

$
0
0

As asked from here I ask my question on the PowerShell forum.

Hello,

The WDS server is a freshly installed Win 2019 server.

I am trying to import install images with PowerShell.

$ImagePath = 'D:\Sources\2019\install.wim'
$ImageName = (Get-WindowsImage -ImagePath $ImagePath -Index 4).ImageName
Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -Path $ImagePath -Multicast

However I get the following error:

Import-WdsInstallImage : An install image could not be found in the image file.
At line:3 char:1+ Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -P ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (MSFT_WdsInstallImage:root/cimv2/MSFT_WdsInstallImage) [Import-WdsInstallImage], CimException+ FullyQualifiedErrorId : 0xC111010E,Import-WdsInstallImage

The image file is NOT read-only.

And with the console it works fine.

I also installed the latest system rollup, but the behavior is the same.

I first started to display image names with Get-WindowsImage and copy/paste the name to the Import-WdsInstallImage and got the same error. That's why I was getting directly the name from the Get-WindowsImage cmdlet. But no luck, still the same error...

And while the Import-WdsInstallImage returns an error, the Import-WdsBootImage and theGet-WindowsImage cmdlets are works fine.

Does anybody see what's wrong with my code or my command lines?

How come I cannot run this basic powershell command?

$
0
0

Hi - I'm just trying to get used to running some basic troubleshooting commands in powershell so wanted to load up the logs. I tried a couple from Event viewer. System I can kind of understand but what about the SECURITY log? Do certain services have to be stopped before running the security log for troubleshooting purposes? 

Thanks in advance

Need to Copy all treeview nodes(which are "checked") when i hit the command button using powershell.

$
0
0

Hi,

I am not able to find direct powershell command to copy the all treeview nodes(which are "checked") when i hit the command button. kindly advice and share the script for achieving the task. thanks.

Regards,

Senthil kumar R. 

n/a

Export all VMs and VHD from a Cluster Shared Volume

$
0
0

Hello guys,

I am trying to do a script to take all the VMs from a specific CSV (Cluster Shared Volme) and the VHD attached to them. 

My script look like:

Get-SCVirtualMachine -VMMServer VMMServerName -all | where{$_.location -like ‘C:\ClusterStorage\VolumeX’} | Select-Object Name,Location, @{N="Capacity(GB)";E={[math]::Round($_.TotalSize/ 1GB)}}

The output is good but the only problem is with the VMs that have more the 1 VHD disk. I have VMs with multiple VHD disks on multimple CSV LUNs.

EX: VM x has a disk on CSV1 and a disk on CSV2 and i need to get only the disk size from CSV1. In my script I get object TotalSize and because of that i get a sum of the 2 disks.

I did some research on google and i found the command Get-VHD and i have modify my script like this:

$VMs= Get-SCVirtualMachine -VMMServer VMMServerName -all | where{$_.location -like ‘C:\ClusterStorage\VolumeX’} 
foreach ($VM in $VMs) {
Get-VHD | Select-Object Name,Location, @{N="Capacity(GB)";E={[math]::Round($_.TotalSize/ 1GB)}}
}

But when i run it i get the message: Path[0]:

What i am doing wrong?

Thanks!



delete entire row from a column

$
0
0

Hi all friends,

there is a piece of code  tha is a pain in the neck.

I am trying to delete entire rows from an excel doc with powershell, but the code delete only some rows but not all.

the excel has the Sheet1 with three columns and the column A has some empty cells ( second sheet is to copy paste the values andd test again and again )

the code is this:

 

function Release-Ref ($ref) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } $xlCellTypeLastCell = 11 $objExcel = new-object -comobject excel.application $objExcel.Visible = $True $objExcel.DisplayAlerts = $false $objWorkbook = $objExcel.Workbooks.Open('C:\Users\'+$env:USERNAME+'\Desktop\data.xlsx') $objWorksheet = $objWorkbook.Worksheets.Item('Sheet1') $a = $objWorksheet.Activate() $objRange = $objWorksheet.UsedRange $a = $objRange.SpecialCells($xlCellTypeLastCell).Activate() $intNewRow = $objExcel.ActiveCell.Row + 1 $strNewCell = "A" + $intNewRow Write-Host $strNewCell #------------------for each ------------------------------------------------------------------------------------ for ($i = 1; $i -le $intNewRow; $i++) { If ([string]::IsNullOrEmpty($objWorksheet.Cells.Item($i,1).value2)){ Write-Host "DELETING "$objWorksheet.Cells.Item($i, 1).Value2"Cell A"$i $Range = $objWorksheet.Cells.Item($i, 1).EntireRow $Range.Delete() $objWorkbook.Save() }else { Write-Host "NOT DELETING " $objWorksheet.Cells.Item($i, 1).Value2"Cell A"$i } } $objWorkbook.Save() $objWorkbook.Close() $objExcel.Quit() [gc]::collect() [gc]::WaitForPendingFinalizers()

excel template is here:

http s : / / drive google . c o m / open?id=1dTPgQN-gL_VqZXitzCusz5Or3quRt7Jz

could anyone help me to understand what the hell is happening please?

thanks , BR.



Running script elevation in background

$
0
0
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   # Exit from the current, unelevated, process
   exit
   }

# Run your code that needs to be elevated here
Get-AppXPackage -AllUsers -Name Microsoft.MicrosoftEdgeDevToolsPreview | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register “$($_.InstallLocation)\AppXManifest.xml” -Verbose}
Add-AppxPackage -register “C:\windows\SystemApps\Microsoft.MicrosoftEdgeDevToolsClient_8wekyb3d8bbwe\AppxManifest.xml” -DisableDevelopmentMode -Confirm:$false
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

#Can I add  powershell.exe -nologo -command  in place of   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";


GPO Computer Startup Script to copy a file from my NAS to my computer.

$
0
0

So I have a script that runs fine manually and does run when applied via gpo, but it does not work correctly when applied this way. It's suppose to copy a file from my NAS to my desktop. I've isolated the error down to this:

Copy-Item : Cannot find path 
'UNC Path' because it does not 
exist.

The path does exist and works fine when I fire the script manually. I've tried having the gpo wait for the network to be established but this did not work either. I'm stumped as to why this error is occurring and I'd appreciate any help!

Here is a copy of the script. It's very basic because it's a test script to try to isolate the issue.

$TEST_INSTALL="\\path_to_file\test.txt"
$TEST_FILE="C:\test.txt"
$INSTALLED_ALREADY=Test-Path $TEST_FILEif($INSTALLED_ALREADY -ne $true){Copy-Item-Path $TEST_INSTALL -Destination $TEST_FILE -Force2>>"C:\errors.txt"}else{Write-Host"Already Installed"exit}


Script to List all users from groups which got access to a windows share

$
0
0

Can some one please help with a Script to List all users from groups which got access to a windows share

Thanks in advance

Shinz


Start Program remotely

$
0
0

Hello

Some users are deliberately closing the skype for bussines.

I need a powershell command (if any), to start skype for bussines, if it is closed on the user's computer, or if the user has deliberately closed the program

I tried some features like invoking, but I did not succeed,

How can I do this?


MCP - MCTS - MCTS AD

PCSIDevice modules missing when running PS script from Visual Basic

$
0
0

Hi,

When running the PowerShell Get-Command from a Visual Basic program in a PowerShell runspace/pipeline, thePcsvDevice modules do not show up. When running the Get-Command from a normal PS box, these commands show up as expected. Is a solution available?

List all folders in all drives with sizes

$
0
0

I need to report all folders from all fixed drives with their sizes. I need to include files list and sizes as long as they are in the root drive. Also to include hidden files/folders.

Can you show a link or script for this?

Thank you,

How to Fetch "Member of" groups from particular user ?

$
0
0

Hi All,

Good day.

Please help me by giving exact command for To Fetch "Member of" groups from particular AD user ? 

Thanks in Advance

Viewing all 21975 articles
Browse latest View live


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